/
index.ts
574 lines (528 loc) · 15.4 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
import os from 'os'
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 { resolveConfig, InlineConfig, ResolvedConfig } from '../config'
import {
createPluginContainer,
PluginContainer
} from '../server/pluginContainer'
import { FSWatcher, WatchOptions } from 'types/chokidar'
import { resolveHttpsConfig } from '../server/https'
import { createWebSocketServer, WebSocketServer } from '../server/ws'
import { proxyMiddleware, ProxyOptions } from './middlewares/proxy'
import { transformMiddleware } from './middlewares/transform'
import { indexHtmlMiddleware } from './middlewares/indexHtml'
import history from 'connect-history-api-fallback'
import {
rawFsStaticMiddleware,
serveStaticMiddleware
} from './middlewares/static'
import { timeMiddleware } from './middlewares/time'
import { ModuleGraph } from './moduleGraph'
import { Connect } from 'types/connect'
import { createDebugger, normalizePath } from '../utils'
import { errorMiddleware, prepareError } from './middlewares/error'
import { handleHMRUpdate, HmrOptions } 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'
export interface ServerOptions {
host?: string
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
}
/**
* 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
/**
* connect app instance
* This can also be used as the handler function of a custom http server
* https://github.com/senchalabs/connect#use-middleware
*/
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>
/**
* 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,
options?: { isolated?: boolean }
): Promise<Record<string, any>>
/**
* Fix ssr error stacktrace
*/
ssrFixStacktrace(e: Error): void
/**
* Start the server.
*/
listen(port?: number): Promise<ViteDevServer>
/**
* Stop the server.
*/
close(): Promise<void>
/**
* @internal
*/
_optimizeDepsMetadata: DepOptimizationMetadata | null
/**
* Deps that are extenralized
* @internal
*/
_ssrExternals: string[] | 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 middlewareMode = !!serverConfig.middlewareMode
const app = connect() as Connect.Server
const httpServer = middlewareMode
? null
: await resolveHttpServer(serverConfig, app)
const ws = createWebSocketServer(httpServer, config)
const watchOptions = serverConfig.watch || {}
const watcher = chokidar.watch(root, {
ignored: [
'**/node_modules/**',
'**/.git/**',
...(watchOptions.ignored || [])
],
ignoreInitial: true,
ignorePermissionErrors: true,
...watchOptions
}) as FSWatcher
const plugins = config.plugins
const container = await createPluginContainer(config, watcher)
const moduleGraph = new ModuleGraph(container)
const closeHttpServer = createSeverCloseFn(httpServer)
const server: ViteDevServer = {
config: config,
app,
httpServer,
watcher,
pluginContainer: container,
ws,
moduleGraph,
transformWithEsbuild,
transformRequest(url, options) {
return transformRequest(url, server, options)
},
ssrLoadModule(url, options) {
if (!server._ssrExternals) {
server._ssrExternals = resolveSSRExternal(config.root)
}
return ssrLoadModule(url, server, !!options?.isolated)
},
ssrFixStacktrace(e) {
if (e.stack) {
e.stack = ssrRewriteStacktrace(e.stack, moduleGraph)
}
},
listen(port?: number) {
return startServer(server, port)
},
async close() {
await Promise.all([
watcher.close(),
ws.close(),
container.close(),
closeHttpServer()
])
},
_optimizeDepsMetadata: null,
_ssrExternals: null
}
process.once('SIGTERM', async () => {
try {
await server.close()
} finally {
process.exit(0)
}
})
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)
})
}
}
})
// 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) {
app.use(timeMiddleware(root))
}
// cors (enabled by default)
const { cors } = serverConfig
if (cors !== false) {
app.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors))
}
// proxy
const { proxy } = serverConfig
if (proxy) {
app.use(proxyMiddleware(server))
}
// open in editor support
app.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.
app.use(serveStaticMiddleware(path.join(root, 'public')))
// main transform middleware
app.use(transformMiddleware(server))
// serve static files
app.use(rawFsStaticMiddleware())
app.use(serveStaticMiddleware(root, config))
// spa fallback
app.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())
// transform index.html
app.use(indexHtmlMiddleware(server, plugins))
// handle 404s
if (!middlewareMode) {
app.use((_, res) => {
res.statusCode = 404
res.end()
})
}
// error handler
app.use(errorMiddleware(server, middlewareMode))
const runOptimize = async () => {
if (config.optimizeCacheDir) {
// run optimizer
await optimizeDeps(config)
// after optimization, read updated optimization metadata
const dataPath = path.resolve(config.optimizeCacheDir, 'metadata.json')
if (fs.existsSync(dataPath)) {
server._optimizeDepsMetadata = JSON.parse(
fs.readFileSync(dataPath, 'utf-8')
)
}
}
}
if (httpServer) {
// overwrite listen to run optimizer before server start
const listen = httpServer.listen.bind(httpServer)
httpServer.listen = (async (port: number, ...args: any[]) => {
await container.buildStart({})
await runOptimize()
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 runOptimize()
}
return server
}
async function resolveHttpServer(
{ https = false, proxy }: ServerOptions,
app: Connect.Server
): Promise<http.Server> {
if (!https) {
return require('http').createServer(app)
}
const httpsOptions = await resolveHttpsConfig(
typeof https === 'boolean' ? {} : https
)
if (proxy) {
// #484 fallback to http1 when proxy is needed.
return require('https').createServer(httpsOptions, app)
} else {
return require('http2').createSecureServer(
{
...httpsOptions,
allowHTTP1: true
},
app
)
}
}
async function startServer(
server: ViteDevServer,
inlinePort?: number
): 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
let hostname = options.host || 'localhost'
const protocol = options.https ? 'https' : 'http'
const info = server.config.logger.info
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)
}
} else {
httpServer.removeListener('error', onError)
reject(e)
}
}
httpServer.on('error', onError)
httpServer.listen(port, () => {
httpServer.removeListener('error', onError)
info(`\n Vite dev server running at:\n`, { clear: true })
const interfaces = os.networkInterfaces()
Object.keys(interfaces).forEach((key) =>
(interfaces[key] || [])
.filter((details) => details.family === 'IPv4')
.map((detail) => {
return {
type: detail.address.includes('127.0.0.1')
? 'Local: '
: 'Network: ',
host: detail.address.replace('127.0.0.1', hostname)
}
})
.forEach(({ type, host }) => {
const url = `${protocol}://${host}:${chalk.bold(port)}/`
info(` > ${type} ${chalk.cyan(url)}`)
})
)
// @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) {
const path = typeof options.open === 'string' ? options.open : ''
openBrowser(
`${protocol}://${hostname}:${port}${path}`,
true,
server.config.logger
)
}
resolve(server)
})
})
}
function createSeverCloseFn(server: http.Server | null) {
if (!server) {
return () => {}
}
const openSockets = new Set<net.Socket>()
server.on('connection', (socket) => {
openSockets.add(socket)
socket.on('close', () => {
openSockets.delete(socket)
})
})
return () =>
new Promise<void>((resolve, reject) => {
openSockets.forEach((s) => s.destroy())
server.close((err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}