/
index.ts
716 lines (655 loc) · 19.2 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
import fs from 'fs'
import path from 'path'
import * as net from 'net'
import * as http from 'http'
import * as https from 'https'
import connect from 'connect'
import corsMiddleware from 'cors'
import chalk from 'chalk'
import { AddressInfo } from 'net'
import chokidar from 'chokidar'
import { resolveHttpsConfig, resolveHttpServer } from './http'
import { resolveConfig, InlineConfig, ResolvedConfig } from '../config'
import {
createPluginContainer,
PluginContainer
} from '../server/pluginContainer'
import { FSWatcher, WatchOptions } from 'types/chokidar'
import { createWebSocketServer, WebSocketServer } from '../server/ws'
import { baseMiddleware } from './middlewares/base'
import { proxyMiddleware, ProxyOptions } from './middlewares/proxy'
import { transformMiddleware } from './middlewares/transform'
import {
createDevHtmlTransformFn,
indexHtmlMiddleware
} from './middlewares/indexHtml'
import history from 'connect-history-api-fallback'
import { decodeURIMiddleware } from './middlewares/decodeURI'
import {
serveRawFsMiddleware,
servePublicMiddleware,
serveStaticMiddleware
} from './middlewares/static'
import { timeMiddleware } from './middlewares/time'
import { ModuleGraph, ModuleNode } from './moduleGraph'
import { Connect } from 'types/connect'
import { createDebugger, normalizePath } from '../utils'
import { errorMiddleware, prepareError } from './middlewares/error'
import { handleHMRUpdate, HmrOptions, handleFileAddUnlink } from './hmr'
import { openBrowser } from './openBrowser'
import launchEditorMiddleware from 'launch-editor-middleware'
import { TransformResult } from 'rollup'
import { TransformOptions, transformRequest } from './transformRequest'
import {
transformWithEsbuild,
ESBuildTransformResult
} from '../plugins/esbuild'
import { TransformOptions as EsbuildTransformOptions } from 'esbuild'
import { DepOptimizationMetadata, optimizeDeps } from '../optimizer'
import { ssrLoadModule } from '../ssr/ssrModuleLoader'
import { resolveSSRExternal } from '../ssr/ssrExternal'
import { ssrRewriteStacktrace } from '../ssr/ssrStacktrace'
import { createMissingImporterRegisterFn } from '../optimizer/registerMissing'
import { printServerUrls } from '../logger'
import { resolveHostname } from '../utils'
import { searchForWorkspaceRoot } from './searchRoot'
export interface ServerOptions {
host?: string | boolean
port?: number
/**
* Enable TLS + HTTP/2.
* Note: this downgrades to TLS only when the proxy option is also used.
*/
https?: boolean | https.ServerOptions
/**
* Open browser window on startup
*/
open?: boolean | string
/**
* Force dep pre-optimization regardless of whether deps have changed.
*/
force?: boolean
/**
* Configure HMR-specific options (port, host, path & protocol)
*/
hmr?: HmrOptions | boolean
/**
* chokidar watch options
* https://github.com/paulmillr/chokidar#api
*/
watch?: WatchOptions
/**
* Configure custom proxy rules for the dev server. Expects an object
* of `{ key: options }` pairs.
* Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
* Full options [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | ProxyOptions>
/**
* Configure CORS for the dev server.
* Uses https://github.com/expressjs/cors.
* Set to `true` to allow all methods from any origin, or configure separately
* using an object.
*/
cors?: CorsOptions | boolean
/**
* If enabled, vite will exit if specified port is already in use
*/
strictPort?: boolean
/**
* 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/'.
*/
fsServe?: FileSystemServeOptions
}
export interface ResolvedServerOptions extends ServerOptions {
fsServe: Required<FileSystemServeOptions>
}
export interface FileSystemServeOptions {
/**
* Strictly restrict file accessing outside of allowing paths.
*
* Default to false at this moment, will enabled by default in the future versions.
* @expiremental
* @default false
*/
strict?: boolean
/**
* Restrict accessing files outside this directory will result in a 403.
*
* Accepts absolute path or a path relative to project root.
* Will try to search up for workspace root by default.
*
* @expiremental
*/
root?: string
}
/**
* https://github.com/expressjs/cors#configuration-options
*/
export interface CorsOptions {
origin?:
| CorsOrigin
| ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void)
methods?: string | string[]
allowedHeaders?: string | string[]
exposedHeaders?: string | string[]
credentials?: boolean
maxAge?: number
preflightContinue?: boolean
optionsSuccessStatus?: number
}
export type CorsOrigin = boolean | string | RegExp | (string | RegExp)[]
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
/**
* @deprecated use `server.middlewares` instead
*/
app: 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>
/**
* Util for transforming a file with esbuild.
* Can be useful for certain plugins.
*/
transformWithEsbuild(
code: string,
filename: string,
options?: EsbuildTransformOptions,
inMap?: object
): Promise<ESBuildTransformResult>
/**
* Load a given URL as an instantiated module for SSR.
*/
ssrLoadModule(url: string): Promise<Record<string, any>>
/**
* Fix ssr error stacktrace
*/
ssrFixStacktrace(e: Error): void
/**
* Start the server.
*/
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
/**
* Stop the server.
*/
close(): Promise<void>
/**
* @internal
*/
_optimizeDepsMetadata: DepOptimizationMetadata | null
/**
* Deps that are externalized
* @internal
*/
_ssrExternals: string[] | null
/**
* @internal
*/
_globImporters: Record<
string,
{
module: ModuleNode
importGlobs: {
base: string
pattern: string
}[]
}
>
/**
* @internal
*/
_isRunningOptimizer: boolean
/**
* @internal
*/
_registerMissingImport:
| ((id: string, resolved: string, ssr: boolean | undefined) => void)
| null
/**
* @internal
*/
_pendingReload: Promise<void> | null
}
export async function createServer(
inlineConfig: InlineConfig = {}
): Promise<ViteDevServer> {
const config = await resolveConfig(inlineConfig, 'serve', 'development')
const root = config.root
const serverConfig = config.server
const httpsOptions = await resolveHttpsConfig(config)
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/**', ...ignored],
ignoreInitial: true,
ignorePermissionErrors: true,
disableGlobbing: true,
...watchOptions
}) as FSWatcher
const plugins = config.plugins
const container = await createPluginContainer(config, watcher)
const moduleGraph = new ModuleGraph(container)
const closeHttpServer = createServerCloseFn(httpServer)
// eslint-disable-next-line prefer-const
let exitProcess: () => void
const server: ViteDevServer = {
config: config,
middlewares,
get app() {
config.logger.warn(
`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`
)
return middlewares
},
httpServer,
watcher,
pluginContainer: container,
ws,
moduleGraph,
transformWithEsbuild,
transformRequest(url, options) {
return transformRequest(url, server, options)
},
transformIndexHtml: null as any,
ssrLoadModule(url) {
if (!server._ssrExternals) {
server._ssrExternals = resolveSSRExternal(
config,
server._optimizeDepsMetadata
? Object.keys(server._optimizeDepsMetadata.optimized)
: []
)
}
return ssrLoadModule(url, server)
},
ssrFixStacktrace(e) {
if (e.stack) {
e.stack = ssrRewriteStacktrace(e.stack, moduleGraph)
}
},
listen(port?: number, isRestart?: boolean) {
return startServer(server, port, isRestart)
},
async close() {
process.off('SIGTERM', exitProcess)
if (!process.stdin.isTTY) {
process.stdin.off('end', exitProcess)
}
await Promise.all([
watcher.close(),
ws.close(),
container.close(),
closeHttpServer()
])
},
_optimizeDepsMetadata: null,
_ssrExternals: null,
_globImporters: {},
_isRunningOptimizer: false,
_registerMissingImport: null,
_pendingReload: null
}
server.transformIndexHtml = createDevHtmlTransformFn(server)
exitProcess = async () => {
try {
await server.close()
} finally {
process.exit(0)
}
}
process.once('SIGTERM', exitProcess)
if (process.env.CI !== 'true') {
process.stdin.on('end', exitProcess)
process.stdin.resume()
}
watcher.on('change', async (file) => {
file = normalizePath(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, true)
})
// apply server configuration hooks from plugins
const postHooks: ((() => void) | void)[] = []
for (const plugin of 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, config))
}
// base
if (config.base !== '/') {
middlewares.use(baseMiddleware(server))
}
// open in editor support
middlewares.use('/__open-in-editor', launchEditorMiddleware())
// hmr reconnect ping
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) {
res.end('pong')
})
//decode request url
middlewares.use(decodeURIMiddleware())
// 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))
}
// main transform middleware
middlewares.use(transformMiddleware(server))
// serve static files
middlewares.use(serveRawFsMiddleware(config))
middlewares.use(serveStaticMiddleware(root, config))
// spa fallback
if (!middlewareMode || middlewareMode === 'html') {
middlewares.use(
history({
logger: createDebugger('vite:spa-fallback'),
// support /dir/ without explicit index.html
rewrites: [
{
from: /\/$/,
to({ parsedUrl }: any) {
const rewritten = parsedUrl.pathname + 'index.html'
if (fs.existsSync(path.join(root, rewritten))) {
return rewritten
} else {
return `/index.html`
}
}
}
]
})
)
}
// 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 (!middlewareMode || middlewareMode === 'html') {
// transform index.html
middlewares.use(indexHtmlMiddleware(server))
// 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 runOptimize = async () => {
if (config.cacheDir) {
server._isRunningOptimizer = true
try {
server._optimizeDepsMetadata = await optimizeDeps(config)
} finally {
server._isRunningOptimizer = false
}
server._registerMissingImport = createMissingImporterRegisterFn(server)
}
}
if (!middlewareMode && httpServer) {
// overwrite listen to run optimizer before server start
const listen = httpServer.listen.bind(httpServer)
httpServer.listen = (async (port: number, ...args: any[]) => {
try {
await container.buildStart({})
await runOptimize()
} catch (e) {
httpServer.emit('error', e)
return
}
return listen(port, ...args)
}) as any
httpServer.once('listening', () => {
// update actual port since this may be different from initial value
serverConfig.port = (httpServer.address() as AddressInfo).port
})
} else {
await container.buildStart({})
await runOptimize()
}
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
let port = inlinePort || options.port || 3000
const hostname = resolveHostname(options.host)
const protocol = options.https ? 'https' : 'http'
const info = server.config.logger.info
const base = server.config.base
return new Promise((resolve, reject) => {
const onError = (e: Error & { code?: string }) => {
if (e.code === 'EADDRINUSE') {
if (options.strictPort) {
httpServer.removeListener('error', onError)
reject(new Error(`Port ${port} is already in use`))
} else {
info(`Port ${port} is in use, trying another one...`)
httpServer.listen(++port, hostname.host)
}
} else {
httpServer.removeListener('error', onError)
reject(e)
}
}
httpServer.on('error', onError)
httpServer.listen(port, hostname.host, () => {
httpServer.removeListener('error', onError)
info(
chalk.cyan(`\n vite v${require('vite/package.json').version}`) +
chalk.green(` dev server running at:\n`),
{
clear: !server.config.logger.hasWarned
}
)
printServerUrls(hostname, protocol, port, base, info)
// @ts-ignore
if (global.__vite_start_time) {
info(
chalk.cyan(
// @ts-ignore
`\n ready in ${Date.now() - global.__vite_start_time}ms.\n`
)
)
}
// @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(
chalk.yellow(
` CPU profile written to ${chalk.white.dim(outPath)}\n`
)
)
} else {
throw err
}
})
}
if (options.open && !isRestart) {
const path = typeof options.open === 'string' ? options.open : base
openBrowser(
`${protocol}://${hostname.name}:${port}${path}`,
true,
server.config.logger
)
}
resolve(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()
}
})
}
export function resolveServerOptions(
root: string,
raw?: ServerOptions
): ResolvedServerOptions {
const server = raw || {}
const fsServeRoot = normalizePath(
path.resolve(root, server.fsServe?.root || searchForWorkspaceRoot(root))
)
// TODO: make strict by default
const fsServeStrict = server.fsServe?.strict ?? false
server.fsServe = {
root: fsServeRoot,
strict: fsServeStrict
}
return server as ResolvedServerOptions
}