-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
dev-server-logs.client.ts
74 lines (66 loc) · 2.26 KB
/
dev-server-logs.client.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
import { consola, createConsola } from 'consola'
import type { LogObject } from 'consola'
import { isAbsolute } from 'pathe'
import { defineNuxtPlugin } from '../nuxt'
// @ts-expect-error virtual file
import { devLogs, devRootDir } from '#build/nuxt.config.mjs'
export default defineNuxtPlugin(nuxtApp => {
// Show things in console
if (devLogs !== 'silent') {
const logger = createConsola({
formatOptions: {
colors: true,
date: true,
}
})
const hydrationLogs = new Set<string>()
consola.wrapAll()
consola.addReporter({
log (logObj) {
try {
hydrationLogs.add(JSON.stringify(logObj.args))
} catch {
// silently ignore - the worst case is a user gets log twice
}
}
})
nuxtApp.hook('dev:ssr-logs', logs => {
for (const log of logs) {
// deduplicate so we don't print out things that are logged on client
if (!hydrationLogs.size || !hydrationLogs.has(JSON.stringify(log.args))) {
logger.log(normalizeServerLog({ ...log }))
}
}
})
nuxtApp.hooks.hook('app:suspense:resolve', () => logger.restoreAll())
nuxtApp.hooks.hookOnce('dev:ssr-logs', () => hydrationLogs.clear())
}
// pass SSR logs after hydration
nuxtApp.hooks.hook('app:suspense:resolve', async () => {
if (window && window.__NUXT_LOGS__) {
await nuxtApp.hooks.callHook('dev:ssr-logs', window.__NUXT_LOGS__)
}
})
// initialise long-running SSE connection
const source = new EventSource('/_nuxt_logs')
source.onmessage = (event) => {
const log = JSON.parse(event.data) as LogObject
log.date = new Date(log.date)
nuxtApp.hooks.callHook('dev:ssr-logs', [log])
}
})
function normalizeFilenames (stack?: string) {
return stack?.replace(/at.*\(([^)]+)\)/g, (match, filename) => {
if (!isAbsolute(filename)) { return match }
// TODO: normalise file names for clickable links in console
return match.replace(filename, filename.replace(devRootDir, ''))
})
}
function normalizeServerLog (log: LogObject) {
if (log.type === 'error' || log.type === 'warn') {
log.additional = normalizeFilenames(log.stack as string)
}
log.tag = `[ssr]${log.filename ? ` ${log.filename}` : ''}${log.tag || ''}`
delete log.stack
return log
}