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.

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