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.

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