forked from vitejs/vite
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
759 lines (689 loc) · 20 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import fs from 'fs'
import path from 'path'
import type * as net from 'net'
import type * as http from 'http'
import { performance } from 'perf_hooks'
import connect from 'connect'
import corsMiddleware from 'cors'
import colors from 'picocolors'
import chokidar from 'chokidar'
import type { FSWatcher, WatchOptions } from 'types/chokidar'
import type { Connect } from 'types/connect'
import launchEditorMiddleware from 'launch-editor-middleware'
import type { SourceMap } from 'rollup'
import type { CommonServerOptions } from '../http'
import { httpServerStart, resolveHttpServer, resolveHttpsConfig } from '../http'
import type { InlineConfig, ResolvedConfig } from '../config'
import { isDepsOptimizerEnabled, resolveConfig } from '../config'
import {
isParentDirectory,
mergeConfig,
normalizePath,
resolveHostname
} from '../utils'
import { ssrLoadModule } from '../ssr/ssrModuleLoader'
import { cjsSsrResolveExternals } from '../ssr/ssrExternal'
import {
rebindErrorStacktrace,
ssrRewriteStacktrace
} from '../ssr/ssrStacktrace'
import { ssrTransform } from '../ssr/ssrTransform'
import { getDepsOptimizer, initDepsOptimizer } from '../optimizer'
import { CLIENT_DIR } from '../constants'
import type { Logger } from '../logger'
import { printCommonServerUrls } from '../logger'
import { invalidatePackageData } from '../packages'
import type { PluginContainer } from './pluginContainer'
import { createPluginContainer } from './pluginContainer'
import type { WebSocketServer } from './ws'
import { createWebSocketServer } from './ws'
import { baseMiddleware } from './middlewares/base'
import { proxyMiddleware } from './middlewares/proxy'
import { spaFallbackMiddleware } from './middlewares/spaFallback'
import { transformMiddleware } from './middlewares/transform'
import {
createDevHtmlTransformFn,
indexHtmlMiddleware
} from './middlewares/indexHtml'
import {
servePublicMiddleware,
serveRawFsMiddleware,
serveStaticMiddleware
} from './middlewares/static'
import { timeMiddleware } from './middlewares/time'
import { ModuleGraph } from './moduleGraph'
import { errorMiddleware, prepareError } from './middlewares/error'
import type { HmrOptions } from './hmr'
import { handleFileAddUnlink, handleHMRUpdate } from './hmr'
import { openBrowser } from './openBrowser'
import type { TransformOptions, TransformResult } from './transformRequest'
import { transformRequest } from './transformRequest'
import { searchForWorkspaceRoot } from './searchRoot'
export { searchForWorkspaceRoot } from './searchRoot'
export interface ServerOptions extends CommonServerOptions {
/**
* Configure HMR-specific options (port, host, path & protocol)
*/
hmr?: HmrOptions | boolean
/**
* chokidar watch options
* https://github.com/paulmillr/chokidar#api
*/
watch?: WatchOptions
/**
* Create Vite dev server to be used as a middleware in an existing server
*/
middlewareMode?: boolean | 'html' | 'ssr'
/**
* Prepend this folder to http requests, for use when proxying vite as a subfolder
* Should start and end with the `/` character
*/
base?: string
/**
* Options for files served via '/\@fs/'.
*/
fs?: FileSystemServeOptions
/**
* Origin for the generated asset URLs.
*
* @example `http://127.0.0.1:8080`
*/
origin?: string
/**
* Pre-transform known direct imports
* @default true
*/
preTransformRequests?: boolean
}
export interface ResolvedServerOptions extends ServerOptions {
fs: Required<FileSystemServeOptions>
}
export interface FileSystemServeOptions {
/**
* Strictly restrict file accessing outside of allowing paths.
*
* Set to `false` to disable the warning
*
* @default true
*/
strict?: boolean
/**
* Restrict accessing files outside the allowed directories.
*
* Accepts absolute path or a path relative to project root.
* Will try to search up for workspace root by default.
*/
allow?: string[]
/**
* Restrict accessing files that matches the patterns.
*
* This will have higher priority than `allow`.
* Glob patterns are supported.
*
* @default ['.env', '.env.*', '*.crt', '*.pem']
*/
deny?: string[]
}
export type ServerHook = (
server: ViteDevServer
) => (() => void) | void | Promise<(() => void) | void>
export interface ViteDevServer {
/**
* The resolved vite config object
*/
config: ResolvedConfig
/**
* A connect app instance.
* - Can be used to attach custom middlewares to the dev server.
* - Can also be used as the handler function of a custom http server
* or as a middleware in any connect-style Node.js frameworks
*
* https://github.com/senchalabs/connect#use-middleware
*/
middlewares: Connect.Server
/**
* native Node http server instance
* will be null in middleware mode
*/
httpServer: http.Server | null
/**
* chokidar watcher instance
* https://github.com/paulmillr/chokidar#api
*/
watcher: FSWatcher
/**
* web socket server with `send(payload)` method
*/
ws: WebSocketServer
/**
* Rollup plugin container that can run plugin hooks on a given file
*/
pluginContainer: PluginContainer
/**
* Module graph that tracks the import relationships, url to file mapping
* and hmr state.
*/
moduleGraph: ModuleGraph
/**
* Programmatically resolve, load and transform a URL and get the result
* without going through the http request pipeline.
*/
transformRequest(
url: string,
options?: TransformOptions
): Promise<TransformResult | null>
/**
* Apply vite built-in HTML transforms and any plugin HTML transforms.
*/
transformIndexHtml(
url: string,
html: string,
originalUrl?: string
): Promise<string>
/**
* Transform module code into SSR format.
*/
ssrTransform(
code: string,
inMap: SourceMap | null,
url: string
): Promise<TransformResult | null>
/**
* Load a given URL as an instantiated module for SSR.
*/
ssrLoadModule(
url: string,
opts?: { fixStacktrace?: boolean }
): Promise<Record<string, any>>
/**
* Returns a fixed version of the given stack
*/
ssrRewriteStacktrace(stack: string): string
/**
* Mutates the given SSR error by rewriting the stacktrace
*/
ssrFixStacktrace(e: Error): void
/**
* Start the server.
*/
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
/**
* Stop the server.
*/
close(): Promise<void>
/**
* Print server urls
*/
printUrls(): void
/**
* Restart the server.
*
* @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
*/
restart(forceOptimize?: boolean): Promise<void>
/**
* @internal
*/
_importGlobMap: Map<string, string[][]>
/**
* Deps that are externalized
* @internal
*/
_ssrExternals: string[] | null
/**
* @internal
*/
_restartPromise: Promise<void> | null
/**
* @internal
*/
_forceOptimizeOnRestart: boolean
/**
* @internal
*/
_pendingRequests: Map<
string,
{
request: Promise<TransformResult | null>
timestamp: number
abort: () => void
}
>
}
export async function createServer(
inlineConfig: InlineConfig = {}
): Promise<ViteDevServer> {
const config = await resolveConfig(inlineConfig, 'serve', 'development')
const { root, server: serverConfig } = config
const httpsOptions = await resolveHttpsConfig(
config.server.https,
config.cacheDir
)
let { middlewareMode } = serverConfig
if (middlewareMode === true) {
middlewareMode = 'ssr'
}
const middlewares = connect() as Connect.Server
const httpServer = middlewareMode
? null
: await resolveHttpServer(serverConfig, middlewares, httpsOptions)
const ws = createWebSocketServer(httpServer, config, httpsOptions)
const { ignored = [], ...watchOptions } = serverConfig.watch || {}
const watcher = chokidar.watch(path.resolve(root), {
ignored: [
'**/node_modules/**',
'**/.git/**',
...(Array.isArray(ignored) ? ignored : [ignored])
],
ignoreInitial: true,
ignorePermissionErrors: true,
disableGlobbing: true,
...watchOptions
}) as FSWatcher
const moduleGraph: ModuleGraph = new ModuleGraph((url, ssr) =>
container.resolveId(url, undefined, { ssr })
)
const container = await createPluginContainer(config, moduleGraph, watcher)
const closeHttpServer = createServerCloseFn(httpServer)
let exitProcess: () => void
const server: ViteDevServer = {
config,
middlewares,
httpServer,
watcher,
pluginContainer: container,
ws,
moduleGraph,
ssrTransform(code: string, inMap: SourceMap | null, url: string) {
return ssrTransform(code, inMap, url, {
json: { stringify: server.config.json?.stringify }
})
},
transformRequest(url, options) {
return transformRequest(url, server, options)
},
transformIndexHtml: null!, // to be immediately set
async ssrLoadModule(url, opts?: { fixStacktrace?: boolean }) {
await updateCjsSsrExternals(server)
return ssrLoadModule(
url,
server,
undefined,
undefined,
opts?.fixStacktrace
)
},
ssrFixStacktrace(e) {
if (e.stack) {
const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph)
rebindErrorStacktrace(e, stacktrace)
}
},
ssrRewriteStacktrace(stack: string) {
return ssrRewriteStacktrace(stack, moduleGraph)
},
listen(port?: number, isRestart?: boolean) {
return startServer(server, port, isRestart)
},
async close() {
if (!middlewareMode && process.env.CI !== 'true') {
process.off('SIGTERM', exitProcess)
process.stdin.off('end', exitProcess)
}
await Promise.all([
watcher.close(),
ws.close(),
container.close(),
closeHttpServer()
])
},
printUrls() {
if (httpServer) {
printCommonServerUrls(httpServer, config.server, config)
} else {
throw new Error('cannot print server URLs in middleware mode.')
}
},
async restart(forceOptimize?: boolean) {
if (!server._restartPromise) {
server._forceOptimizeOnRestart = !!forceOptimize
server._restartPromise = restartServer(server).finally(() => {
server._restartPromise = null
server._forceOptimizeOnRestart = false
})
}
return server._restartPromise
},
_ssrExternals: null,
_restartPromise: null,
_importGlobMap: new Map(),
_forceOptimizeOnRestart: false,
_pendingRequests: new Map()
}
server.transformIndexHtml = createDevHtmlTransformFn(server)
if (!middlewareMode && process.env.CI !== 'true') {
exitProcess = async () => {
try {
await server.close()
} finally {
process.exit()
}
}
process.once('SIGTERM', exitProcess)
process.stdin.on('end', exitProcess)
}
const { packageCache } = config
const setPackageData = packageCache.set.bind(packageCache)
packageCache.set = (id, pkg) => {
if (id.endsWith('.json')) {
watcher.add(id)
}
return setPackageData(id, pkg)
}
watcher.on('change', async (file) => {
file = normalizePath(file)
if (file.endsWith('/package.json')) {
return invalidatePackageData(packageCache, file)
}
// invalidate module graph cache on file change
moduleGraph.onFileChange(file)
if (serverConfig.hmr !== false) {
try {
await handleHMRUpdate(file, server)
} catch (err) {
ws.send({
type: 'error',
err: prepareError(err)
})
}
}
})
watcher.on('add', (file) => {
handleFileAddUnlink(normalizePath(file), server)
})
watcher.on('unlink', (file) => {
handleFileAddUnlink(normalizePath(file), server)
})
if (!middlewareMode && httpServer) {
httpServer.once('listening', () => {
// update actual port since this may be different from initial value
serverConfig.port = (httpServer.address() as net.AddressInfo).port
})
}
// apply server configuration hooks from plugins
const postHooks: ((() => void) | void)[] = []
for (const plugin of config.plugins) {
if (plugin.configureServer) {
postHooks.push(await plugin.configureServer(server))
}
}
// Internal middlewares ------------------------------------------------------
// request timer
if (process.env.DEBUG) {
middlewares.use(timeMiddleware(root))
}
// cors (enabled by default)
const { cors } = serverConfig
if (cors !== false) {
middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors))
}
// proxy
const { proxy } = serverConfig
if (proxy) {
middlewares.use(proxyMiddleware(httpServer, proxy, config))
}
// base
if (config.base !== '/') {
middlewares.use(baseMiddleware(server))
}
// open in editor support
middlewares.use('/__open-in-editor', launchEditorMiddleware())
// serve static files under /public
// this applies before the transform middleware so that these files are served
// as-is without transforms.
if (config.publicDir) {
middlewares.use(
servePublicMiddleware(config.publicDir, config.server.headers)
)
}
// main transform middleware
middlewares.use(transformMiddleware(server))
// serve static files
middlewares.use(serveRawFsMiddleware(server))
middlewares.use(serveStaticMiddleware(root, server))
const isMiddlewareMode = middlewareMode && middlewareMode !== 'html'
// spa fallback
if (config.spa && !isMiddlewareMode) {
middlewares.use(spaFallbackMiddleware(root))
}
// run post config hooks
// This is applied before the html middleware so that user middleware can
// serve custom content instead of index.html.
postHooks.forEach((fn) => fn && fn())
if (config.spa && !isMiddlewareMode) {
// transform index.html
middlewares.use(indexHtmlMiddleware(server))
}
if (!isMiddlewareMode) {
// handle 404s
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
middlewares.use(function vite404Middleware(_, res) {
res.statusCode = 404
res.end()
})
}
// error handler
middlewares.use(errorMiddleware(server, !!middlewareMode))
const initOptimizer = async () => {
if (isDepsOptimizerEnabled(config)) {
await initDepsOptimizer(config, server)
}
}
if (!middlewareMode && httpServer) {
let isOptimized = false
// overwrite listen to init optimizer before server start
const listen = httpServer.listen.bind(httpServer)
httpServer.listen = (async (port: number, ...args: any[]) => {
if (!isOptimized) {
try {
await container.buildStart({})
await initOptimizer()
isOptimized = true
} catch (e) {
httpServer.emit('error', e)
return
}
}
return listen(port, ...args)
}) as any
} else {
await container.buildStart({})
await initOptimizer()
}
return server
}
async function startServer(
server: ViteDevServer,
inlinePort?: number,
isRestart: boolean = false
): Promise<ViteDevServer> {
const httpServer = server.httpServer
if (!httpServer) {
throw new Error('Cannot call server.listen in middleware mode.')
}
const options = server.config.server
const port = inlinePort ?? options.port ?? 5173
const hostname = resolveHostname(options.host)
const protocol = options.https ? 'https' : 'http'
const info = server.config.logger.info
const base = server.config.base
const serverPort = await httpServerStart(httpServer, {
port,
strictPort: options.strictPort,
host: hostname.host,
logger: server.config.logger
})
// @ts-ignore
const profileSession = global.__vite_profile_session
if (profileSession) {
profileSession.post('Profiler.stop', (err: any, { profile }: any) => {
// Write profile to disk, upload, etc.
if (!err) {
const outPath = path.resolve('./vite-profile.cpuprofile')
fs.writeFileSync(outPath, JSON.stringify(profile))
info(
colors.yellow(
` CPU profile written to ${colors.white(colors.dim(outPath))}\n`
)
)
} else {
throw err
}
})
}
if (options.open && !isRestart) {
const path = typeof options.open === 'string' ? options.open : base
openBrowser(
path.startsWith('http')
? path
: `${protocol}://${hostname.name}:${serverPort}${path}`,
true,
server.config.logger
)
}
return server
}
function createServerCloseFn(server: http.Server | null) {
if (!server) {
return () => {}
}
let hasListened = false
const openSockets = new Set<net.Socket>()
server.on('connection', (socket) => {
openSockets.add(socket)
socket.on('close', () => {
openSockets.delete(socket)
})
})
server.once('listening', () => {
hasListened = true
})
return () =>
new Promise<void>((resolve, reject) => {
openSockets.forEach((s) => s.destroy())
if (hasListened) {
server.close((err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
} else {
resolve()
}
})
}
function resolvedAllowDir(root: string, dir: string): string {
return normalizePath(path.resolve(root, dir))
}
export function resolveServerOptions(
root: string,
raw: ServerOptions | undefined,
logger: Logger
): ResolvedServerOptions {
const server: ResolvedServerOptions = {
preTransformRequests: true,
...(raw as ResolvedServerOptions)
}
let allowDirs = server.fs?.allow
const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}']
if (!allowDirs) {
allowDirs = [searchForWorkspaceRoot(root)]
}
allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i))
// only push client dir when vite itself is outside-of-root
const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR)
if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) {
allowDirs.push(resolvedClientDir)
}
server.fs = {
strict: server.fs?.strict ?? true,
allow: allowDirs,
deny
}
if (server.origin?.endsWith('/')) {
server.origin = server.origin.slice(0, -1)
logger.warn(
colors.yellow(
`${colors.bold('(!)')} server.origin should not end with "/". Using "${
server.origin
}" instead.`
)
)
}
return server
}
async function restartServer(server: ViteDevServer) {
// @ts-ignore
global.__vite_start_time = performance.now()
const { port: prevPort, host: prevHost } = server.config.server
await server.close()
let inlineConfig = server.config.inlineConfig
if (server._forceOptimizeOnRestart) {
inlineConfig = mergeConfig(inlineConfig, {
server: {
force: true
}
})
}
let newServer = null
try {
newServer = await createServer(inlineConfig)
} catch (err: any) {
server.config.logger.error(err.message, {
timestamp: true
})
return
}
for (const key in newServer) {
if (key === '_restartPromise') {
// prevent new server `restart` function from calling
// @ts-ignore
newServer[key] = server[key]
} else if (key !== 'app') {
// @ts-ignore
server[key] = newServer[key]
}
}
const {
logger,
server: { port, host, middlewareMode }
} = server.config
if (!middlewareMode) {
await server.listen(port, true)
logger.info('server restarted.', { timestamp: true })
if (port !== prevPort || host !== prevHost) {
logger.info('')
server.printUrls()
}
} else {
logger.info('server restarted.', { timestamp: true })
}
// new server (the current server) can restart now
newServer._restartPromise = null
}
async function updateCjsSsrExternals(server: ViteDevServer) {
if (!server._ssrExternals) {
let knownImports: string[] = []
const depsOptimizer = getDepsOptimizer(server.config)
if (depsOptimizer) {
await depsOptimizer.scanProcessing
knownImports = [
...Object.keys(depsOptimizer.metadata.optimized),
...Object.keys(depsOptimizer.metadata.discovered)
]
}
server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports)
}
}