1 | 'use strict'
|
2 |
|
3 | const { gray, green, magenta, red, yellow } = require('./detect/colors')
|
4 | const { log } = require('./console')
|
5 | const logCommon = require('./logCommon')
|
6 | const logError = require('./logError')
|
7 |
|
8 | const onRedirected = (verbose, event) => {
|
9 | const statusCode = event.statusCode
|
10 | let statusText
|
11 | if (!statusCode) {
|
12 | statusText = red('N/A')
|
13 | } else if (statusCode > 399) {
|
14 | statusText = red(statusCode.toString())
|
15 | } else {
|
16 | statusText = green(statusCode.toString())
|
17 | }
|
18 | logCommon.call(event, 'SERVE', verbose, statusText, magenta(`${event.timeSpent} ms`))
|
19 | }
|
20 |
|
21 | const onIncoming = event => logCommon.call(event, 'INCMG', true, gray(event.method), gray(event.url))
|
22 |
|
23 | const onEvent = (type, event) => logCommon.call(event, type, true)
|
24 |
|
25 | const onRedirecting = event => {
|
26 | const redirect = event.redirect
|
27 | let redirectLabel
|
28 | if (typeof redirect === 'function') {
|
29 | redirectLabel = redirect.name || 'anonymous'
|
30 | } else {
|
31 | redirectLabel = redirect.toString()
|
32 | }
|
33 | logCommon.call(event, 'RDRCT', true, gray(event.type), gray(redirectLabel))
|
34 | }
|
35 |
|
36 | module.exports = (serve, verbose) => {
|
37 | serve
|
38 | .on('ready', ({ url }) => {
|
39 | log(yellow(`Server running at ${url}`))
|
40 | })
|
41 | .on('redirected', onRedirected.bind(null, verbose))
|
42 | if (verbose) {
|
43 | serve
|
44 | .on('error', event => { logError(event, true) })
|
45 | .on('incoming', onIncoming)
|
46 | .on('aborted', onEvent.bind(null, 'ABORT'))
|
47 | .on('closed', onEvent.bind(null, 'CLOSE'))
|
48 | .on('redirecting', onRedirecting)
|
49 | } else {
|
50 | serve
|
51 | .on('error', logError)
|
52 | }
|
53 | return serve
|
54 | }
|