UNPKG

1.58 kBJavaScriptView Raw
1'use strict'
2
3const { gray, green, magenta, red, yellow } = require('./detect/colors')
4const { log } = require('./console')
5const logCommon = require('./logCommon')
6const logError = require('./logError')
7
8const 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
21const onIncoming = event => logCommon.call(event, 'INCMG', true, gray(event.method), gray(event.url))
22
23const onEvent = (type, event) => logCommon.call(event, type, true)
24
25const 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
36module.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}