You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

220 lines
6.6 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. 'use strict'
  2. const path = require('path')
  3. const url = require('url')
  4. const arrayify = require('array-back')
  5. /**
  6. * @module local-web-server
  7. */
  8. module.exports = localWebServer
  9. /**
  10. * Returns a Koa application you can launch or mix into an existing app.
  11. *
  12. * @param [options] {object} - options
  13. * @param [options.static] {object} - koa-static config
  14. * @param [options.static.root=.] {string} - root directory
  15. * @param [options.static.options] {string} - [options](https://github.com/koajs/static#options)
  16. * @param [options.serveIndex] {object} - koa-serve-index config
  17. * @param [options.serveIndex.path=.] {string} - root directory
  18. * @param [options.serveIndex.options] {string} - [options](https://github.com/expressjs/serve-index#options)
  19. * @param [options.forbid] {string[]} - A list of forbidden routes, each route being an [express route-path](http://expressjs.com/guide/routing.html#route-paths).
  20. * @param [options.spa] {string} - specify an SPA file to catch requests for everything but static assets.
  21. * @param [options.log] {object} - [morgan](https://github.com/expressjs/morgan) config
  22. * @param [options.log.format] {string} - [log format](https://github.com/expressjs/morgan#predefined-formats)
  23. * @param [options.log.options] {object} - [options](https://github.com/expressjs/morgan#options)
  24. * @param [options.compress] {boolean} - Serve gzip-compressed resources, where applicable
  25. * @param [options.mime] {object} - A list of mime-type overrides, passed directly to [mime.define()](https://github.com/broofa/node-mime#mimedefine)
  26. * @param [options.rewrite] {module:local-web-server~rewriteRule[]} - One or more rewrite rules
  27. * @param [options.verbose] {boolean} - Print detailed output, useful for debugging
  28. *
  29. * @alias module:local-web-server
  30. * @return {external:KoaApplication}
  31. * @example
  32. * const localWebServer = require('local-web-server')
  33. * localWebServer().listen(8000)
  34. */
  35. function localWebServer (options) {
  36. options = Object.assign({
  37. static: {},
  38. serveIndex: {},
  39. spa: null,
  40. log: {},
  41. compress: false,
  42. mime: {},
  43. forbid: [],
  44. rewrite: [],
  45. verbose: false,
  46. mocks: []
  47. }, options)
  48. if (options.verbose) {
  49. process.env.DEBUG = '*'
  50. }
  51. const log = options.log
  52. log.options = log.options || {}
  53. if (options.verbose && !log.format) {
  54. log.format = 'none'
  55. }
  56. options.rewrite = arrayify(options.rewrite)
  57. options.forbid = arrayify(options.forbid)
  58. options.mocks = arrayify(options.mocks)
  59. const debug = require('debug')('local-web-server')
  60. const Koa = require('koa')
  61. const convert = require('koa-convert')
  62. const cors = require('kcors')
  63. const _ = require('koa-route')
  64. const json = require('koa-json')
  65. const bodyParser = require('koa-bodyparser')
  66. const mw = require('./middleware')
  67. const app = new Koa()
  68. const _use = app.use
  69. app.use = x => _use.call(app, convert(x))
  70. /* CORS: allow from any origin */
  71. app.use(cors())
  72. /* pretty print JSON */
  73. app.use(json())
  74. /* request body parser */
  75. app.use(bodyParser())
  76. /* rewrite rules */
  77. if (options.rewrite && options.rewrite.length) {
  78. options.rewrite.forEach(route => {
  79. if (route.to) {
  80. if (url.parse(route.to).host) {
  81. debug('proxy rewrite', `${route.from} -> ${route.to}`)
  82. app.use(_.all(route.from, mw.proxyRequest(route, app)))
  83. } else {
  84. const rewrite = require('koa-rewrite')
  85. const rmw = rewrite(route.from, route.to)
  86. rmw._name = 'rewrite'
  87. app.use(rmw)
  88. }
  89. }
  90. })
  91. }
  92. /* path blacklist */
  93. if (options.forbid.length) {
  94. debug('forbid', options.forbid.join(', '))
  95. app.use(mw.blacklist(options.forbid))
  96. }
  97. /* cache */
  98. if (!options['no-cache']) {
  99. const conditional = require('koa-conditional-get')
  100. const etag = require('koa-etag')
  101. app.use(conditional())
  102. app.use(etag())
  103. }
  104. /* mime-type overrides */
  105. if (options.mime) {
  106. debug('mime override', JSON.stringify(options.mime))
  107. app.use(mw.mime(options.mime))
  108. }
  109. /* compress response */
  110. if (options.compress) {
  111. const compress = require('koa-compress')
  112. debug('compression', 'enabled')
  113. app.use(compress())
  114. }
  115. /* Logging */
  116. if (log.format !== 'none') {
  117. const morgan = require('koa-morgan')
  118. if (!log.format) {
  119. const streamLogStats = require('stream-log-stats')
  120. log.options.stream = streamLogStats({ refreshRate: 500 })
  121. app.use(morgan('common', log.options))
  122. } else if (log.format === 'logstalgia') {
  123. morgan.token('date', logstalgiaDate)
  124. app.use(morgan('combined', log.options))
  125. } else {
  126. app.use(morgan(log.format, log.options))
  127. }
  128. }
  129. /* Mock Responses */
  130. options.mocks.forEach(mock => {
  131. if (mock.module) {
  132. mock.responses = require(path.join(options.static.root, mock.module))
  133. }
  134. if (mock.responses) {
  135. app.use(mw.mockResponses(mock.route, mock.responses))
  136. } else if (mock.response) {
  137. mock.target = {
  138. request: mock.request,
  139. response: mock.response
  140. }
  141. app.use(mw.mockResponses(mock.route, mock.target))
  142. }
  143. })
  144. /* serve static files */
  145. if (options.static.root) {
  146. const serve = require('koa-static')
  147. app.use(serve(options.static.root, options.static.options))
  148. }
  149. /* serve directory index */
  150. if (options.serveIndex.path) {
  151. const serveIndex = require('koa-serve-index')
  152. app.use(serveIndex(options.serveIndex.path, options.serveIndex.options))
  153. }
  154. /* for any URL not matched by static (e.g. `/search`), serve the SPA */
  155. if (options.spa) {
  156. const send = require('koa-send')
  157. debug('SPA', options.spa)
  158. app.use(_.all('*', function spa (ctx, route, next) {
  159. const root = path.resolve(options.static.root) || process.cwd()
  160. return send(ctx, options.spa, { root: root }).then(next)
  161. }))
  162. }
  163. return app
  164. }
  165. function logstalgiaDate () {
  166. var d = new Date()
  167. return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`).replace('GMT', '').replace(' (BST)', '')
  168. }
  169. process.on('unhandledRejection', (reason, p) => {
  170. throw reason
  171. })
  172. /**
  173. * The `from` and `to` routes are specified using [express route-paths](http://expressjs.com/guide/routing.html#route-paths)
  174. *
  175. * @example
  176. * ```json
  177. * {
  178. * "rewrite": [
  179. * { "from": "/css/*", "to": "/build/styles/$1" },
  180. * { "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
  181. * { "from": "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
  182. * ]
  183. * }
  184. * ```
  185. *
  186. * @typedef rewriteRule
  187. * @property from {string} - request route
  188. * @property to {string} - target route
  189. */
  190. /**
  191. * @external KoaApplication
  192. * @see https://github.com/koajs/koa/blob/master/docs/api/index.md#application
  193. */