-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
server.ts
82 lines (66 loc) · 2.45 KB
/
server.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
import type { TransformResult, ViteDevServer } from 'vite'
import { shouldExternalize } from './externalize'
import type { ViteNodeResolveId, ViteNodeServerOptions } from './types'
import { toFilePath, withInlineSourcemap } from './utils'
export * from './externalize'
export class ViteNodeServer {
promiseMap = new Map<string, Promise<TransformResult | null | undefined>>()
constructor(
public server: ViteDevServer,
public options: ViteNodeServerOptions = {},
) {}
shouldExternalize(id: string) {
return shouldExternalize(id, this.options.deps)
}
async fetchModule(id: string) {
const externalize = await this.shouldExternalize(toFilePath(id, this.server.config.root))
if (externalize)
return { externalize }
const r = await this.transformRequest(id)
return { code: r?.code }
}
async resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null> {
return this.server.pluginContainer.resolveId(id, importer, { ssr: true })
}
async transformRequest(id: string) {
// reuse transform for concurrent requests
if (!this.promiseMap.has(id)) {
this.promiseMap.set(id,
this._transformRequest(id)
.finally(() => {
this.promiseMap.delete(id)
}),
)
}
return this.promiseMap.get(id)
}
private getTransformMode(id: string) {
const withoutQuery = id.split('?')[0]
if (this.options.transformMode?.web?.some(r => withoutQuery.match(r)))
return 'web'
if (this.options.transformMode?.ssr?.some(r => withoutQuery.match(r)))
return 'ssr'
if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/))
return 'ssr'
return 'web'
}
private async _transformRequest(id: string) {
let result: TransformResult | null = null
const mode = this.getTransformMode(id)
if (mode === 'web') {
// for components like Vue, we want to use the client side
// plugins but then covert the code to be consumed by the server
result = await this.server.transformRequest(id)
if (result)
result = await this.server.ssrTransform(result.code, result.map, id)
}
else {
result = await this.server.transformRequest(id, { ssr: true })
}
if (this.options.sourcemap !== false && result && !id.includes('node_modules'))
withInlineSourcemap(result)
// if (result?.map && process.env.NODE_V8_COVERAGE)
// visitedFilesMap.set(toFilePath(id, config.root), result.map as any)
return result
}
}