forked from vitejs/vite
/
logger.ts
246 lines (224 loc) · 6.34 KB
/
logger.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/* eslint no-console: 0 */
import type { AddressInfo, Server } from 'net'
import os from 'os'
import readline from 'readline'
import colors from 'picocolors'
import type { RollupError } from 'rollup'
import type { CommonServerOptions } from './http'
import type { Hostname } from './utils'
import { resolveHostname } from './utils'
import { loopbackHosts, wildcardHosts } from './constants'
import type { ResolvedConfig } from '.'
export type LogType = 'error' | 'warn' | 'info'
export type LogLevel = LogType | 'silent'
export interface Logger {
info(msg: string, options?: LogOptions): void
warn(msg: string, options?: LogOptions): void
warnOnce(msg: string, options?: LogOptions): void
error(msg: string, options?: LogErrorOptions): void
clearScreen(type: LogType): void
hasErrorLogged(error: Error | RollupError): boolean
hasWarned: boolean
}
export interface LogOptions {
clear?: boolean
timestamp?: boolean
}
export interface LogErrorOptions extends LogOptions {
error?: Error | RollupError | null
}
export const LogLevels: Record<LogLevel, number> = {
silent: 0,
error: 1,
warn: 2,
info: 3
}
let lastType: LogType | undefined
let lastMsg: string | undefined
let sameCount = 0
function clearScreen() {
const repeatCount = process.stdout.rows - 2
const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''
console.log(blank)
readline.cursorTo(process.stdout, 0, 0)
readline.clearScreenDown(process.stdout)
}
export interface LoggerOptions {
prefix?: string
allowClearScreen?: boolean
customLogger?: Logger
}
export function createLogger(
level: LogLevel = 'info',
options: LoggerOptions = {}
): Logger {
if (options.customLogger) {
return options.customLogger
}
const loggedErrors = new WeakSet<Error | RollupError>()
const { prefix = '[vite]', allowClearScreen = true } = options
const thresh = LogLevels[level]
const canClearScreen =
allowClearScreen && process.stdout.isTTY && !process.env.CI
const clear = canClearScreen ? clearScreen : () => {}
function output(type: LogType, msg: string, options: LogErrorOptions = {}) {
if (thresh >= LogLevels[type]) {
const method = type === 'info' ? 'log' : type
const format = () => {
if (options.timestamp) {
const tag =
type === 'info'
? colors.cyan(colors.bold(prefix))
: type === 'warn'
? colors.yellow(colors.bold(prefix))
: colors.red(colors.bold(prefix))
return `${colors.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`
} else {
return msg
}
}
if (options.error) {
loggedErrors.add(options.error)
}
if (canClearScreen) {
if (type === lastType && msg === lastMsg) {
sameCount++
clear()
console[method](format(), colors.yellow(`(x${sameCount + 1})`))
} else {
sameCount = 0
lastMsg = msg
lastType = type
if (options.clear) {
clear()
}
console[method](format())
}
} else {
console[method](format())
}
}
}
const warnedMessages = new Set<string>()
const logger: Logger = {
hasWarned: false,
info(msg, opts) {
output('info', msg, opts)
},
warn(msg, opts) {
logger.hasWarned = true
output('warn', msg, opts)
},
warnOnce(msg, opts) {
if (warnedMessages.has(msg)) return
logger.hasWarned = true
output('warn', msg, opts)
warnedMessages.add(msg)
},
error(msg, opts) {
logger.hasWarned = true
output('error', msg, opts)
},
clearScreen(type) {
if (thresh >= LogLevels[type]) {
clear()
}
},
hasErrorLogged(error) {
return loggedErrors.has(error)
}
}
return logger
}
export function printCommonServerUrls(
server: Server,
options: CommonServerOptions,
config: ResolvedConfig
): void {
const address = server.address()
const isAddressInfo = (x: any): x is AddressInfo => x?.address
if (isAddressInfo(address)) {
const hostname = resolveHostname(options.host)
const protocol = options.https ? 'https' : 'http'
printServerUrls(
hostname,
protocol,
address.port,
config.base,
config.logger.info
)
}
}
function printServerUrls(
hostname: Hostname,
protocol: string,
port: number,
base: string,
info: Logger['info']
): void {
const urls: Array<{ label: string; url: string }> = []
if (hostname.host && loopbackHosts.has(hostname.host)) {
let hostnameName = hostname.name
if (
hostnameName === '::1' ||
hostnameName === '0000:0000:0000:0000:0000:0000:0000:0001'
) {
hostnameName = `[${hostnameName}]`
}
urls.push({
label: 'Local',
url: colors.cyan(
`${protocol}://${hostnameName}:${colors.bold(port)}${base}`
)
})
if (hostname.name === 'localhost') {
urls.push({
label: 'Network',
url: colors.dim(`use ${colors.white(colors.bold('--host'))} to expose`)
})
}
} else {
Object.values(os.networkInterfaces())
.flatMap((nInterface) => nInterface ?? [])
.filter(
(detail) =>
detail &&
detail.address &&
// Node < v18
((typeof detail.family === 'string' && detail.family === 'IPv4') ||
// Node >= v18
(typeof detail.family === 'number' && detail.family === 4))
)
.forEach((detail) => {
const host = detail.address.replace('127.0.0.1', hostname.name)
const url = `${protocol}://${host}:${colors.bold(port)}${base}`
const label = detail.address.includes('127.0.0.1') ? 'Local' : 'Network'
urls.push({ label, url: colors.cyan(url) })
})
}
const length = urls.reduce(
(length, { label }) => Math.max(length, label.length),
0
)
const print = (
iconWithColor: string,
label: string,
messageWithColor: string
) => {
info(
` ${iconWithColor} ${colors.bold(label)}: ${' '.repeat(
length - label.length
)}${messageWithColor}`
)
}
urls.forEach(({ label, url: text }) => {
print(colors.green('➜'), label, text)
})
if (!hostname.host || wildcardHosts.has(hostname.host)) {
print(
colors.bold(colors.blue('ⓘ')),
'Note',
colors.dim('You are using a wildcard host. Ports might be overriden.')
)
}
}