-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathssrLoadModule.spec.ts
317 lines (287 loc) · 8.44 KB
/
ssrLoadModule.spec.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import fs from 'node:fs'
import { stripVTControlCharacters } from 'node:util'
import { expect, onTestFinished, test, vi } from 'vitest'
import { createServer } from '../../server'
import { normalizePath } from '../../utils'
const root = fileURLToPath(new URL('./', import.meta.url))
async function createDevServer() {
const server = await createServer({
configFile: false,
root,
logLevel: 'silent',
optimizeDeps: {
noDiscovery: true,
},
})
server.pluginContainer.buildStart({})
return server
}
test('ssrLoad', async () => {
expect.assertions(1)
const server = await createDevServer()
const moduleRelativePath = '/fixtures/modules/has-invalid-import.js'
const moduleAbsolutePath = normalizePath(path.join(root, moduleRelativePath))
try {
await server.ssrLoadModule(moduleRelativePath)
} catch (e) {
expect(e.message).toBe(
`Failed to load url ./non-existent.js (resolved id: ./non-existent.js) in ${moduleAbsolutePath}. Does the file exist?`,
)
}
})
test('error has same instance', async () => {
expect.assertions(3)
const s = Symbol()
const server = await createDevServer()
try {
await server.ssrLoadModule('/fixtures/modules/has-error.js')
} catch (e) {
expect(e[s]).toBeUndefined()
e[s] = true
expect(e[s]).toBe(true)
}
try {
await server.ssrLoadModule('/fixtures/modules/has-error.js')
} catch (e) {
expect(e[s]).toBe(true)
}
})
test('import.meta.filename/dirname returns same value with Node', async () => {
const server = await createDevServer()
const moduleRelativePath = '/fixtures/modules/import-meta.js'
const filename = path.resolve(root, '.' + moduleRelativePath)
const viteValue = await server.ssrLoadModule(moduleRelativePath)
expect(viteValue.dirname).toBe(path.dirname(filename))
expect(viteValue.filename).toBe(filename)
})
test('virtual module invalidation simple', async () => {
const server = await createServer({
configFile: false,
root,
logLevel: 'silent',
optimizeDeps: {
noDiscovery: true,
},
plugins: [
{
name: 'virtual-test',
resolveId(id) {
if (id === 'virtual:test') {
return '\0virtual:test'
}
},
load(id) {
if (id === '\0virtual:test') {
return `
globalThis.__virtual_test_state ??= 0;
globalThis.__virtual_test_state++;
export default globalThis.__virtual_test_state;
`
}
},
},
],
})
await server.pluginContainer.buildStart({})
const mod1 = await server.ssrLoadModule('virtual:test')
expect(mod1.default).toEqual(1)
const mod2 = await server.ssrLoadModule('virtual:test')
expect(mod2.default).toEqual(1)
const modNode = server.moduleGraph.getModuleById('\0virtual:test')
server.moduleGraph.invalidateModule(modNode!)
const mod3 = await server.ssrLoadModule('virtual:test')
expect(mod3.default).toEqual(2)
})
test('virtual module invalidation nested', async () => {
const server = await createServer({
configFile: false,
root,
logLevel: 'silent',
optimizeDeps: {
noDiscovery: true,
},
plugins: [
{
name: 'test-virtual',
resolveId(id) {
if (id === 'virtual:test') {
return '\0virtual:test'
}
},
load(id) {
if (id === '\0virtual:test') {
return `
import testDep from "virtual:test-dep";
export default testDep;
`
}
},
},
{
name: 'test-virtual-dep',
resolveId(id) {
if (id === 'virtual:test-dep') {
return '\0virtual:test-dep'
}
},
load(id) {
if (id === '\0virtual:test-dep') {
return `
globalThis.__virtual_test_state2 ??= 0;
globalThis.__virtual_test_state2++;
export default globalThis.__virtual_test_state2;
`
}
},
},
],
})
await server.pluginContainer.buildStart({})
const mod1 = await server.ssrLoadModule('virtual:test')
expect(mod1.default).toEqual(1)
const mod2 = await server.ssrLoadModule('virtual:test')
expect(mod2.default).toEqual(1)
server.moduleGraph.invalidateModule(
server.moduleGraph.getModuleById('\0virtual:test')!,
)
server.moduleGraph.invalidateModule(
server.moduleGraph.getModuleById('\0virtual:test-dep')!,
)
const mod3 = await server.ssrLoadModule('virtual:test')
expect(mod3.default).toEqual(2)
})
test('can export global', async () => {
const server = await createDevServer()
const mod = await server.ssrLoadModule('/fixtures/global/export.js')
expect(mod.global).toBe('ok')
})
test('can access nodejs global', async () => {
const server = await createDevServer()
const mod = await server.ssrLoadModule('/fixtures/global/test.js')
expect(mod.default).toBe(globalThis)
})
test('parse error', async () => {
const server = await createDevServer()
function stripRoot(s?: string) {
return (s || '').replace(server.config.root, '<root>')
}
for (const file of [
'/fixtures/errors/syntax-error.ts',
'/fixtures/errors/syntax-error.js',
'/fixtures/errors/syntax-error-dep.ts',
'/fixtures/errors/syntax-error-dep.js',
]) {
try {
await server.ssrLoadModule(file)
} catch (e) {
expect(e).toBeInstanceOf(Error)
expect({
message: stripRoot(e.message),
frame: stripVTControlCharacters(e.frame || ''),
id: stripRoot(e.id),
loc: e.loc && {
file: stripRoot(e.loc.file),
column: e.loc.column,
line: e.loc.line,
},
}).toMatchSnapshot()
continue
}
expect.unreachable()
}
})
test('json', async () => {
const server = await createDevServer()
const mod = await server.ssrLoadModule('/fixtures/json/test.json')
expect(mod).toMatchInlineSnapshot(`
{
"default": {
"hello": "this is json",
},
"hello": "this is json",
}
`)
const source = fs.readFileSync(
path.join(root, 'fixtures/json/test.json'),
'utf-8',
)
const json = await server.ssrTransform(
`export default ${source}`,
null,
'/test.json',
)
expect(json?.code.length).toMatchInlineSnapshot(`61`)
})
test('file url', async () => {
const server = await createDevServer()
const mod = await server.ssrLoadModule(
new URL('./fixtures/file-url/test.js', import.meta.url).href,
)
expect(mod.msg).toBe('works')
const modWithSpace = await server.ssrLoadModule(
new URL('./fixtures/file-url/test space.js', import.meta.url).href,
)
expect(modWithSpace.msg).toBe('works')
})
test('plugin error', async () => {
const server = await createServer({
configFile: false,
root,
logLevel: 'error',
plugins: [
{
name: 'test-plugin',
resolveId(source) {
if (source === 'virtual:test') {
return '\0' + source
}
},
load(id) {
if (id === '\0virtual:test') {
return this.error('test-error')
}
},
},
],
})
onTestFinished(() => server.close())
const spy = vi
.spyOn(server.config.logger, 'error')
.mockImplementation(() => {})
try {
await server.ssrLoadModule('virtual:test')
expect.unreachable()
} catch {}
expect(
stripVTControlCharacters(spy.mock.lastCall![0])
.split('\n')
.slice(0, 2)
.join('\n'),
).toMatchInlineSnapshot(`
"Error when evaluating SSR module virtual:test: test-error
Plugin: test-plugin"
`)
})
test('named exports overwrite export all', async () => {
const server = await createDevServer()
const mod = await server.ssrLoadModule(
'./fixtures/named-overwrite-all/main.js',
)
// ESM spec doesn't allow conflicting `export *` and such duplicate exports are removed (in this case "d"),
// but this is likely not possible to support due to Vite dev SSR's lazy nature.
// [Node]
// $ node -e 'import("./packages/vite/src/node/ssr/__tests__/fixtures/named-overwrite-all/main.js").then(console.log)'
// [Module: null prototype] { a: 'main-a', b: 'dep1-b', c: 'main-c' }
// [Rollup]
// Conflicting namespaces: "main.js" re-exports "d" from one of the modules "dep1.js" and "dep2.js" (will be ignored).
expect(mod).toMatchInlineSnapshot(`
{
"a": "main-a",
"b": "dep1-b",
"c": "main-c",
"d": "dep1-d",
}
`)
})