From 26105034da4fcce7ac883c899d781f016559310d Mon Sep 17 00:00:00 2001 From: ruki Date: Thu, 8 Nov 2018 00:38:48 +0800 Subject: switch to vuepress --- node_modules/koa/History.md | 482 ++++++++++++++ node_modules/koa/LICENSE | 22 + node_modules/koa/Readme.md | 311 +++++++++ node_modules/koa/lib/application.js | 244 +++++++ node_modules/koa/lib/context.js | 241 +++++++ node_modules/koa/lib/request.js | 727 +++++++++++++++++++++ node_modules/koa/lib/response.js | 558 ++++++++++++++++ node_modules/koa/node_modules/debug/.coveralls.yml | 1 + node_modules/koa/node_modules/debug/.eslintrc | 14 + node_modules/koa/node_modules/debug/.npmignore | 9 + node_modules/koa/node_modules/debug/.travis.yml | 20 + node_modules/koa/node_modules/debug/CHANGELOG.md | 395 +++++++++++ node_modules/koa/node_modules/debug/LICENSE | 19 + node_modules/koa/node_modules/debug/Makefile | 58 ++ node_modules/koa/node_modules/debug/README.md | 368 +++++++++++ node_modules/koa/node_modules/debug/karma.conf.js | 70 ++ node_modules/koa/node_modules/debug/node.js | 1 + node_modules/koa/node_modules/debug/package.json | 43 ++ node_modules/koa/node_modules/debug/src/browser.js | 195 ++++++ node_modules/koa/node_modules/debug/src/debug.js | 225 +++++++ node_modules/koa/node_modules/debug/src/index.js | 10 + node_modules/koa/node_modules/debug/src/node.js | 186 ++++++ .../koa/node_modules/koa-compose/History.md | 60 ++ .../koa/node_modules/koa-compose/Readme.md | 40 ++ node_modules/koa/node_modules/koa-compose/index.js | 48 ++ .../koa/node_modules/koa-compose/package.json | 30 + node_modules/koa/package.json | 76 +++ 27 files changed, 4453 insertions(+) create mode 100644 node_modules/koa/History.md create mode 100644 node_modules/koa/LICENSE create mode 100644 node_modules/koa/Readme.md create mode 100644 node_modules/koa/lib/application.js create mode 100644 node_modules/koa/lib/context.js create mode 100644 node_modules/koa/lib/request.js create mode 100644 node_modules/koa/lib/response.js create mode 100644 node_modules/koa/node_modules/debug/.coveralls.yml create mode 100644 node_modules/koa/node_modules/debug/.eslintrc create mode 100644 node_modules/koa/node_modules/debug/.npmignore create mode 100644 node_modules/koa/node_modules/debug/.travis.yml create mode 100644 node_modules/koa/node_modules/debug/CHANGELOG.md create mode 100644 node_modules/koa/node_modules/debug/LICENSE create mode 100644 node_modules/koa/node_modules/debug/Makefile create mode 100644 node_modules/koa/node_modules/debug/README.md create mode 100644 node_modules/koa/node_modules/debug/karma.conf.js create mode 100644 node_modules/koa/node_modules/debug/node.js create mode 100644 node_modules/koa/node_modules/debug/package.json create mode 100644 node_modules/koa/node_modules/debug/src/browser.js create mode 100644 node_modules/koa/node_modules/debug/src/debug.js create mode 100644 node_modules/koa/node_modules/debug/src/index.js create mode 100644 node_modules/koa/node_modules/debug/src/node.js create mode 100644 node_modules/koa/node_modules/koa-compose/History.md create mode 100644 node_modules/koa/node_modules/koa-compose/Readme.md create mode 100644 node_modules/koa/node_modules/koa-compose/index.js create mode 100644 node_modules/koa/node_modules/koa-compose/package.json create mode 100644 node_modules/koa/package.json (limited to 'node_modules/koa') diff --git a/node_modules/koa/History.md b/node_modules/koa/History.md new file mode 100644 index 00000000..80c67304 --- /dev/null +++ b/node_modules/koa/History.md @@ -0,0 +1,482 @@ + +2.6.1 / 2018-10-23 +================== + +**fixes** + * [[`4964242`](http://github.com/koajs/koa/commit/49642428342e5f291eb9d690802e83ed830623b5)] - fix: use X-Forwarded-Host first on app.proxy present (#1263) (fengmk2 <>) + +2.6.0 / 2018-10-23 +================== + +**features** + * [[`9c5c58b`](http://github.com/koajs/koa/commit/9c5c58b18363494976185e7ddc790ac63de840ed)] - feat: use :authority header of http2 requests as host (#1262) (Martin Michaelis <>) + * [[`9146024`](http://github.com/koajs/koa/commit/9146024e1094e8bb871ab15d1b7fc556a710732f)] - feat: response.attachment append a parameter: options from contentDisposition (#1240) (小雷 <<863837949@qq.com>>) + +**others** + * [[`d32623b`](http://github.com/koajs/koa/commit/d32623baa7a6273d47be67d587ad4ea0ecffc5de)] - docs: Update error-handling.md (#1239) (urugator <>) + +2.5.3 / 2018-09-11 +================== + +**fixes** + * [[`2ee32f5`](http://github.com/koajs/koa/commit/2ee32f50b88b383317e33cc0a4bfaa5f2eadead7)] - fix: pin debug@~3.1.0 avoid deprecated warnning (#1245) (fengmk2 <>) + +**others** + * [[`2180839`](http://github.com/koajs/koa/commit/2180839eda2cb16edcfda46ccfe24711680af850)] - docs: Update koa-vs-express.md (#1230) (Clayton Ray <>) + +2.5.2 / 2018-07-12 +================== + + * deps: upgrade all dependencies + * perf: avoid stringify when set header (#1220) + * perf: cache content type's result (#1218) + * perf: lazy init cookies and ip when first time use it (#1216) + * chore: fix comment & approve cov (#1214) + * docs: fix grammar + * test&cov: add test case (#1211) + * Lazily initialize `request.accept` and delegate `context.accept` (#1209) + * fix: use non deprecated custom inspect (#1198) + * Simplify processes in the getter `request.protocol` (#1203) + * docs: better demonstrate middleware flow (#1195) + * fix: Throw a TypeError instead of a AssertionError (#1199) + * chore: mistake in a comment (#1201) + * chore: use this.res.socket insteadof this.ctx.req.socket (#1177) + * chore: Using "listenerCount" instead of "listeners" (#1184) + +2.5.1 / 2018-04-27 +================== + + * test: node v10 on travis (#1182) + * fix tests: remove unnecessary assert doesNotThrow and api calls (#1170) + * use this.response insteadof this.ctx.response (#1163) + * deps: remove istanbul (#1151) + * Update guide.md (#1150) + +2.5.0 / 2018-02-11 +================== + + * feat: ignore set header/status when header sent (#1137) + * run coverage using --runInBand (#1141) + * [Update] license year to 2018 (#1130) + * docs: small grammatical fix in api docs index (#1111) + * docs: fixed typo (#1112) + * docs: capitalize K in word koa (#1126) + * Error handling: on non-error throw try to stringify if error is an object (#1113) + * Use eslint-config-koa (#1105) + * Update mgol's name in AUTHORS, add .mailmap (#1100) + * Avoid generating package locks instead of ignoring them (#1108) + * chore: update copyright year to 2017 (#1095) + + +2.4.1 / 2017-11-06 +================== + + * fix bad merge w/ 2.4.0 + +2.4.0 / 2017-11-06 +================== + +UNPUBLISHED + + * update `package.engines.node` to be more strict + * update `fresh@^0.5.2` + * fix: `inspect()` no longer crashes `context` + * fix: gated `res.statusMessage` for HTTP/2 + * added: `app.handleRequest()` is exposed + +2.3.0 / 2017-06-20 +================== + + * fix: use `Buffer.from()` + * test on node 7 & 8 + * add `package-lock.json` to `.gitignore` + * run `lint --fix` + * add `request.header` in addition to `request.headers` + * add IPv6 hostname support + +2.2.0 / 2017-03-14 +================== + + * fix: drop `package.engines.node` requirement to >= 6.0.0 + * this fixes `yarn`, which errors when this semver range is not satisfied + * bump `cookies@~0.7.0` + * bump `fresh@^0.5.0` + +2.1.0 / 2017-03-07 +================== + + * added: return middleware chain promise from `callback()` #848 + * added: node v7.7+ `res.getHeaderNames()` support #930 + * added: `err.headerSent` in error handling #919 + * added: lots of docs! + +2.0.1 / 2017-02-25 +================== + +NOTE: we hit a versioning snafu. `v2.0.0` was previously released, +so `v2.0.1` is released as the first `v2.x` with a `latest` tag. + + * upgrade mocha #900 + * add names to `application`'s request and response handlers #805 + * breaking: remove unused `app.name` #899 + * breaking: drop official support for node < 7.6 + +2.0.0 / ?????????? +================== + + * Fix malformed content-type header causing exception on charset get (#898) + * fix: subdomains should be [] if the host is an ip (#808) + * don't pre-bound onerror [breaking change] (#800) + * fix `ctx.flushHeaders()` to use `res.flushHeaders()` instead of `res.writeHead()` (#795) + * fix(response): correct response.writable logic (#782) + * merge v1.1.2 and v1.2.0 changes + * include `koa-convert` so that generator functions still work + * NOTE: generator functions are deprecated in v2 and will be removed in v3 + * improve linting + * improve docs + +2.0.0-alpha.8 / 2017-02-13 +================== + + * Fix malformed content-type header causing exception on charset get (#898) + +2.0.0-alpha.7 / 2016-09-07 +================== + + * fix: subdomains should be [] if the host is an ip (#808) + +2.0.0-alpha.6 / 2016-08-29 +================== + + * don't pre-bound onerror [breaking change] + +2.0.0-alpha.5 / 2016-08-10 +================== + + * fix `ctx.flushHeaders()` to use `res.flushHeaders()` instead of `res.writeHead()` + +2.0.0-alpha.4 / 2016-07-23 +================== + + * fix `response.writeable` during pipelined requests + +1.2.0 / 2016-03-03 +================== + + * add support for `err.headers` in `ctx.onerror()` + - see: https://github.com/koajs/koa/pull/668 + - note: you should set these headers in your custom error handlers as well + - docs: https://github.com/koajs/koa/blob/master/docs/error-handling.md + * fix `cookies`' detection of http/https + - see: https://github.com/koajs/koa/pull/614 + * deprecate `app.experimental = true`. Koa v2 does not use this signature. + * add a code of conduct + * test against the latest version of node + * add a lot of docs + +1.1.2 / 2015-11-05 +================== + + * ensure parseurl always working as expected + * fix Application.inspect() – missing .proxy value. + +2.0.0-alpha.3 / 2015-11-05 +================== + + * ensure parseurl always working as expected. #586 + * fix Application.inspect() – missing .proxy value. Closes #563 + +2.0.0-alpha.2 / 2015-10-27 +================== + + * remove `co` and generator support completely + * improved documentation + * more refactoring into ES6 + +2.0.0-alpha.1 / 2015-10-22 +================== + + * change the middleware signature to `async (ctx, next) => await next()` + * drop node < 4 support and rewrite the codebase in ES6 + +1.1.1 / 2015-10-22 +================== + + * do not send a content-type when the type is unknown #536 + +1.1.0 / 2015-10-11 +================== + + * add `app.silent=` to toggle error logging @tejasmanohar #486 + * add `ctx.origin` @chentsulin #480 + * various refactoring + - add `use strict` everywhere + +1.0.0 / 2015-08-22 +================== + + * add `this.req` check for `querystring()` + * don't log errors with `err.expose` + * `koa` now follows semver! + +0.21.0 / 2015-05-23 +================== + + * empty `request.query` objects are now always the same instance + * bump `fresh@0.3.0` + +0.20.0 / 2015-04-30 +================== + +Breaking change if you're using `this.get('ua') === undefined` etc. +For more details please checkout [#438](https://github.com/koajs/koa/pull/438). + + * make sure helpers return strict string + * feat: alias response.headers to response.header + +0.19.1 / 2015-04-14 +================== + + * non-error thrown, fixed #432 + +0.19.0 / 2015-04-05 +================== + + * `req.host` and `req.hostname` now always return a string (semi-breaking change) + * improved test coverage + +0.18.1 / 2015-03-01 +================== + + * move babel to `devDependencies` + +0.18.0 / 2015-02-14 +================== + + * experimental es7 async function support via `app.experimental = true` + * use `content-type` instead of `media-typer` + +0.17.0 / 2015-02-05 +================== + +Breaking change if you're using an old version of node v0.11! +Otherwise, you should have no trouble upgrading. + + * official iojs support + * drop support for node.js `>= 0.11.0 < 0.11.16` + * use `Object.setPrototypeOf()` instead of `__proto__` + * update dependencies + +0.16.0 / 2015-01-27 +================== + + * add `res.append()` + * fix path usage for node@0.11.15 + +0.15.0 / 2015-01-18 +================== + + * add `this.href` + +0.14.0 / 2014-12-15 +================== + + * remove `x-powered-by` response header + * fix the content type on plain-text redirects + * add ctx.state + * bump `co@4` + * bump dependencies + +0.13.0 / 2014-10-17 +================== + + * add this.message + * custom status support via `statuses` + +0.12.2 / 2014-09-28 +================== + + * use wider semver ranges for dependencies koa maintainers also maintain + +0.12.1 / 2014-09-21 +================== + + * bump content-disposition + * bump statuses + +0.12.0 / 2014-09-20 +================== + + * add this.assert() + * use content-disposition + +0.11.0 / 2014-09-08 +================== + + * fix app.use() assertion #337 + * bump a lot of dependencies + +0.10.0 / 2014-08-12 +================== + + * add `ctx.throw(err, object)` support + * add `ctx.throw(err, status, object)` support + +0.9.0 / 2014-08-07 +================== + + * add: do not set `err.expose` to true when err.status not a valid http status code + * add: alias `request.headers` as `request.header` + * add context.inspect(), cleanup app.inspect() + * update cookies + * fix `err.status` invalid lead to uncaughtException + * fix middleware gif, close #322 + +0.8.2 / 2014-07-27 +================== + + * bump co + * bump parseurl + +0.8.1 / 2014-06-24 +================== + + * bump type-is + +0.8.0 / 2014-06-13 +================== + + * add `this.response.is()`` + * remove `.status=string` and `res.statusString` #298 + +0.7.0 / 2014-06-07 +================== + + * add `this.lastModified` and `this.etag` as both getters and setters for ubiquity #292. + See koajs/koa@4065bf7 for an explanation. + * refactor `this.response.vary()` to use [vary](https://github.com/expressjs/vary) #291 + * remove `this.response.append()` #291 + +0.6.3 / 2014-06-06 +================== + + * fix res.type= when the extension is unknown + * assert when non-error is passed to app.onerror #287 + * bump finished + +0.6.2 / 2014-06-03 +================== + + * switch from set-type to mime-types + +0.6.1 / 2014-05-11 +================== + + * bump type-is + * bump koa-compose + +0.6.0 / 2014-05-01 +================== + + * add nicer error formatting + * add: assert object type in ctx.onerror + * change .status default to 404. Closes #263 + * remove .outputErrors, suppress output when handled by the dev. Closes #272 + * fix content-length when body is re-assigned. Closes #267 + +0.5.5 / 2014-04-14 +================== + + * fix length when .body is missing + * fix: make sure all intermediate stream bodies will be destroyed + +0.5.4 / 2014-04-12 +================== + + * fix header stripping in a few cases + +0.5.3 / 2014-04-09 +================== + + * change res.type= to always default charset. Closes #252 + * remove ctx.inspect() implementation. Closes #164 + +0.5.2 / 2014-03-23 +================== + + * fix: inspection of `app` and `app.toJSON()` + * fix: let `this.throw`n errors provide their own status + * fix: overwriting of `content-type` w/ `HEAD` requests + * refactor: use statuses + * refactor: use escape-html + * bump dev deps + +0.5.1 / 2014-03-06 +================== + + * add request.hostname(getter). Closes #224 + * remove response.charset and ctx.charset (too confusing in relation to ctx.type) [breaking change] + * fix a debug() name + +0.5.0 / 2014-02-19 +================== + + * add context.charset + * add context.charset= + * add request.charset + * add response.charset + * add response.charset= + * fix response.body= html content sniffing + * change ctx.length and ctx.type to always delegate to response object [breaking change] + +0.4.0 / 2014-02-11 +================== + + * remove app.jsonSpaces settings - moved to [koa-json](https://github.com/koajs/json) + * add this.response=false to bypass koa's response handling + * fix response handling after body has been sent + * changed ctx.throw() to no longer .expose 5xx errors + * remove app.keys getter/setter, update cookies, and remove keygrip deps + * update fresh + * update koa-compose + +0.3.0 / 2014-01-17 +================== + + * add ctx.host= delegate + * add req.host= + * add: context.throw supports Error instances + * update co + * update cookies + +0.2.1 / 2013-12-30 +================== + + * add better 404 handling + * add check for fn._name in debug() output + * add explicit .toJSON() calls to ctx.toJSON() + +0.2.0 / 2013-12-28 +================== + + * add support for .throw(status, msg). Closes #130 + * add GeneratorFunction assertion for app.use(). Closes #120 + * refactor: move `.is()` to `type-is` + * refactor: move content negotiation to "accepts" + * refactor: allow any streams with .pipe method + * remove `next` in callback for now + +0.1.2 / 2013-12-21 +================== + + * update co, koa-compose, keygrip + * use on-socket-error + * add throw(status, msg) support + * assert middleware is GeneratorFunction + * ducktype stream checks + * remove `next` is `app.callback()` + +0.1.1 / 2013-12-19 +================== + + * fix: cleanup socker error handler on response diff --git a/node_modules/koa/LICENSE b/node_modules/koa/LICENSE new file mode 100644 index 00000000..67c8f12b --- /dev/null +++ b/node_modules/koa/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2018 Koa 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/node_modules/koa/Readme.md b/node_modules/koa/Readme.md new file mode 100644 index 00000000..c352d009 --- /dev/null +++ b/node_modules/koa/Readme.md @@ -0,0 +1,311 @@ +Koa middleware framework for nodejs + + [![gitter][gitter-image]][gitter-url] + [![NPM version][npm-image]][npm-url] + [![build status][travis-image]][travis-url] + [![Test coverage][coveralls-image]][coveralls-url] + [![OpenCollective Backers][backers-image]](#backers) + [![OpenCollective Sponsors][sponsors-image]](#sponsors) + + Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream. + + Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. This + includes things like content negotiation, normalization of node inconsistencies, redirection, and a few others. + + Koa is not bundled with any middleware. + +## Installation + +Koa requires __node v7.6.0__ or higher for ES2015 and async function support. + +``` +$ npm install koa +``` + +## Hello Koa + +```js +const Koa = require('koa'); +const app = new Koa(); + +// response +app.use(ctx => { + ctx.body = 'Hello Koa'; +}); + +app.listen(3000); +``` + +## Getting started + + - [Kick-Off-Koa](https://github.com/koajs/kick-off-koa) - An intro to Koa via a set of self-guided workshops. + - [Workshop](https://github.com/koajs/workshop) - A workshop to learn the basics of Koa, Express' spiritual successor. + - [Introduction Screencast](http://knowthen.com/episode-3-koajs-quickstart-guide/) - An introduction to installing and getting started with Koa + + +## Middleware + +Koa is a middleware framework that can take two different kinds of functions as middleware: + + * async function + * common function + +Here is an example of logger middleware with each of the different functions: + +### ___async___ functions (node v7.6+) + +```js +app.use(async (ctx, next) => { + const start = Date.now(); + await next(); + const ms = Date.now() - start; + console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); +}); +``` + +### Common function + +```js +// Middleware normally takes two parameters (ctx, next), ctx is the context for one request, +// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion. + +app.use((ctx, next) => { + const start = Date.now(); + return next().then(() => { + const ms = Date.now() - start; + console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); + }); +}); +``` + +### Koa v1.x Middleware Signature + +The middleware signature changed between v1.x and v2.x. The older signature is deprecated. + +**Old signature middleware support will be removed in v3** + +Please see the [Migration Guide](docs/migration.md) for more information on upgrading from v1.x and +using v1.x middleware with v2.x. + +## Context, Request and Response + +Each middleware receives a Koa `Context` object that encapsulates an incoming +http message and the corresponding response to that message. `ctx` is often used +as the parameter name for the context object. + +```js +app.use(async (ctx, next) => { await next(); }); +``` + +Koa provides a `Request` object as the `request` property of the `Context`. +Koa's `Request` object provides helpful methods for working with +http requests which delegate to an [IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage) +from the node `http` module. + +Here is an example of checking that a requesting client supports xml. + +```js +app.use(async (ctx, next) => { + ctx.assert(ctx.request.accepts('xml'), 406); + // equivalent to: + // if (!ctx.request.accepts('xml')) ctx.throw(406); + await next(); +}); +``` + +Koa provides a `Response` object as the `response` property of the `Context`. +Koa's `Response` object provides helpful methods for working with +http responses which delegate to a [ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) +. + +Koa's pattern of delegating to Node's request and response objects rather than extending them +provides a cleaner interface and reduces conflicts between different middleware and with Node +itself as well as providing better support for stream handling. The `IncomingMessage` can still be +directly accessed as the `req` property on the `Context` and `ServerResponse` can be directly +accessed as the `res` property on the `Context`. + +Here is an example using Koa's `Response` object to stream a file as the response body. + +```js +app.use(async (ctx, next) => { + await next(); + ctx.response.type = 'xml'; + ctx.response.body = fs.createReadStream('really_large.xml'); +}); +``` + +The `Context` object also provides shortcuts for methods on its `request` and `response`. In the prior +examples, `ctx.type` can be used instead of `ctx.request.type` and `ctx.accepts` can be used +instead of `ctx.request.accepts`. + +For more information on `Request`, `Response` and `Context`, see the [Request API Reference](docs/api/request.md), +[Response API Reference](docs/api/response.md) and [Context API Reference](docs/api/context.md). + +## Koa Application + +The object created when executing `new Koa()` is known as the Koa application object. + +The application object is Koa's interface with node's http server and handles the registration +of middleware, dispatching to the middleware from http, default error handling, as well as +configuration of the context, request and response objects. + +Learn more about the application object in the [Application API Reference](docs/api/index.md). + +## Documentation + + - [Usage Guide](docs/guide.md) + - [Error Handling](docs/error-handling.md) + - [Koa for Express Users](docs/koa-vs-express.md) + - [FAQ](docs/faq.md) + - [API documentation](docs/api/index.md) + +## Babel setup + +If you're not using `node v7.6+`, we recommend setting up `babel` with [`babel-preset-env`](https://github.com/babel/babel-preset-env): + +```bash +$ npm install babel-register babel-preset-env --save +``` + +Setup `babel-register` in your entry file: + +```js +require('babel-register'); +``` + +And have your `.babelrc` setup: + +```json +{ + "presets": [ + ["env", { + "targets": { + "node": true + } + }] + ] +} +``` + +## Troubleshooting + +Check the [Troubleshooting Guide](docs/troubleshooting.md) or [Debugging Koa](docs/guide.md#debugging-koa) in +the general Koa guide. + +## Running tests + +``` +$ npm test +``` + +## Authors + +See [AUTHORS](AUTHORS). + +## Community + + - [Badgeboard](https://koajs.github.io/badgeboard) and list of official modules + - [Examples](https://github.com/koajs/examples) + - [Middleware](https://github.com/koajs/koa/wiki) list + - [Wiki](https://github.com/koajs/koa/wiki) + - [G+ Community](https://plus.google.com/communities/101845768320796750641) + - [Reddit Community](https://www.reddit.com/r/koajs) + - [Mailing list](https://groups.google.com/forum/#!forum/koajs) + - [中文文档 v1.x](https://github.com/guo-yu/koa-guide) + - [中文文档 v2.x](https://github.com/demopark/koa-docs-Zh-CN) + - __[#koajs]__ on freenode + +## Job Board + +Looking for a career upgrade? + + + + + +## Backers + +Support us with a monthly donation and help us continue our activities. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# License + + MIT + +[npm-image]: https://img.shields.io/npm/v/koa.svg?style=flat-square +[npm-url]: https://www.npmjs.com/package/koa +[travis-image]: https://img.shields.io/travis/koajs/koa/master.svg?style=flat-square +[travis-url]: https://travis-ci.org/koajs/koa +[coveralls-image]: https://img.shields.io/codecov/c/github/koajs/koa.svg?style=flat-square +[coveralls-url]: https://codecov.io/github/koajs/koa?branch=master +[backers-image]: https://opencollective.com/koajs/backers/badge.svg?style=flat-square +[sponsors-image]: https://opencollective.com/koajs/sponsors/badge.svg?style=flat-square +[gitter-image]: https://img.shields.io/gitter/room/koajs/koa.svg?style=flat-square +[gitter-url]: https://gitter.im/koajs/koa?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[#koajs]: https://webchat.freenode.net/?channels=#koajs diff --git a/node_modules/koa/lib/application.js b/node_modules/koa/lib/application.js new file mode 100644 index 00000000..84107cb6 --- /dev/null +++ b/node_modules/koa/lib/application.js @@ -0,0 +1,244 @@ + +'use strict'; + +/** + * Module dependencies. + */ + +const isGeneratorFunction = require('is-generator-function'); +const debug = require('debug')('koa:application'); +const onFinished = require('on-finished'); +const response = require('./response'); +const compose = require('koa-compose'); +const isJSON = require('koa-is-json'); +const context = require('./context'); +const request = require('./request'); +const statuses = require('statuses'); +const Emitter = require('events'); +const util = require('util'); +const Stream = require('stream'); +const http = require('http'); +const only = require('only'); +const convert = require('koa-convert'); +const deprecate = require('depd')('koa'); + +/** + * Expose `Application` class. + * Inherits from `Emitter.prototype`. + */ + +module.exports = class Application extends Emitter { + /** + * Initialize a new `Application`. + * + * @api public + */ + + constructor() { + super(); + + this.proxy = false; + this.middleware = []; + this.subdomainOffset = 2; + this.env = process.env.NODE_ENV || 'development'; + this.context = Object.create(context); + this.request = Object.create(request); + this.response = Object.create(response); + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + } + + /** + * Shorthand for: + * + * http.createServer(app.callback()).listen(...) + * + * @param {Mixed} ... + * @return {Server} + * @api public + */ + + listen(...args) { + debug('listen'); + const server = http.createServer(this.callback()); + return server.listen(...args); + } + + /** + * Return JSON representation. + * We only bother showing settings. + * + * @return {Object} + * @api public + */ + + toJSON() { + return only(this, [ + 'subdomainOffset', + 'proxy', + 'env' + ]); + } + + /** + * Inspect implementation. + * + * @return {Object} + * @api public + */ + + inspect() { + return this.toJSON(); + } + + /** + * Use the given middleware `fn`. + * + * Old-style middleware will be converted. + * + * @param {Function} fn + * @return {Application} self + * @api public + */ + + use(fn) { + if (typeof fn !== 'function') throw new TypeError('middleware must be a function!'); + if (isGeneratorFunction(fn)) { + deprecate('Support for generators will be removed in v3. ' + + 'See the documentation for examples of how to convert old middleware ' + + 'https://github.com/koajs/koa/blob/master/docs/migration.md'); + fn = convert(fn); + } + debug('use %s', fn._name || fn.name || '-'); + this.middleware.push(fn); + return this; + } + + /** + * Return a request handler callback + * for node's native http server. + * + * @return {Function} + * @api public + */ + + callback() { + const fn = compose(this.middleware); + + if (!this.listenerCount('error')) this.on('error', this.onerror); + + const handleRequest = (req, res) => { + const ctx = this.createContext(req, res); + return this.handleRequest(ctx, fn); + }; + + return handleRequest; + } + + /** + * Handle request in callback. + * + * @api private + */ + + handleRequest(ctx, fnMiddleware) { + const res = ctx.res; + res.statusCode = 404; + const onerror = err => ctx.onerror(err); + const handleResponse = () => respond(ctx); + onFinished(res, onerror); + return fnMiddleware(ctx).then(handleResponse).catch(onerror); + } + + /** + * Initialize a new context. + * + * @api private + */ + + createContext(req, res) { + const context = Object.create(this.context); + const request = context.request = Object.create(this.request); + const response = context.response = Object.create(this.response); + context.app = request.app = response.app = this; + context.req = request.req = response.req = req; + context.res = request.res = response.res = res; + request.ctx = response.ctx = context; + request.response = response; + response.request = request; + context.originalUrl = request.originalUrl = req.url; + context.state = {}; + return context; + } + + /** + * Default error handler. + * + * @param {Error} err + * @api private + */ + + onerror(err) { + if (!(err instanceof Error)) throw new TypeError(util.format('non-error thrown: %j', err)); + + if (404 == err.status || err.expose) return; + if (this.silent) return; + + const msg = err.stack || err.toString(); + console.error(); + console.error(msg.replace(/^/gm, ' ')); + console.error(); + } +}; + +/** + * Response helper. + */ + +function respond(ctx) { + // allow bypassing koa + if (false === ctx.respond) return; + + const res = ctx.res; + if (!ctx.writable) return; + + let body = ctx.body; + const code = ctx.status; + + // ignore body + if (statuses.empty[code]) { + // strip headers + ctx.body = null; + return res.end(); + } + + if ('HEAD' == ctx.method) { + if (!res.headersSent && isJSON(body)) { + ctx.length = Buffer.byteLength(JSON.stringify(body)); + } + return res.end(); + } + + // status body + if (null == body) { + body = ctx.message || String(code); + if (!res.headersSent) { + ctx.type = 'text'; + ctx.length = Buffer.byteLength(body); + } + return res.end(body); + } + + // responses + if (Buffer.isBuffer(body)) return res.end(body); + if ('string' == typeof body) return res.end(body); + if (body instanceof Stream) return body.pipe(res); + + // body: json + body = JSON.stringify(body); + if (!res.headersSent) { + ctx.length = Buffer.byteLength(body); + } + res.end(body); +} diff --git a/node_modules/koa/lib/context.js b/node_modules/koa/lib/context.js new file mode 100644 index 00000000..1b92f018 --- /dev/null +++ b/node_modules/koa/lib/context.js @@ -0,0 +1,241 @@ + +'use strict'; + +/** + * Module dependencies. + */ + +const util = require('util'); +const createError = require('http-errors'); +const httpAssert = require('http-assert'); +const delegate = require('delegates'); +const statuses = require('statuses'); +const Cookies = require('cookies'); + +const COOKIES = Symbol('context#cookies'); + +/** + * Context prototype. + */ + +const proto = module.exports = { + + /** + * util.inspect() implementation, which + * just returns the JSON output. + * + * @return {Object} + * @api public + */ + + inspect() { + if (this === proto) return this; + return this.toJSON(); + }, + + /** + * Return JSON representation. + * + * Here we explicitly invoke .toJSON() on each + * object, as iteration will otherwise fail due + * to the getters and cause utilities such as + * clone() to fail. + * + * @return {Object} + * @api public + */ + + toJSON() { + return { + request: this.request.toJSON(), + response: this.response.toJSON(), + app: this.app.toJSON(), + originalUrl: this.originalUrl, + req: '', + res: '', + socket: '' + }; + }, + + /** + * Similar to .throw(), adds assertion. + * + * this.assert(this.user, 401, 'Please login!'); + * + * See: https://github.com/jshttp/http-assert + * + * @param {Mixed} test + * @param {Number} status + * @param {String} message + * @api public + */ + + assert: httpAssert, + + /** + * Throw an error with `msg` and optional `status` + * defaulting to 500. Note that these are user-level + * errors, and the message may be exposed to the client. + * + * this.throw(403) + * this.throw('name required', 400) + * this.throw(400, 'name required') + * this.throw('something exploded') + * this.throw(new Error('invalid'), 400); + * this.throw(400, new Error('invalid')); + * + * See: https://github.com/jshttp/http-errors + * + * @param {String|Number|Error} err, msg or status + * @param {String|Number|Error} [err, msg or status] + * @param {Object} [props] + * @api public + */ + + throw(...args) { + throw createError(...args); + }, + + /** + * Default error handling. + * + * @param {Error} err + * @api private + */ + + onerror(err) { + // don't do anything if there is no error. + // this allows you to pass `this.onerror` + // to node-style callbacks. + if (null == err) return; + + if (!(err instanceof Error)) err = new Error(util.format('non-error thrown: %j', err)); + + let headerSent = false; + if (this.headerSent || !this.writable) { + headerSent = err.headerSent = true; + } + + // delegate + this.app.emit('error', err, this); + + // nothing we can do here other + // than delegate to the app-level + // handler and log. + if (headerSent) { + return; + } + + const { res } = this; + + // first unset all headers + /* istanbul ignore else */ + if (typeof res.getHeaderNames === 'function') { + res.getHeaderNames().forEach(name => res.removeHeader(name)); + } else { + res._headers = {}; // Node < 7.7 + } + + // then set those specified + this.set(err.headers); + + // force text/plain + this.type = 'text'; + + // ENOENT support + if ('ENOENT' == err.code) err.status = 404; + + // default to 500 + if ('number' != typeof err.status || !statuses[err.status]) err.status = 500; + + // respond + const code = statuses[err.status]; + const msg = err.expose ? err.message : code; + this.status = err.status; + this.length = Buffer.byteLength(msg); + this.res.end(msg); + }, + + get cookies() { + if (!this[COOKIES]) { + this[COOKIES] = new Cookies(this.req, this.res, { + keys: this.app.keys, + secure: this.request.secure + }); + } + return this[COOKIES]; + }, + + set cookies(_cookies) { + this[COOKIES] = _cookies; + } +}; + +/** + * Custom inspection implementation for newer Node.js versions. + * + * @return {Object} + * @api public + */ + +/* istanbul ignore else */ +if (util.inspect.custom) { + module.exports[util.inspect.custom] = module.exports.inspect; +} + +/** + * Response delegation. + */ + +delegate(proto, 'response') + .method('attachment') + .method('redirect') + .method('remove') + .method('vary') + .method('set') + .method('append') + .method('flushHeaders') + .access('status') + .access('message') + .access('body') + .access('length') + .access('type') + .access('lastModified') + .access('etag') + .getter('headerSent') + .getter('writable'); + +/** + * Request delegation. + */ + +delegate(proto, 'request') + .method('acceptsLanguages') + .method('acceptsEncodings') + .method('acceptsCharsets') + .method('accepts') + .method('get') + .method('is') + .access('querystring') + .access('idempotent') + .access('socket') + .access('search') + .access('method') + .access('query') + .access('path') + .access('url') + .access('accept') + .getter('origin') + .getter('href') + .getter('subdomains') + .getter('protocol') + .getter('host') + .getter('hostname') + .getter('URL') + .getter('header') + .getter('headers') + .getter('secure') + .getter('stale') + .getter('fresh') + .getter('ips') + .getter('ip'); diff --git a/node_modules/koa/lib/request.js b/node_modules/koa/lib/request.js new file mode 100644 index 00000000..0b0b2625 --- /dev/null +++ b/node_modules/koa/lib/request.js @@ -0,0 +1,727 @@ + +'use strict'; + +/** + * Module dependencies. + */ + +const URL = require('url').URL; +const net = require('net'); +const accepts = require('accepts'); +const contentType = require('content-type'); +const stringify = require('url').format; +const parse = require('parseurl'); +const qs = require('querystring'); +const typeis = require('type-is'); +const fresh = require('fresh'); +const only = require('only'); +const util = require('util'); + +const IP = Symbol('context#ip'); + +/** + * Prototype. + */ + +module.exports = { + + /** + * Return request header. + * + * @return {Object} + * @api public + */ + + get header() { + return this.req.headers; + }, + + /** + * Set request header. + * + * @api public + */ + + set header(val) { + this.req.headers = val; + }, + + /** + * Return request header, alias as request.header + * + * @return {Object} + * @api public + */ + + get headers() { + return this.req.headers; + }, + + /** + * Set request header, alias as request.header + * + * @api public + */ + + set headers(val) { + this.req.headers = val; + }, + + /** + * Get request URL. + * + * @return {String} + * @api public + */ + + get url() { + return this.req.url; + }, + + /** + * Set request URL. + * + * @api public + */ + + set url(val) { + this.req.url = val; + }, + + /** + * Get origin of URL. + * + * @return {String} + * @api public + */ + + get origin() { + return `${this.protocol}://${this.host}`; + }, + + /** + * Get full request URL. + * + * @return {String} + * @api public + */ + + get href() { + // support: `GET http://example.com/foo` + if (/^https?:\/\//i.test(this.originalUrl)) return this.originalUrl; + return this.origin + this.originalUrl; + }, + + /** + * Get request method. + * + * @return {String} + * @api public + */ + + get method() { + return this.req.method; + }, + + /** + * Set request method. + * + * @param {String} val + * @api public + */ + + set method(val) { + this.req.method = val; + }, + + /** + * Get request pathname. + * + * @return {String} + * @api public + */ + + get path() { + return parse(this.req).pathname; + }, + + /** + * Set pathname, retaining the query-string when present. + * + * @param {String} path + * @api public + */ + + set path(path) { + const url = parse(this.req); + if (url.pathname === path) return; + + url.pathname = path; + url.path = null; + + this.url = stringify(url); + }, + + /** + * Get parsed query-string. + * + * @return {Object} + * @api public + */ + + get query() { + const str = this.querystring; + const c = this._querycache = this._querycache || {}; + return c[str] || (c[str] = qs.parse(str)); + }, + + /** + * Set query-string as an object. + * + * @param {Object} obj + * @api public + */ + + set query(obj) { + this.querystring = qs.stringify(obj); + }, + + /** + * Get query string. + * + * @return {String} + * @api public + */ + + get querystring() { + if (!this.req) return ''; + return parse(this.req).query || ''; + }, + + /** + * Set querystring. + * + * @param {String} str + * @api public + */ + + set querystring(str) { + const url = parse(this.req); + if (url.search === `?${str}`) return; + + url.search = str; + url.path = null; + + this.url = stringify(url); + }, + + /** + * Get the search string. Same as the querystring + * except it includes the leading ?. + * + * @return {String} + * @api public + */ + + get search() { + if (!this.querystring) return ''; + return `?${this.querystring}`; + }, + + /** + * Set the search string. Same as + * request.querystring= but included for ubiquity. + * + * @param {String} str + * @api public + */ + + set search(str) { + this.querystring = str; + }, + + /** + * Parse the "Host" header field host + * and support X-Forwarded-Host when a + * proxy is enabled. + * + * @return {String} hostname:port + * @api public + */ + + get host() { + const proxy = this.app.proxy; + let host = proxy && this.get('X-Forwarded-Host'); + if (!host) { + if (this.req.httpVersionMajor >= 2) host = this.get(':authority'); + if (!host) host = this.get('Host'); + } + if (!host) return ''; + return host.split(/\s*,\s*/)[0]; + }, + + /** + * Parse the "Host" header field hostname + * and support X-Forwarded-Host when a + * proxy is enabled. + * + * @return {String} hostname + * @api public + */ + + get hostname() { + const host = this.host; + if (!host) return ''; + if ('[' == host[0]) return this.URL.hostname || ''; // IPv6 + return host.split(':')[0]; + }, + + /** + * Get WHATWG parsed URL. + * Lazily memoized. + * + * @return {URL|Object} + * @api public + */ + + get URL() { + /* istanbul ignore else */ + if (!this.memoizedURL) { + const protocol = this.protocol; + const host = this.host; + const originalUrl = this.originalUrl || ''; // avoid undefined in template string + try { + this.memoizedURL = new URL(`${protocol}://${host}${originalUrl}`); + } catch (err) { + this.memoizedURL = Object.create(null); + } + } + return this.memoizedURL; + }, + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @api public + */ + + get fresh() { + const method = this.method; + const s = this.ctx.status; + + // 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.header, this.response.header); + } + + return false; + }, + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @api public + */ + + get stale() { + return !this.fresh; + }, + + /** + * Check if the request is idempotent. + * + * @return {Boolean} + * @api public + */ + + get idempotent() { + const methods = ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE']; + return !!~methods.indexOf(this.method); + }, + + /** + * Return the request socket. + * + * @return {Connection} + * @api public + */ + + get socket() { + return this.req.socket; + }, + + /** + * Get the charset when present or undefined. + * + * @return {String} + * @api public + */ + + get charset() { + let type = this.get('Content-Type'); + if (!type) return ''; + + try { + type = contentType.parse(type); + } catch (e) { + return ''; + } + + return type.parameters.charset || ''; + }, + + /** + * Return parsed Content-Length when present. + * + * @return {Number} + * @api public + */ + + get length() { + const len = this.get('Content-Length'); + if (len == '') return; + return ~~len; + }, + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the proxy setting + * is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + * + * @return {String} + * @api public + */ + + get protocol() { + if (this.socket.encrypted) return 'https'; + if (!this.app.proxy) return 'http'; + const proto = this.get('X-Forwarded-Proto'); + return proto ? proto.split(/\s*,\s*/)[0] : 'http'; + }, + + /** + * Short-hand for: + * + * this.protocol == 'https' + * + * @return {Boolean} + * @api public + */ + + get secure() { + return 'https' == this.protocol; + }, + + /** + * When `app.proxy` is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + * + * @return {Array} + * @api public + */ + + get ips() { + const proxy = this.app.proxy; + const val = this.get('X-Forwarded-For'); + return proxy && val + ? val.split(/\s*,\s*/) + : []; + }, + + /** + * Return request's remote address + * When `app.proxy` is `true`, parse + * the "X-Forwarded-For" ip address list and return the first one + * + * @return {String} + * @api public + */ + + get ip() { + if (!this[IP]) { + this[IP] = this.ips[0] || this.socket.remoteAddress || ''; + } + return this[IP]; + }, + + set ip(_ip) { + this[IP] = _ip; + }, + + /** + * 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 `app.subdomainOffset`. + * + * For example, if the domain is "tobi.ferrets.example.com": + * If `app.subdomainOffset` is not set, this.subdomains is + * `["ferrets", "tobi"]`. + * If `app.subdomainOffset` is 3, this.subdomains is `["tobi"]`. + * + * @return {Array} + * @api public + */ + + get subdomains() { + const offset = this.app.subdomainOffset; + const hostname = this.hostname; + if (net.isIP(hostname)) return []; + return hostname + .split('.') + .reverse() + .slice(offset); + }, + + /** + * Get accept object. + * Lazily memoized. + * + * @return {Object} + * @api private + */ + get accept() { + return this._accept || (this._accept = accepts(this.req)); + }, + + /** + * Set accept object. + * + * @param {Object} + * @api private + */ + set accept(obj) { + return this._accept = obj; + }, + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `false`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.accepts('html'); + * // => "html" + * this.accepts('text/html'); + * // => "text/html" + * this.accepts('json', 'text'); + * // => "json" + * this.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.accepts('image/png'); + * this.accepts('png'); + * // => false + * + * // Accept: text/*;q=.5, application/json + * this.accepts(['html', 'json']); + * this.accepts('html', 'json'); + * // => "json" + * + * @param {String|Array} type(s)... + * @return {String|Array|false} + * @api public + */ + + accepts(...args) { + return this.accept.types(...args); + }, + + /** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encoding(s)... + * @return {String|Array} + * @api public + */ + + acceptsEncodings(...args) { + return this.accept.encodings(...args); + }, + + /** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charset(s)... + * @return {String|Array} + * @api public + */ + + acceptsCharsets(...args) { + return this.accept.charsets(...args); + }, + + /** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} lang(s)... + * @return {Array|String} + * @api public + */ + + acceptsLanguages(...args) { + return this.accept.languages(...args); + }, + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @api public + */ + + is(types) { + if (!types) return typeis(this.req); + if (!Array.isArray(types)) types = [].slice.call(arguments); + return typeis(this.req, types); + }, + + /** + * Return the request mime type void of + * parameters such as "charset". + * + * @return {String} + * @api public + */ + + get type() { + const type = this.get('Content-Type'); + if (!type) return ''; + return type.split(';')[0]; + }, + + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * this.get('Content-Type'); + * // => "text/plain" + * + * this.get('content-type'); + * // => "text/plain" + * + * this.get('Something'); + * // => '' + * + * @param {String} field + * @return {String} + * @api public + */ + + get(field) { + const req = this.req; + switch (field = field.toLowerCase()) { + case 'referer': + case 'referrer': + return req.headers.referrer || req.headers.referer || ''; + default: + return req.headers[field] || ''; + } + }, + + /** + * Inspect implementation. + * + * @return {Object} + * @api public + */ + + inspect() { + if (!this.req) return; + return this.toJSON(); + }, + + /** + * Return JSON representation. + * + * @return {Object} + * @api public + */ + + toJSON() { + return only(this, [ + 'method', + 'url', + 'header' + ]); + } +}; + +/** + * Custom inspection implementation for newer Node.js versions. + * + * @return {Object} + * @api public + */ + +/* istanbul ignore else */ +if (util.inspect.custom) { + module.exports[util.inspect.custom] = module.exports.inspect; +} diff --git a/node_modules/koa/lib/response.js b/node_modules/koa/lib/response.js new file mode 100644 index 00000000..371875fe --- /dev/null +++ b/node_modules/koa/lib/response.js @@ -0,0 +1,558 @@ + +'use strict'; + +/** + * Module dependencies. + */ + +const contentDisposition = require('content-disposition'); +const ensureErrorHandler = require('error-inject'); +const getType = require('cache-content-type'); +const onFinish = require('on-finished'); +const isJSON = require('koa-is-json'); +const escape = require('escape-html'); +const typeis = require('type-is').is; +const statuses = require('statuses'); +const destroy = require('destroy'); +const assert = require('assert'); +const extname = require('path').extname; +const vary = require('vary'); +const only = require('only'); +const util = require('util'); + +/** + * Prototype. + */ + +module.exports = { + + /** + * Return the request socket. + * + * @return {Connection} + * @api public + */ + + get socket() { + return this.res.socket; + }, + + /** + * Return response header. + * + * @return {Object} + * @api public + */ + + get header() { + const { res } = this; + return typeof res.getHeaders === 'function' + ? res.getHeaders() + : res._headers || {}; // Node < 7.7 + }, + + /** + * Return response header, alias as response.header + * + * @return {Object} + * @api public + */ + + get headers() { + return this.header; + }, + + /** + * Get response status code. + * + * @return {Number} + * @api public + */ + + get status() { + return this.res.statusCode; + }, + + /** + * Set response status code. + * + * @param {Number} code + * @api public + */ + + set status(code) { + if (this.headerSent) return; + + assert('number' == typeof code, 'status code must be a number'); + assert(statuses[code], `invalid status code: ${code}`); + this._explicitStatus = true; + this.res.statusCode = code; + if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code]; + if (this.body && statuses.empty[code]) this.body = null; + }, + + /** + * Get response status message + * + * @return {String} + * @api public + */ + + get message() { + return this.res.statusMessage || statuses[this.status]; + }, + + /** + * Set response status message + * + * @param {String} msg + * @api public + */ + + set message(msg) { + this.res.statusMessage = msg; + }, + + /** + * Get response body. + * + * @return {Mixed} + * @api public + */ + + get body() { + return this._body; + }, + + /** + * Set response body. + * + * @param {String|Buffer|Object|Stream} val + * @api public + */ + + set body(val) { + const original = this._body; + this._body = val; + + // no content + if (null == val) { + if (!statuses.empty[this.status]) this.status = 204; + this.remove('Content-Type'); + this.remove('Content-Length'); + this.remove('Transfer-Encoding'); + return; + } + + // set the status + if (!this._explicitStatus) this.status = 200; + + // set the content-type only if not yet set + const setType = !this.header['content-type']; + + // string + if ('string' == typeof val) { + if (setType) this.type = /^\s* this.ctx.onerror(err)); + + // overwriting + if (null != original && original != val) this.remove('Content-Length'); + + if (setType) this.type = 'bin'; + return; + } + + // json + this.remove('Content-Length'); + this.type = 'json'; + }, + + /** + * Set Content-Length field to `n`. + * + * @param {Number} n + * @api public + */ + + set length(n) { + this.set('Content-Length', n); + }, + + /** + * Return parsed response Content-Length when present. + * + * @return {Number} + * @api public + */ + + get length() { + const len = this.header['content-length']; + const body = this.body; + + if (null == len) { + if (!body) return; + if ('string' == typeof body) return Buffer.byteLength(body); + if (Buffer.isBuffer(body)) return body.length; + if (isJSON(body)) return Buffer.byteLength(JSON.stringify(body)); + return; + } + + return ~~len; + }, + + /** + * Check if a header has been written to the socket. + * + * @return {Boolean} + * @api public + */ + + get headerSent() { + return this.res.headersSent; + }, + + /** + * Vary on `field`. + * + * @param {String} field + * @api public + */ + + vary(field) { + if (this.headerSent) return; + + vary(this.res, field); + }, + + /** + * Perform a 302 redirect to `url`. + * + * The string "back" is special-cased + * to provide Referrer support, when Referrer + * is not present `alt` or "/" is used. + * + * Examples: + * + * this.redirect('back'); + * this.redirect('back', '/index.html'); + * this.redirect('/login'); + * this.redirect('http://google.com'); + * + * @param {String} url + * @param {String} [alt] + * @api public + */ + + redirect(url, alt) { + // location + if ('back' == url) url = this.ctx.get('Referrer') || alt || '/'; + this.set('Location', url); + + // status + if (!statuses.redirect[this.status]) this.status = 302; + + // html + if (this.ctx.accepts('html')) { + url = escape(url); + this.type = 'text/html; charset=utf-8'; + this.body = `Redirecting to ${url}.`; + return; + } + + // text + this.type = 'text/plain; charset=utf-8'; + this.body = `Redirecting to ${url}.`; + }, + + /** + * Set Content-Disposition header to "attachment" with optional `filename`. + * + * @param {String} filename + * @api public + */ + + attachment(filename, options) { + if (filename) this.type = extname(filename); + this.set('Content-Disposition', contentDisposition(filename, options)); + }, + + /** + * Set Content-Type response header with `type` through `mime.lookup()` + * when it does not contain a charset. + * + * Examples: + * + * this.type = '.html'; + * this.type = 'html'; + * this.type = 'json'; + * this.type = 'application/json'; + * this.type = 'png'; + * + * @param {String} type + * @api public + */ + + set type(type) { + type = getType(type); + if (type) { + this.set('Content-Type', type); + } else { + this.remove('Content-Type'); + } + }, + + /** + * Set the Last-Modified date using a string or a Date. + * + * this.response.lastModified = new Date(); + * this.response.lastModified = '2013-09-13'; + * + * @param {String|Date} type + * @api public + */ + + set lastModified(val) { + if ('string' == typeof val) val = new Date(val); + this.set('Last-Modified', val.toUTCString()); + }, + + /** + * Get the Last-Modified date in Date form, if it exists. + * + * @return {Date} + * @api public + */ + + get lastModified() { + const date = this.get('last-modified'); + if (date) return new Date(date); + }, + + /** + * Set the ETag of a response. + * This will normalize the quotes if necessary. + * + * this.response.etag = 'md5hashsum'; + * this.response.etag = '"md5hashsum"'; + * this.response.etag = 'W/"123456789"'; + * + * @param {String} etag + * @api public + */ + + set etag(val) { + if (!/^(W\/)?"/.test(val)) val = `"${val}"`; + this.set('ETag', val); + }, + + /** + * Get the ETag of a response. + * + * @return {String} + * @api public + */ + + get etag() { + return this.get('ETag'); + }, + + /** + * Return the response mime type void of + * parameters such as "charset". + * + * @return {String} + * @api public + */ + + get type() { + const type = this.get('Content-Type'); + if (!type) return ''; + return type.split(';')[0]; + }, + + /** + * Check whether the response is one of the listed types. + * Pretty much the same as `this.request.is()`. + * + * @param {String|Array} types... + * @return {String|false} + * @api public + */ + + is(types) { + const type = this.type; + if (!types) return type || false; + if (!Array.isArray(types)) types = [].slice.call(arguments); + return typeis(type, types); + }, + + /** + * Return response header. + * + * Examples: + * + * this.get('Content-Type'); + * // => "text/plain" + * + * this.get('content-type'); + * // => "text/plain" + * + * @param {String} field + * @return {String} + * @api public + */ + + get(field) { + return this.header[field.toLowerCase()] || ''; + }, + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * this.set('Foo', ['bar', 'baz']); + * this.set('Accept', 'application/json'); + * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * @param {String|Object|Array} field + * @param {String} val + * @api public + */ + + set(field, val) { + if (this.headerSent) return; + + if (2 == arguments.length) { + if (Array.isArray(val)) val = val.map(v => typeof v === 'string' ? v : String(v)); + else if (typeof val !== 'string') val = String(val); + this.res.setHeader(field, val); + } else { + for (const key in field) { + this.set(key, field[key]); + } + } + }, + + /** + * Append additional header `field` with value `val`. + * + * Examples: + * + * ``` + * this.append('Link', ['', '']); + * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * this.append('Warning', '199 Miscellaneous warning'); + * ``` + * + * @param {String} field + * @param {String|Array} val + * @api public + */ + + append(field, val) { + const prev = this.get(field); + + if (prev) { + val = Array.isArray(prev) + ? prev.concat(val) + : [prev].concat(val); + } + + return this.set(field, val); + }, + + /** + * Remove header `field`. + * + * @param {String} name + * @api public + */ + + remove(field) { + if (this.headerSent) return; + + this.res.removeHeader(field); + }, + + /** + * Checks if the request is writable. + * Tests for the existence of the socket + * as node sometimes does not set it. + * + * @return {Boolean} + * @api private + */ + + get writable() { + // can't write any more after response finished + if (this.res.finished) return false; + + const socket = this.res.socket; + // There are already pending outgoing res, but still writable + // https://github.com/nodejs/node/blob/v4.4.7/lib/_http_server.js#L486 + if (!socket) return true; + return socket.writable; + }, + + /** + * Inspect implementation. + * + * @return {Object} + * @api public + */ + + inspect() { + if (!this.res) return; + const o = this.toJSON(); + o.body = this.body; + return o; + }, + + /** + * Return JSON representation. + * + * @return {Object} + * @api public + */ + + toJSON() { + return only(this, [ + 'status', + 'message', + 'header' + ]); + }, + + /** + * Flush any set headers, and begin the body + */ + flushHeaders() { + this.res.flushHeaders(); + } +}; + +/** + * Custom inspection implementation for newer Node.js versions. + * + * @return {Object} + * @api public + */ +if (util.inspect.custom) { + module.exports[util.inspect.custom] = module.exports.inspect; +} diff --git a/node_modules/koa/node_modules/debug/.coveralls.yml b/node_modules/koa/node_modules/debug/.coveralls.yml new file mode 100644 index 00000000..20a70685 --- /dev/null +++ b/node_modules/koa/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/koa/node_modules/debug/.eslintrc b/node_modules/koa/node_modules/debug/.eslintrc new file mode 100644 index 00000000..146371ed --- /dev/null +++ b/node_modules/koa/node_modules/debug/.eslintrc @@ -0,0 +1,14 @@ +{ + "env": { + "browser": true, + "node": true + }, + "globals": { + "chrome": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/koa/node_modules/debug/.npmignore b/node_modules/koa/node_modules/debug/.npmignore new file mode 100644 index 00000000..5f60eecc --- /dev/null +++ b/node_modules/koa/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/koa/node_modules/debug/.travis.yml b/node_modules/koa/node_modules/debug/.travis.yml new file mode 100644 index 00000000..a7643003 --- /dev/null +++ b/node_modules/koa/node_modules/debug/.travis.yml @@ -0,0 +1,20 @@ +sudo: false + +language: node_js + +node_js: + - "4" + - "6" + - "8" + +install: + - make install + +script: + - make lint + - make test + +matrix: + include: + - node_js: '8' + env: BROWSER=1 diff --git a/node_modules/koa/node_modules/debug/CHANGELOG.md b/node_modules/koa/node_modules/debug/CHANGELOG.md new file mode 100644 index 00000000..820d21e3 --- /dev/null +++ b/node_modules/koa/node_modules/debug/CHANGELOG.md @@ -0,0 +1,395 @@ + +3.1.0 / 2017-09-26 +================== + + * Add `DEBUG_HIDE_DATE` env var (#486) + * Remove ReDoS regexp in %o formatter (#504) + * Remove "component" from package.json + * Remove `component.json` + * Ignore package-lock.json + * Examples: fix colors printout + * Fix: browser detection + * Fix: spelling mistake (#496, @EdwardBetts) + +3.0.1 / 2017-08-24 +================== + + * Fix: Disable colors in Edge and Internet Explorer (#489) + +3.0.0 / 2017-08-08 +================== + + * Breaking: Remove DEBUG_FD (#406) + * Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418) + * Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408) + * Addition: document `enabled` flag (#465) + * Addition: add 256 colors mode (#481) + * Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440) + * Update: component: update "ms" to v2.0.0 + * Update: separate the Node and Browser tests in Travis-CI + * Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots + * Update: separate Node.js and web browser examples for organization + * Update: update "browserify" to v14.4.0 + * Fix: fix Readme typo (#473) + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +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/node_modules/koa/node_modules/debug/LICENSE b/node_modules/koa/node_modules/debug/LICENSE new file mode 100644 index 00000000..658c933d --- /dev/null +++ b/node_modules/koa/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/koa/node_modules/debug/Makefile b/node_modules/koa/node_modules/debug/Makefile new file mode 100644 index 00000000..3ddd1360 --- /dev/null +++ b/node_modules/koa/node_modules/debug/Makefile @@ -0,0 +1,58 @@ +# 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 + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +install: node_modules + +browser: dist/debug.js + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +dist/debug.js: src/*.js node_modules + @mkdir -p dist + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + +lint: + @eslint *.js src/*.js + +test-node: + @istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + @cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +test-browser: + @$(MAKE) browser + @karma start --single-run + +test-all: + @concurrently \ + "make test-node" \ + "make test-browser" + +test: + @if [ "x$(BROWSER)" = "x" ]; then \ + $(MAKE) test-node; \ + else \ + $(MAKE) test-browser; \ + fi + +clean: + rimraf dist coverage + +.PHONY: browser install clean lint test test-all test-node test-browser diff --git a/node_modules/koa/node_modules/debug/README.md b/node_modules/koa/node_modules/debug/README.md new file mode 100644 index 00000000..8e754d17 --- /dev/null +++ b/node_modules/koa/node_modules/debug/README.md @@ -0,0 +1,368 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', 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_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows note + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Note that PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Then, run the program to be debugged as usual. + + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +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). + + + + +## 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. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## 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". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## 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:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/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'); +``` + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/koa/node_modules/debug/karma.conf.js b/node_modules/koa/node_modules/debug/karma.conf.js new file mode 100644 index 00000000..103a82d1 --- /dev/null +++ b/node_modules/koa/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/koa/node_modules/debug/node.js b/node_modules/koa/node_modules/debug/node.js new file mode 100644 index 00000000..7fc36fe6 --- /dev/null +++ b/node_modules/koa/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/koa/node_modules/debug/package.json b/node_modules/koa/node_modules/debug/package.json new file mode 100644 index 00000000..ada43cfe --- /dev/null +++ b/node_modules/koa/node_modules/debug/package.json @@ -0,0 +1,43 @@ +{ + "name": "debug", + "version": "3.1.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "devDependencies": { + "browserify": "14.4.0", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js" +} diff --git a/node_modules/koa/node_modules/debug/src/browser.js b/node_modules/koa/node_modules/debug/src/browser.js new file mode 100644 index 00000000..f5149ff5 --- /dev/null +++ b/node_modules/koa/node_modules/debug/src/browser.js @@ -0,0 +1,195 @@ +/** + * 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 = [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' +]; + +/** + * 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() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // 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-zA-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); +} + +/** + * 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) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + 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/node_modules/koa/node_modules/debug/src/debug.js b/node_modules/koa/node_modules/debug/src/debug.js new file mode 100644 index 00000000..77e6384a --- /dev/null +++ b/node_modules/koa/node_modules/debug/src/debug.js @@ -0,0 +1,225 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * Active `debug` instances. + */ +exports.instances = []; + +/** + * 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, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + var prevTime; + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-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; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + exports.instances.push(debug); + + return debug; +} + +function destroy () { + var index = exports.instances.indexOf(this); + if (index !== -1) { + exports.instances.splice(index, 1); + return true; + } else { + return false; + } +} + +/** + * 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); + + exports.names = []; + exports.skips = []; + + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (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 + '$')); + } + } + + for (i = 0; i < exports.instances.length; i++) { + var instance = exports.instances[i]; + instance.enabled = exports.enabled(instance.namespace); + } +} + +/** + * 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) { + if (name[name.length - 1] === '*') { + return true; + } + 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/node_modules/koa/node_modules/debug/src/index.js b/node_modules/koa/node_modules/debug/src/index.js new file mode 100644 index 00000000..cabcbcda --- /dev/null +++ b/node_modules/koa/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/koa/node_modules/debug/src/node.js b/node_modules/koa/node_modules/debug/src/node.js new file mode 100644 index 00000000..d666fb9c --- /dev/null +++ b/node_modules/koa/node_modules/debug/src/node.js @@ -0,0 +1,186 @@ +/** + * 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.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [ 6, 2, 3, 4, 5, 1 ]; + +try { + var supportsColor = require('supports-color'); + if (supportsColor && supportsColor.level >= 2) { + exports.colors = [ + 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, + 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, + 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, + 205, 206, 207, 208, 209, 214, 215, 220, 221 + ]; + } +} catch (err) { + // swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(process.stderr.fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); + var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } else { + return new Date().toISOString() + ' '; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log() { + return process.stderr.write(util.format.apply(util, 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; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/koa/node_modules/koa-compose/History.md b/node_modules/koa/node_modules/koa-compose/History.md new file mode 100644 index 00000000..9f01d71b --- /dev/null +++ b/node_modules/koa/node_modules/koa-compose/History.md @@ -0,0 +1,60 @@ + +4.1.0 / 2018-05-22 +================== + + * improve: reduce stack trace by removing useless function call (#95) + +4.0.0 / 2017-04-12 +================== + + * remove `any-promise` as a dependency + +3.2.1 / 2016-10-26 +================== + + * revert add variadric support #65 - introduced an unintended breaking change + +3.2.0 / 2016-10-25 +================== + + * fix #60 infinite loop when calling next https://github.com/koajs/compose/pull/61 + * add variadric support https://github.com/koajs/compose/pull/65 + +3.1.0 / 2016-03-17 +================== + + * add linting w/ standard + * use `any-promise` so that the promise engine is configurable + +3.0.0 / 2015-10-19 +================== + + * change middleware signature to `async (ctx, next) => await next()` for `koa@2`. + See https://github.com/koajs/compose/pull/27 for more information. + +2.3.0 / 2014-05-01 +================== + + * remove instrumentation + +2.2.0 / 2014-01-22 +================== + + * add `fn._name` for debugging + +2.1.0 / 2013-12-22 +================== + + * add debugging support + * improve performance ~15% + +2.0.1 / 2013-12-21 +================== + + * update co to v3 + * use generator delegation + +2.0.0 / 2013-11-07 +================== + + * change middleware signature expected diff --git a/node_modules/koa/node_modules/koa-compose/Readme.md b/node_modules/koa/node_modules/koa-compose/Readme.md new file mode 100644 index 00000000..8fa6a392 --- /dev/null +++ b/node_modules/koa/node_modules/koa-compose/Readme.md @@ -0,0 +1,40 @@ + +# koa-compose + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][codecov-image]][codecov-url] +[![Dependency Status][david-image]][david-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + + Compose middleware. + +## Installation + +```js +$ npm install koa-compose +``` + +## API + +### compose([a, b, c, ...]) + + Compose the given middleware and return middleware. + +## License + + MIT + +[npm-image]: https://img.shields.io/npm/v/koa-compose.svg?style=flat-square +[npm-url]: https://npmjs.org/package/koa-compose +[travis-image]: https://img.shields.io/travis/koajs/compose/next.svg?style=flat-square +[travis-url]: https://travis-ci.org/koajs/compose +[codecov-image]: https://img.shields.io/codecov/c/github/koajs/compose/next.svg?style=flat-square +[codecov-url]: https://codecov.io/github/koajs/compose +[david-image]: http://img.shields.io/david/koajs/compose.svg?style=flat-square +[david-url]: https://david-dm.org/koajs/compose +[license-image]: http://img.shields.io/npm/l/koa-compose.svg?style=flat-square +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/koa-compose.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/koa-compose diff --git a/node_modules/koa/node_modules/koa-compose/index.js b/node_modules/koa/node_modules/koa-compose/index.js new file mode 100644 index 00000000..5cdc7faa --- /dev/null +++ b/node_modules/koa/node_modules/koa-compose/index.js @@ -0,0 +1,48 @@ +'use strict' + +/** + * Expose compositor. + */ + +module.exports = compose + +/** + * Compose `middleware` returning + * a fully valid middleware comprised + * of all those which are passed. + * + * @param {Array} middleware + * @return {Function} + * @api public + */ + +function compose (middleware) { + if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!') + for (const fn of middleware) { + if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!') + } + + /** + * @param {Object} context + * @return {Promise} + * @api public + */ + + return function (context, next) { + // last called middleware # + let index = -1 + return dispatch(0) + function dispatch (i) { + if (i <= index) return Promise.reject(new Error('next() called multiple times')) + index = i + let fn = middleware[i] + if (i === middleware.length) fn = next + if (!fn) return Promise.resolve() + try { + return Promise.resolve(fn(context, dispatch.bind(null, i + 1))); + } catch (err) { + return Promise.reject(err) + } + } + } +} diff --git a/node_modules/koa/node_modules/koa-compose/package.json b/node_modules/koa/node_modules/koa-compose/package.json new file mode 100644 index 00000000..7afa637e --- /dev/null +++ b/node_modules/koa/node_modules/koa-compose/package.json @@ -0,0 +1,30 @@ +{ + "name": "koa-compose", + "description": "compose Koa middleware", + "repository": "koajs/compose", + "version": "4.1.0", + "keywords": [ + "koa", + "middleware", + "compose" + ], + "files": [ + "index.js" + ], + "dependencies": {}, + "devDependencies": { + "codecov": "^3.0.0", + "jest": "^21.0.0", + "matcha": "^0.7.0", + "standard": "^10.0.3" + }, + "scripts": { + "bench": "matcha bench/bench.js", + "lint": "standard --fix .", + "test": "jest --forceExit --coverage" + }, + "jest": { + "testEnvironment": "node" + }, + "license": "MIT" +} diff --git a/node_modules/koa/package.json b/node_modules/koa/package.json new file mode 100644 index 00000000..a8b74cdb --- /dev/null +++ b/node_modules/koa/package.json @@ -0,0 +1,76 @@ +{ + "name": "koa", + "version": "2.6.1", + "description": "Koa web app framework", + "main": "lib/application.js", + "scripts": { + "test": "jest", + "test-cov": "jest --coverage --runInBand --forceExit", + "lint": "eslint benchmarks lib test", + "bench": "make -C benchmarks", + "authors": "git log --format='%aN <%aE>' | sort -u > AUTHORS" + }, + "repository": "koajs/koa", + "keywords": [ + "web", + "app", + "http", + "application", + "framework", + "middleware", + "rack" + ], + "license": "MIT", + "dependencies": { + "accepts": "^1.3.5", + "cache-content-type": "^1.0.0", + "content-disposition": "~0.5.2", + "content-type": "^1.0.4", + "cookies": "~0.7.1", + "debug": "~3.1.0", + "delegates": "^1.0.0", + "depd": "^1.1.2", + "destroy": "^1.0.4", + "error-inject": "^1.0.0", + "escape-html": "^1.0.3", + "fresh": "~0.5.2", + "http-assert": "^1.3.0", + "http-errors": "^1.6.3", + "is-generator-function": "^1.0.7", + "koa-compose": "^4.1.0", + "koa-convert": "^1.2.0", + "koa-is-json": "^1.0.0", + "on-finished": "^2.3.0", + "only": "~0.0.2", + "parseurl": "^1.3.2", + "statuses": "^1.5.0", + "type-is": "^1.6.16", + "vary": "^1.1.2" + }, + "devDependencies": { + "eslint": "^3.17.1", + "eslint-config-koa": "^2.0.0", + "eslint-config-standard": "^7.0.1", + "eslint-plugin-promise": "^3.5.0", + "eslint-plugin-standard": "^2.1.1", + "jest": "^20.0.0", + "supertest": "^3.1.0" + }, + "engines": { + "node": "^4.8.4 || ^6.10.1 || ^7.10.1 || >= 8.1.4" + }, + "files": [ + "lib" + ], + "jest": { + "testMatch": [ + "**/test/!(helpers)/*.js" + ], + "coverageReporters": [ + "text-summary", + "lcov" + ], + "bail": true, + "testEnvironment": "node" + } +} -- cgit v1.2.3