/
server.ts
190 lines (160 loc) · 6.07 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
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
import { performance } from 'node:perf_hooks'
import { resolve } from 'pathe'
import type { TransformResult, ViteDevServer } from 'vite'
import createDebug from 'debug'
import type { DebuggerOptions, FetchResult, RawSourceMap, ViteNodeResolveId, ViteNodeServerOptions } from './types'
import { shouldExternalize } from './externalize'
import { normalizeModuleId, toArray, toFilePath } from './utils'
import { Debugger } from './debug'
import { withInlineSourcemap } from './source-map'
export * from './externalize'
const debugRequest = createDebug('vite-node:server:request')
export class ViteNodeServer {
private fetchPromiseMap = new Map<string, Promise<FetchResult>>()
private transformPromiseMap = new Map<string, Promise<TransformResult | null | undefined>>()
fetchCache = new Map<string, {
duration?: number
timestamp: number
result: FetchResult
}>()
externalizeCache = new Map<string, Promise<string | false>>()
debugger?: Debugger
constructor(
public server: ViteDevServer,
public options: ViteNodeServerOptions = {},
) {
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore ssr is not typed in Vite 2, but defined in Vite 3, so we can't use expect-error
const ssrOptions = server.config.ssr
if (ssrOptions) {
options.deps ??= {}
// we don't externalize ssr, because it has different semantics in Vite
// if (ssrOptions.external) {
// options.deps.external ??= []
// options.deps.external.push(...ssrOptions.external)
// }
if (ssrOptions.noExternal === true) {
options.deps.inline ??= true
}
else if (options.deps.inline !== true) {
options.deps.inline ??= []
options.deps.inline.push(...toArray(ssrOptions.noExternal))
}
}
if (process.env.VITE_NODE_DEBUG_DUMP) {
options.debug = Object.assign(<DebuggerOptions>{
dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === 'load',
}, options.debug ?? {})
}
if (options.debug)
this.debugger = new Debugger(server.config.root, options.debug!)
}
shouldExternalize(id: string) {
return shouldExternalize(id, this.options.deps, this.externalizeCache)
}
async resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null> {
if (importer && !importer.startsWith(this.server.config.root))
importer = resolve(this.server.config.root, importer)
const mode = (importer && this.getTransformMode(importer)) || 'ssr'
return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === 'ssr' })
}
getSourceMap(source: string) {
const fetchResult = this.fetchCache.get(source)?.result
if (fetchResult?.map)
return fetchResult.map
const ssrTransformResult = this.server.moduleGraph.getModuleById(source)?.ssrTransformResult
return (ssrTransformResult?.map || null) as unknown as RawSourceMap | null
}
async fetchModule(id: string): Promise<FetchResult> {
id = normalizeModuleId(id)
// reuse transform for concurrent requests
if (!this.fetchPromiseMap.has(id)) {
this.fetchPromiseMap.set(id,
this._fetchModule(id)
.then((r) => {
return this.options.sourcemap !== true ? { ...r, map: undefined } : r
})
.finally(() => {
this.fetchPromiseMap.delete(id)
}),
)
}
return this.fetchPromiseMap.get(id)!
}
async transformRequest(id: string) {
// reuse transform for concurrent requests
if (!this.transformPromiseMap.has(id)) {
this.transformPromiseMap.set(id,
this._transformRequest(id)
.finally(() => {
this.transformPromiseMap.delete(id)
}),
)
}
return this.transformPromiseMap.get(id)!
}
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 _fetchModule(id: string): Promise<FetchResult> {
let result: FetchResult
const { path: filePath } = toFilePath(id, this.server.config.root)
const module = this.server.moduleGraph.getModuleById(id)
const timestamp = module ? module.lastHMRTimestamp : null
const cache = this.fetchCache.get(filePath)
if (timestamp && cache && cache.timestamp >= timestamp)
return cache.result
const time = Date.now()
const externalize = await this.shouldExternalize(filePath)
let duration: number | undefined
if (externalize) {
result = { externalize }
this.debugger?.recordExternalize(id, externalize)
}
else {
const start = performance.now()
const r = await this._transformRequest(id)
duration = performance.now() - start
result = { code: r?.code, map: r?.map as unknown as RawSourceMap }
}
this.fetchCache.set(filePath, {
duration,
timestamp: time,
result,
})
return result
}
private async _transformRequest(id: string) {
debugRequest(id)
let result: TransformResult | null = null
if (this.options.debug?.loadDumppedModules) {
result = await this.debugger?.loadDump(id) ?? null
if (result)
return result
}
if (this.getTransformMode(id) === 'web') {
// for components like Vue, we want to use the client side
// plugins but then convert 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 })
}
const sourcemap = this.options.sourcemap ?? 'inline'
if (sourcemap === 'inline' && result && !id.includes('node_modules'))
withInlineSourcemap(result)
if (this.options.debug?.dumpModules)
await this.debugger?.dumpFile(id, result)
return result
}
}