@ -5,17 +5,9 @@ const url = require('url')
const debug = require ( 'debug' ) ( 'local-web-server' )
const debug = require ( 'debug' ) ( 'local-web-server' )
const mw = require ( './middleware' )
const mw = require ( './middleware' )
const t = require ( 'typical' )
const t = require ( 'typical' )
const compose = require ( 'koa-compose' )
class MiddlewareStack extends Array {
class MiddlewareStack extends Array {
constructor ( options ) {
super ( )
this . options = options
if ( options . verbose ) {
process . env . DEBUG = '*'
}
}
add ( middleware ) {
add ( middleware ) {
this . push ( middleware )
this . push ( middleware )
return this
return this
@ -25,19 +17,26 @@ class MiddlewareStack extends Array {
* allow from any origin
* allow from any origin
* /
* /
addCors ( ) {
addCors ( ) {
this . push ( require ( 'kcors' ) ( ) )
this . push ( { middleware : require ( 'kcors' ) } )
return this
return this
}
}
/* pretty print JSON */
/* pretty print JSON */
addJson ( ) {
addJson ( ) {
this . push ( require ( 'koa-json' ) ( ) )
this . push ( { middleware : require ( 'koa-json' ) } )
return this
return this
}
}
/* rewrite rules */
/* rewrite rules */
addRewrite ( rewriteRules ) {
addRewrite ( rewriteRules ) {
const options = arrayify ( this . options . server . rewrite || rewriteRules )
this . push ( {
optionDefinitions : {
name : 'rewrite' , alias : 'r' , type : String , multiple : true ,
typeLabel : '[underline]{expression} ...' ,
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'."
} ,
middleware : function ( cliOptions ) {
const options = arrayify ( cliOptions . middleware . rewrite || rewriteRules )
if ( options . length ) {
if ( options . length ) {
options . forEach ( route => {
options . forEach ( route => {
if ( route . to ) {
if ( route . to ) {
@ -45,81 +44,123 @@ class MiddlewareStack extends Array {
if ( url . parse ( route . to ) . host ) {
if ( url . parse ( route . to ) . host ) {
const _ = require ( 'koa-route' )
const _ = require ( 'koa-route' )
debug ( 'proxy rewrite' , ` ${ route . from } -> ${ route . to } ` )
debug ( 'proxy rewrite' , ` ${ route . from } -> ${ route . to } ` )
this . push ( _ . all ( route . from , mw . proxyRequest ( route ) ) )
return _ . all ( route . from , mw . proxyRequest ( route ) )
} else {
} else {
const rewrite = require ( 'koa-rewrite' )
const rewrite = require ( 'koa-rewrite' )
const rmw = rewrite ( route . from , route . to )
const rmw = rewrite ( route . from , route . to )
rmw . _name = 'rewrite'
rmw . _name = 'rewrite'
this . push ( rmw )
return rmw
}
}
}
}
} )
} )
}
}
}
} )
return this
return this
}
}
/ * m u s t c o m e a f t e r r e w r i t e .
/ * m u s t c o m e a f t e r r e w r i t e .
See https : //github.com/nodejitsu/node-http-proxy/issues/180. */
See https : //github.com/nodejitsu/node-http-proxy/issues/180. */
addBodyParser ( ) {
addBodyParser ( ) {
this . push ( require ( 'koa-bodyparser' ) ( ) )
this . push ( { middleware : require ( 'koa-bodyparser' ) } )
return this
return this
}
}
/* path blacklist */
/* path blacklist */
addBlacklist ( forbidList ) {
addBlacklist ( forbidList ) {
forbidList = arrayify ( this . options . server . forbid || forbidList )
this . push ( {
optionDefinitions : {
name : 'forbid' , alias : 'b' , type : String ,
multiple : true , typeLabel : '[underline]{path} ...' ,
description : 'A list of forbidden routes.'
} ,
middleware : function ( cliOptions ) {
forbidList = arrayify ( cliOptions . middleware . forbid || forbidList )
if ( forbidList . length ) {
if ( forbidList . length ) {
const pathToRegexp = require ( 'path-to-regexp' )
const pathToRegexp = require ( 'path-to-regexp' )
debug ( 'forbid' , forbidList . join ( ', ' ) )
debug ( 'forbid' , forbidList . join ( ', ' ) )
this . push ( function blacklist ( ctx , next ) {
return function blacklist ( ctx , next ) {
if ( forbidList . some ( expression => pathToRegexp ( expression ) . test ( ctx . path ) ) ) {
if ( forbidList . some ( expression => pathToRegexp ( expression ) . test ( ctx . path ) ) ) {
const http = require ( 'http' )
ctx . throw ( 403 , http . STATUS_CODES [ 403 ] )
ctx . throw ( 403 , http . STATUS_CODES [ 403 ] )
} else {
} else {
return next ( )
return next ( )
}
}
} )
}
}
}
}
} )
return this
return this
}
}
/* cache */
/* cache */
addCache ( ) {
addCache ( ) {
const noCache = this . options . server [ 'no-cache' ]
this . push ( {
optionDefinitions : {
name : 'no-cache' , alias : 'n' , type : Boolean ,
description : 'Disable etag-based caching - forces loading from disk each request.'
} ,
middleware : function ( cliOptions ) {
const noCache = cliOptions . middleware [ 'no-cache' ]
if ( ! noCache ) {
if ( ! noCache ) {
this . push ( require ( 'koa-conditional-get' ) ( ) )
this . push ( require ( 'koa-etag' ) ( ) )
return [
require ( 'koa-conditional-get' ) ( ) ,
require ( 'koa-etag' ) ( )
]
}
}
}
} )
return this
return this
}
}
/* mime-type overrides */
/* mime-type overrides */
addMimeType ( mime ) {
addMimeType ( mime ) {
mime = this . options . server . mime || mime
this . push ( {
middleware : function ( cliOptions ) {
mime = cliOptions . middleware . mime || mime
if ( mime ) {
if ( mime ) {
debug ( 'mime override' , JSON . stringify ( mime ) )
debug ( 'mime override' , JSON . stringify ( mime ) )
this . push ( mw . mime ( mime ) )
return mw . mime ( mime )
}
}
}
} )
return this
return this
}
}
/* compress response */
/* compress response */
addCompression ( compress ) {
addCompression ( compress ) {
compress = t . isDefined ( this . options . server . compress )
? this . options . server . compress
this . push ( {
optionDefinitions : {
name : 'compress' , alias : 'c' , type : Boolean ,
description : 'Serve gzip-compressed resources, where applicable.'
} ,
middleware : function ( cliOptions ) {
compress = t . isDefined ( cliOptions . middleware . compress )
? cliOptions . middleware . compress
: compress
: compress
if ( compress ) {
if ( compress ) {
debug ( 'compression' , 'enabled' )
debug ( 'compression' , 'enabled' )
this . push ( require ( 'koa-compress' ) ( ) )
return require ( 'koa-compress' ) ( )
}
}
}
} )
return this
return this
}
}
/* Logging */
/* Logging */
addLogging ( format , options ) {
addLogging ( format , options ) {
format = this . options . server [ 'log-format' ] || format
options = options || { }
options = options || { }
this . push ( {
optionDefinitions : {
name : 'log-format' ,
alias : 'f' ,
type : String ,
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')."
} ,
middleware : function ( cliOptions ) {
format = cliOptions . middleware [ 'log-format' ] || format
if ( this . options . verbose && ! format ) {
if ( cliOptions . misc . verbose && ! format ) {
format = 'none'
format = 'none'
}
}
@ -129,37 +170,43 @@ class MiddlewareStack extends Array {
if ( ! format ) {
if ( ! format ) {
const streamLogStats = require ( 'stream-log-stats' )
const streamLogStats = require ( 'stream-log-stats' )
options . stream = streamLogStats ( { refreshRate : 500 } )
options . stream = streamLogStats ( { refreshRate : 500 } )
this . push ( morgan ( 'common' , options ) )
return morgan ( 'common' , options )
} else if ( format === 'logstalgia' ) {
} else if ( format === 'logstalgia' ) {
morgan . token ( 'date' , ( ) => {
morgan . token ( 'date' , ( ) => {
var d = new Date ( )
var d = new Date ( )
return ( ` ${ d . getDate ( ) } / ${ d . getUTCMonth ( ) } / ${ d . getFullYear ( ) } : ${ d . toTimeString ( ) } ` ) . replace ( 'GMT' , '' ) . replace ( ' (BST)' , '' )
return ( ` ${ d . getDate ( ) } / ${ d . getUTCMonth ( ) } / ${ d . getFullYear ( ) } : ${ d . toTimeString ( ) } ` ) . replace ( 'GMT' , '' ) . replace ( ' (BST)' , '' )
} )
} )
this . push ( morgan ( 'combined' , options ) )
return morgan ( 'combined' , options )
} else {
} else {
this . push ( morgan ( format , options ) )
return morgan ( format , options )
}
}
}
}
}
} )
return this
return this
}
}
/* Mock Responses */
/* Mock Responses */
addMockResponses ( mocks ) {
addMockResponses ( mocks ) {
mocks = arrayify ( this . options . server . mocks || mocks )
this . push ( {
middleware : function ( cliOptions ) {
mocks = arrayify ( cliOptions . middleware . mocks || mocks )
mocks . forEach ( mock => {
mocks . forEach ( mock => {
if ( mock . module ) {
if ( mock . module ) {
// TODO: ENSURE this.o ptions.static.root is correct value
mock . responses = require ( path . resolve ( path . join ( this . o ptions. static . root , mock . module ) ) )
// TODO: ENSURE cliO ptions.static.root is correct value
mock . responses = require ( path . resolve ( path . join ( cliO ptions. static . root , mock . module ) ) )
}
}
if ( mock . responses ) {
if ( mock . responses ) {
this . push ( mw . mockResponses ( mock . route , mock . responses ) )
return mw . mockResponses ( mock . route , mock . responses )
} else if ( mock . response ) {
} else if ( mock . response ) {
mock . target = {
mock . target = {
request : mock . request ,
request : mock . request ,
response : mock . response
response : mock . response
}
}
this . push ( mw . mockResponses ( mock . route , mock . target ) )
return mw . mockResponses ( mock . route , mock . target )
}
} )
}
}
} )
} )
return this
return this
@ -167,44 +214,77 @@ class MiddlewareStack extends Array {
/* for any URL not matched by static (e.g. `/search`), serve the SPA */
/* for any URL not matched by static (e.g. `/search`), serve the SPA */
addSpa ( spa ) {
addSpa ( spa ) {
spa = t . isDefined ( this . options . server . spa ) ? this . options . server . spa : spa
this . push ( {
optionDefinitions : {
name : 'spa' , alias : 's' , type : String , typeLabel : '[underline]{file}' ,
description : 'Path to a Single Page App, e.g. app.html.'
} ,
middleware : function ( cliOptions ) {
spa = t . isDefined ( cliOptions . middleware . spa ) ? cliOptions . middleware . spa : spa
if ( spa ) {
if ( spa ) {
const historyApiFallback = require ( 'koa-connect-history-api-fallback' )
const historyApiFallback = require ( 'koa-connect-history-api-fallback' )
debug ( 'SPA' , spa )
debug ( 'SPA' , spa )
this . push ( historyApiFallback ( {
return historyApiFallback ( {
index : spa ,
index : spa ,
verbose : this . options . verbose
} ) )
verbose : cliOptions . misc . verbose
} )
}
}
}
} )
return this
return this
}
}
/* serve static files */
/* serve static files */
addStatic ( root , options ) {
addStatic ( root , options ) {
root = this . options . server . directory || root || process . cwd ( )
this . push ( {
optionDefinitions : {
name : 'directory' , alias : 'd' , type : String , typeLabel : '[underline]{path}' ,
description : 'Root directory, defaults to the current directory.'
} ,
middleware : function ( cliOptions ) {
root = cliOptions . middleware . directory || root || process . cwd ( )
options = Object . assign ( { hidden : true } , options )
options = Object . assign ( { hidden : true } , options )
// console.log(root, options, cliOptions)
if ( root ) {
if ( root ) {
const serve = require ( 'koa-static' )
const serve = require ( 'koa-static' )
this . push ( serve ( root , options ) )
return serve ( root , options )
}
}
}
} )
return this
return this
}
}
/* serve directory index */
/* serve directory index */
addIndex ( path , options ) {
addIndex ( path , options ) {
path = this . options . server . directory || path || process . cwd ( )
this . push ( {
middleware : function ( cliOptions ) {
path = cliOptions . middleware . directory || path || process . cwd ( )
options = Object . assign ( { icons : true , hidden : true } , options )
options = Object . assign ( { icons : true , hidden : true } , options )
if ( path ) {
if ( path ) {
const serveIndex = require ( 'koa-serve-index' )
const serveIndex = require ( 'koa-serve-index' )
this . push ( serveIndex ( path , options ) )
return serveIndex ( path , options )
}
}
}
} )
return this
return this
}
}
getOptionDefinitions ( ) {
const flatten = require ( 'reduce-flatten' )
return this
. filter ( mw => mw . optionDefinitions )
. map ( mw => mw . optionDefinitions )
. reduce ( flatten , [ ] )
. map ( def => {
def . group = 'middleware'
return def
} )
}
compose ( options ) {
compose ( options ) {
const compose = require ( 'koa-compose' )
const convert = require ( 'koa-convert' )
const convert = require ( 'koa-convert' )
const middlewareStack = this . map ( convert )
const middlewareStack = this
. filter ( mw => mw )
. map ( mw => compose ( arrayify ( mw . middleware ( options ) ) . map ( convert ) ) )
return compose ( middlewareStack )
return compose ( middlewareStack )
}
}
}
}