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.

291 lines
8.7 KiB

9 years ago
  1. 'use strict'
  2. const arrayify = require('array-back')
  3. const path = require('path')
  4. const url = require('url')
  5. const debug = require('./debug')
  6. const mw = require('./middleware')
  7. const t = require('typical')
  8. const compose = require('koa-compose')
  9. const flatten = require('reduce-flatten')
  10. const MiddlewareStack = require('./middleware-stack')
  11. class DefaultStack extends MiddlewareStack {
  12. /**
  13. * allow from any origin
  14. */
  15. addCors () {
  16. this.push({ middleware: require('kcors') })
  17. return this
  18. }
  19. /* pretty print JSON */
  20. addJson () {
  21. this.push({ middleware: require('koa-json') })
  22. return this
  23. }
  24. /* rewrite rules */
  25. addRewrite (rewriteRules) {
  26. this.push({
  27. optionDefinitions: {
  28. name: 'rewrite', alias: 'r', type: String, multiple: true,
  29. typeLabel: '[underline]{expression} ...',
  30. description: "A list of URL rewrite rules. For each rule, separate the 'from' and 'to' routes with '->'. Whitespace surrounded the routes is ignored. E.g. '/from -> /to'."
  31. },
  32. middleware: function (cliOptions) {
  33. const options = parseRewriteRules(arrayify(cliOptions.rewrite || rewriteRules))
  34. if (options.length) {
  35. return options.map(route => {
  36. if (route.to) {
  37. /* `to` address is remote if the url specifies a host */
  38. if (url.parse(route.to).host) {
  39. const _ = require('koa-route')
  40. debug('proxy rewrite', `${route.from} -> ${route.to}`)
  41. return _.all(route.from, mw.proxyRequest(route))
  42. } else {
  43. const rewrite = require('koa-rewrite')
  44. const rmw = rewrite(route.from, route.to)
  45. rmw._name = 'rewrite'
  46. return rmw
  47. }
  48. }
  49. })
  50. }
  51. }
  52. })
  53. return this
  54. }
  55. /* must come after rewrite.
  56. See https://github.com/nodejitsu/node-http-proxy/issues/180. */
  57. addBodyParser () {
  58. this.push({ middleware: require('koa-bodyparser') })
  59. return this
  60. }
  61. /* path blacklist */
  62. addBlacklist (forbidList) {
  63. this.push({
  64. optionDefinitions: {
  65. name: 'forbid', alias: 'b', type: String,
  66. multiple: true, typeLabel: '[underline]{path} ...',
  67. description: 'A list of forbidden routes.'
  68. },
  69. middleware: function (cliOptions) {
  70. forbidList = arrayify(cliOptions.forbid || forbidList)
  71. if (forbidList.length) {
  72. const pathToRegexp = require('path-to-regexp')
  73. debug('forbid', forbidList.join(', '))
  74. return function blacklist (ctx, next) {
  75. if (forbidList.some(expression => pathToRegexp(expression).test(ctx.path))) {
  76. ctx.status = 403
  77. } else {
  78. return next()
  79. }
  80. }
  81. }
  82. }
  83. })
  84. return this
  85. }
  86. /* cache */
  87. addCache () {
  88. this.push({
  89. optionDefinitions: {
  90. name: 'no-cache', alias: 'n', type: Boolean,
  91. description: 'Disable etag-based caching - forces loading from disk each request.'
  92. },
  93. middleware: function (cliOptions) {
  94. const noCache = cliOptions['no-cache']
  95. if (!noCache) {
  96. return [
  97. require('koa-conditional-get')(),
  98. require('koa-etag')()
  99. ]
  100. }
  101. }
  102. })
  103. return this
  104. }
  105. /* mime-type overrides */
  106. addMimeOverride (mime) {
  107. this.push({
  108. middleware: function (cliOptions) {
  109. mime = cliOptions.mime || mime
  110. if (mime) {
  111. debug('mime override', JSON.stringify(mime))
  112. return mw.mime(mime)
  113. }
  114. }
  115. })
  116. return this
  117. }
  118. /* compress response */
  119. addCompression (compress) {
  120. this.push({
  121. optionDefinitions: {
  122. name: 'compress', alias: 'c', type: Boolean,
  123. description: 'Serve gzip-compressed resources, where applicable.'
  124. },
  125. middleware: function (cliOptions) {
  126. compress = t.isDefined(cliOptions.compress)
  127. ? cliOptions.compress
  128. : compress
  129. if (compress) {
  130. debug('compression', 'enabled')
  131. return require('koa-compress')()
  132. }
  133. }
  134. })
  135. return this
  136. }
  137. /* Logging */
  138. addLogging (format, options) {
  139. options = options || {}
  140. this.push({
  141. optionDefinitions: {
  142. name: 'log-format',
  143. alias: 'f',
  144. type: String,
  145. description: "If a format is supplied an access log is written to stdout. If not, a dynamic statistics view is displayed. Use a preset ('none', 'dev','combined', 'short', 'tiny' or 'logstalgia') or supply a custom format (e.g. ':method -> :url')."
  146. },
  147. middleware: function (cliOptions) {
  148. format = cliOptions['log-format'] || format
  149. if (cliOptions.verbose && !format) {
  150. format = 'none'
  151. }
  152. if (format !== 'none') {
  153. const morgan = require('koa-morgan')
  154. if (!format) {
  155. const streamLogStats = require('stream-log-stats')
  156. options.stream = streamLogStats({ refreshRate: 500 })
  157. return morgan('common', options)
  158. } else if (format === 'logstalgia') {
  159. morgan.token('date', () => {
  160. var d = new Date()
  161. return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`).replace('GMT', '').replace(' (BST)', '')
  162. })
  163. return morgan('combined', options)
  164. } else {
  165. return morgan(format, options)
  166. }
  167. }
  168. }
  169. })
  170. return this
  171. }
  172. /* Mock Responses */
  173. addMockResponses (mocks) {
  174. this.push({
  175. middleware: function (cliOptions) {
  176. mocks = arrayify(cliOptions.mocks || mocks)
  177. return mocks.map(mock => {
  178. if (mock.module) {
  179. const modulePath = path.resolve(path.join(cliOptions.directory, mock.module))
  180. mock.responses = require(modulePath)
  181. }
  182. if (mock.responses) {
  183. return mw.mockResponses(mock.route, mock.responses)
  184. } else if (mock.response) {
  185. mock.target = {
  186. request: mock.request,
  187. response: mock.response
  188. }
  189. return mw.mockResponses(mock.route, mock.target)
  190. }
  191. })
  192. }
  193. })
  194. return this
  195. }
  196. /* for any URL not matched by static (e.g. `/search`), serve the SPA */
  197. addSpa (spa, assetTest) {
  198. this.push({
  199. optionDefinitions: {
  200. name: 'spa', alias: 's', type: String, typeLabel: '[underline]{file}',
  201. description: 'Path to a Single Page App, e.g. app.html.'
  202. },
  203. middleware: function (cliOptions) {
  204. spa = cliOptions.spa || spa || 'index.html'
  205. assetTest = new RegExp(cliOptions['spa-asset-test'] || assetTest || '\\.')
  206. if (spa) {
  207. const send = require('koa-send')
  208. const _ = require('koa-route')
  209. debug('SPA', spa)
  210. return _.get('*', function spaMw (ctx, route, next) {
  211. const root = path.resolve(cliOptions.directory || process.cwd())
  212. if (ctx.accepts('text/html') && !assetTest.test(route)) {
  213. debug(`SPA request. Route: ${route}, isAsset: ${assetTest.test(route)}`)
  214. return send(ctx, spa, { root: root }).then(next)
  215. } else {
  216. return send(ctx, route, { root: root }).then(next)
  217. }
  218. })
  219. }
  220. }
  221. })
  222. return this
  223. }
  224. /* serve static files */
  225. addStatic (root, options) {
  226. this.push({
  227. optionDefinitions: {
  228. name: 'directory', alias: 'd', type: String, typeLabel: '[underline]{path}',
  229. description: 'Root directory, defaults to the current directory.'
  230. },
  231. middleware: function (cliOptions) {
  232. /* update global cliOptions */
  233. cliOptions.directory = cliOptions.directory || root || process.cwd()
  234. options = Object.assign({ hidden: true }, options)
  235. if (cliOptions.directory) {
  236. const serve = require('koa-static')
  237. return serve(cliOptions.directory, options)
  238. }
  239. }
  240. })
  241. return this
  242. }
  243. /* serve directory index */
  244. addIndex (path, options) {
  245. this.push({
  246. middleware: function (cliOptions) {
  247. path = cliOptions.directory || path || process.cwd()
  248. options = Object.assign({ icons: true, hidden: true }, options)
  249. if (path) {
  250. const serveIndex = require('koa-serve-index')
  251. return serveIndex(path, options)
  252. }
  253. }
  254. })
  255. return this
  256. }
  257. }
  258. module.exports = DefaultStack
  259. function parseRewriteRules (rules) {
  260. return rules && rules.map(rule => {
  261. if (t.isString(rule)) {
  262. const matches = rule.match(/(\S*)\s*->\s*(\S*)/)
  263. if (!(matches && matches.length >= 3)) throw new Error('Invalid rule: ' + rule)
  264. return {
  265. from: matches[1],
  266. to: matches[2]
  267. }
  268. } else {
  269. return rule
  270. }
  271. })
  272. }