-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.ts
102 lines (91 loc) · 2.86 KB
/
index.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
import type { Plugin } from 'vite'
import type { Vitest } from 'vitest/node'
import { fileURLToPath } from 'node:url'
import { toArray } from '@vitest/utils'
import { basename, resolve } from 'pathe'
import sirv from 'sirv'
import c from 'tinyrainbow'
import { coverageConfigDefaults } from 'vitest/config'
import { version } from '../package.json'
export default (ctx: Vitest): Plugin => {
if (ctx.version !== version) {
ctx.logger.warn(
c.yellow(
`Loaded ${c.inverse(c.yellow(` vitest@${ctx.version} `))} and ${c.inverse(c.yellow(` @vitest/ui@${version} `))}.`
+ '\nRunning mixed versions is not supported and may lead into bugs'
+ '\nUpdate your dependencies and make sure the versions match.',
),
)
}
return <Plugin>{
name: 'vitest:ui',
apply: 'serve',
configureServer: {
order: 'post',
handler(server) {
const uiOptions = ctx.config
const base = uiOptions.uiBase
const coverageFolder = resolveCoverageFolder(ctx)
const coveragePath = coverageFolder ? coverageFolder[1] : undefined
if (coveragePath && base === coveragePath) {
throw new Error(
`The ui base path and the coverage path cannot be the same: ${base}, change coverage.reportsDirectory`,
)
}
if (coverageFolder) {
server.middlewares.use(
coveragePath!,
sirv(coverageFolder[0], {
single: true,
dev: true,
setHeaders: (res) => {
res.setHeader(
'Cache-Control',
'public,max-age=0,must-revalidate',
)
},
}),
)
}
const clientDist = resolve(fileURLToPath(import.meta.url), '../client')
server.middlewares.use(
base,
sirv(clientDist, {
single: true,
dev: true,
}),
)
},
},
}
}
function resolveCoverageFolder(ctx: Vitest) {
const options = ctx.config
const htmlReporter
= options.api?.port && options.coverage?.enabled
? toArray(options.coverage.reporter).find((reporter) => {
if (typeof reporter === 'string') {
return reporter === 'html'
}
return reporter[0] === 'html'
})
: undefined
if (!htmlReporter) {
return undefined
}
// reportsDirectory not resolved yet
const root = resolve(
ctx.config?.root || options.root || process.cwd(),
options.coverage.reportsDirectory || coverageConfigDefaults.reportsDirectory,
)
const subdir
= Array.isArray(htmlReporter)
&& htmlReporter.length > 1
&& 'subdir' in htmlReporter[1]
? htmlReporter[1].subdir
: undefined
if (!subdir || typeof subdir !== 'string') {
return [root, `/${basename(root)}/`]
}
return [resolve(root, subdir), `/${basename(root)}/${subdir}/`]
}