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.

224 lines
6.8 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. if (!options.static.root) options.static.root = process.cwd()
  57. if (!options.serveIndex.path) options.serveIndex.path = process.cwd()
  58. options.rewrite = arrayify(options.rewrite)
  59. options.forbid = arrayify(options.forbid)
  60. options.mocks = arrayify(options.mocks)
  61. const debug = require('debug')('local-web-server')
  62. const Koa = require('koa')
  63. const convert = require('koa-convert')
  64. const cors = require('kcors')
  65. const _ = require('koa-route')
  66. const json = require('koa-json')
  67. const bodyParser = require('koa-bodyparser')
  68. const mw = require('./middleware')
  69. const app = new Koa()
  70. const _use = app.use
  71. app.use = x => _use.call(app, convert(x))
  72. /* CORS: allow from any origin */
  73. app.use(cors())
  74. /* pretty print JSON */
  75. app.use(json())
  76. /* rewrite rules */
  77. if (options.rewrite && options.rewrite.length) {
  78. options.rewrite.forEach(route => {
  79. if (route.to) {
  80. /* `to` address is remote if the url specifies a host */
  81. if (url.parse(route.to).host) {
  82. debug('proxy rewrite', `${route.from} -> ${route.to}`)
  83. app.use(_.all(route.from, mw.proxyRequest(route, app)))
  84. } else {
  85. const rewrite = require('koa-rewrite')
  86. const rmw = rewrite(route.from, route.to)
  87. rmw._name = 'rewrite'
  88. app.use(rmw)
  89. }
  90. }
  91. })
  92. }
  93. /* must come after rewrite. See https://github.com/nodejitsu/node-http-proxy/issues/180. */
  94. app.use(bodyParser())
  95. /* path blacklist */
  96. if (options.forbid.length) {
  97. debug('forbid', options.forbid.join(', '))
  98. app.use(mw.blacklist(options.forbid))
  99. }
  100. /* cache */
  101. if (!options['no-cache']) {
  102. const conditional = require('koa-conditional-get')
  103. const etag = require('koa-etag')
  104. app.use(conditional())
  105. app.use(etag())
  106. }
  107. /* mime-type overrides */
  108. if (options.mime) {
  109. debug('mime override', JSON.stringify(options.mime))
  110. app.use(mw.mime(options.mime))
  111. }
  112. /* compress response */
  113. if (options.compress) {
  114. const compress = require('koa-compress')
  115. debug('compression', 'enabled')
  116. app.use(compress())
  117. }
  118. /* Logging */
  119. if (log.format !== 'none') {
  120. const morgan = require('koa-morgan')
  121. if (!log.format) {
  122. const streamLogStats = require('stream-log-stats')
  123. log.options.stream = streamLogStats({ refreshRate: 500 })
  124. app.use(morgan('common', log.options))
  125. } else if (log.format === 'logstalgia') {
  126. morgan.token('date', logstalgiaDate)
  127. app.use(morgan('combined', log.options))
  128. } else {
  129. app.use(morgan(log.format, log.options))
  130. }
  131. }
  132. /* Mock Responses */
  133. options.mocks.forEach(mock => {
  134. if (mock.module) {
  135. mock.responses = require(path.resolve(path.join(options.static.root, mock.module)))
  136. }
  137. if (mock.responses) {
  138. app.use(mw.mockResponses(mock.route, mock.responses))
  139. } else if (mock.response) {
  140. mock.target = {
  141. request: mock.request,
  142. response: mock.response
  143. }
  144. app.use(mw.mockResponses(mock.route, mock.target))
  145. }
  146. })
  147. /* for any URL not matched by static (e.g. `/search`), serve the SPA */
  148. if (options.spa) {
  149. const historyApiFallback = require('koa-connect-history-api-fallback')
  150. debug('SPA', options.spa)
  151. app.use(historyApiFallback({
  152. index: options.spa,
  153. verbose: options.verbose
  154. }))
  155. }
  156. /* serve static files */
  157. if (options.static.root) {
  158. const serve = require('koa-static')
  159. app.use(serve(options.static.root, options.static.options))
  160. }
  161. /* serve directory index */
  162. if (options.serveIndex.path) {
  163. const serveIndex = require('koa-serve-index')
  164. app.use(serveIndex(options.serveIndex.path, options.serveIndex.options))
  165. }
  166. return app
  167. }
  168. function logstalgiaDate () {
  169. var d = new Date()
  170. return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`).replace('GMT', '').replace(' (BST)', '')
  171. }
  172. process.on('unhandledRejection', (reason, p) => {
  173. throw reason
  174. })
  175. /**
  176. * The `from` and `to` routes are specified using [express route-paths](http://expressjs.com/guide/routing.html#route-paths)
  177. *
  178. * @example
  179. * ```json
  180. * {
  181. * "rewrite": [
  182. * { "from": "/css/*", "to": "/build/styles/$1" },
  183. * { "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
  184. * { "from": "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
  185. * ]
  186. * }
  187. * ```
  188. *
  189. * @typedef rewriteRule
  190. * @property from {string} - request route
  191. * @property to {string} - target route
  192. */
  193. /**
  194. * @external KoaApplication
  195. * @see https://github.com/koajs/koa/blob/master/docs/api/index.md#application
  196. */