-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
index.ts
1062 lines (974 loc) · 30.1 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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'node:path'
import type * as net from 'node:net'
import { get as httpGet } from 'node:http'
import { get as httpsGet } from 'node:https'
import type * as http from 'node:http'
import { performance } from 'node:perf_hooks'
import type { Http2SecureServer } from 'node:http2'
import connect from 'connect'
import corsMiddleware from 'cors'
import colors from 'picocolors'
import chokidar from 'chokidar'
import type { FSWatcher, WatchOptions } from 'dep-types/chokidar'
import type { Connect } from 'dep-types/connect'
import launchEditorMiddleware from 'launch-editor-middleware'
import type { SourceMap } from 'rollup'
import picomatch from 'picomatch'
import type { Matcher } from 'picomatch'
import type { InvalidatePayload } from 'types/customEvent'
import type { CommonServerOptions } from '../http'
import {
httpServerStart,
resolveHttpServer,
resolveHttpsConfig,
setClientErrorHandler,
} from '../http'
import type { InlineConfig, ResolvedConfig } from '../config'
import { isDepsOptimizerEnabled, resolveConfig } from '../config'
import {
diffDnsOrderChange,
isInNodeModules,
isObject,
isParentDirectory,
mergeConfig,
normalizePath,
resolveHostname,
resolveServerUrls,
} from '../utils'
import { getFsUtils } from '../fsUtils'
import { ssrLoadModule } from '../ssr/ssrModuleLoader'
import { ssrFixStacktrace, ssrRewriteStacktrace } from '../ssr/ssrStacktrace'
import { ssrTransform } from '../ssr/ssrTransform'
import { ERR_OUTDATED_OPTIMIZED_DEP } from '../plugins/optimizedDeps'
import {
getDepsOptimizer,
initDepsOptimizer,
initDevSsrDepsOptimizer,
} from '../optimizer'
import { bindCLIShortcuts } from '../shortcuts'
import type { BindCLIShortcutsOptions } from '../shortcuts'
import { CLIENT_DIR, DEFAULT_DEV_PORT } from '../constants'
import type { Logger } from '../logger'
import { printServerUrls } from '../logger'
import { createNoopWatcher, resolveChokidarOptions } from '../watch'
import { initPublicFiles } from '../publicDir'
import type { PluginContainer } from './pluginContainer'
import { ERR_CLOSED_SERVER, createPluginContainer } from './pluginContainer'
import type { WebSocketServer } from './ws'
import { createWebSocketServer } from './ws'
import { baseMiddleware } from './middlewares/base'
import { proxyMiddleware } from './middlewares/proxy'
import { htmlFallbackMiddleware } from './middlewares/htmlFallback'
import { transformMiddleware } from './middlewares/transform'
import {
createDevHtmlTransformFn,
indexHtmlMiddleware,
} from './middlewares/indexHtml'
import {
servePublicMiddleware,
serveRawFsMiddleware,
serveStaticMiddleware,
} from './middlewares/static'
import { timeMiddleware } from './middlewares/time'
import type { ModuleNode } from './moduleGraph'
import { ModuleGraph } from './moduleGraph'
import { notFoundMiddleware } from './middlewares/notFound'
import { errorMiddleware, prepareError } from './middlewares/error'
import type { HmrOptions } from './hmr'
import {
getShortName,
handleFileAddUnlink,
handleHMRUpdate,
updateModules,
} from './hmr'
import { openBrowser as _openBrowser } from './openBrowser'
import type { TransformOptions, TransformResult } from './transformRequest'
import { transformRequest } from './transformRequest'
import { searchForWorkspaceRoot } from './searchRoot'
import { warmupFiles } from './warmup'
export interface ServerOptions extends CommonServerOptions {
/**
* Configure HMR-specific options (port, host, path & protocol)
*/
hmr?: HmrOptions | boolean
/**
* Warm-up files to transform and cache the results in advance. This improves the
* initial page load during server starts and prevents transform waterfalls.
*/
warmup?: {
/**
* The files to be transformed and used on the client-side. Supports glob patterns.
*/
clientFiles?: string[]
/**
* The files to be transformed and used in SSR. Supports glob patterns.
*/
ssrFiles?: string[]
}
/**
* chokidar watch options or null to disable FS watching
* https://github.com/paulmillr/chokidar#api
*/
watch?: WatchOptions | null
/**
* Create Vite dev server to be used as a middleware in an existing server
* @default false
*/
middlewareMode?:
| boolean
| {
/**
* Parent server instance to attach to
*
* This is needed to proxy WebSocket connections to the parent server.
*/
server: http.Server
}
/**
* 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
/**
* Whether or not to ignore-list source files in the dev server sourcemap, used to populate
* the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
*
* By default, it excludes all paths containing `node_modules`. You can pass `false` to
* disable this behavior, or, for full control, a function that takes the source path and
* sourcemap path and returns whether to ignore the source path.
*/
sourcemapIgnoreList?:
| false
| ((sourcePath: string, sourcemapPath: string) => boolean)
}
export interface ResolvedServerOptions extends ServerOptions {
fs: Required<FileSystemServeOptions>
middlewareMode: boolean
sourcemapIgnoreList: Exclude<
ServerOptions['sourcemapIgnoreList'],
false | undefined
>
}
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`.
* picomatch patterns are supported.
*
* @default ['.env', '.env.*', '*.crt', '*.pem']
*/
deny?: string[]
/**
* Enable caching of fs calls.
*
* @experimental
* @default false
*/
cachedChecks?: boolean
}
export type ServerHook = (
this: void,
server: ViteDevServer,
) => (() => void) | void | Promise<(() => void) | void>
export type HttpServer = http.Server | Http2SecureServer
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: HttpServer | 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
/**
* The resolved urls Vite prints on the CLI. null in middleware mode or
* before `server.listen` is called.
*/
resolvedUrls: ResolvedServerUrls | null
/**
* 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>
/**
* Same as `transformRequest` but only warm up the URLs so the next request
* will already be cached. The function will never throw as it handles and
* reports errors internally.
*/
warmupRequest(url: string, options?: TransformOptions): Promise<void>
/**
* 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 | { mappings: '' } | null,
url: string,
originalCode?: 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
/**
* Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
* API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
*/
reloadModule(module: ModuleNode): Promise<void>
/**
* Start the server.
*/
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
/**
* Stop the server.
*/
close(): Promise<void>
/**
* Print server urls
*/
printUrls(): void
/**
* Bind CLI shortcuts
*/
bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void
/**
* Restart the server.
*
* @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
*/
restart(forceOptimize?: boolean): Promise<void>
/**
* Open browser
*/
openBrowser(): void
/**
* @internal
*/
_setInternalServer(server: ViteDevServer): void
/**
* @internal
*/
_importGlobMap: Map<string, { affirmed: string[]; negated: string[] }[]>
/**
* @internal
*/
_restartPromise: Promise<void> | null
/**
* @internal
*/
_forceOptimizeOnRestart: boolean
/**
* @internal
*/
_pendingRequests: Map<
string,
{
request: Promise<TransformResult | null>
timestamp: number
abort: () => void
}
>
/**
* @internal
*/
_fsDenyGlob: Matcher
/**
* @internal
*/
_shortcutsOptions?: BindCLIShortcutsOptions<ViteDevServer>
/**
* @internal
*/
_currentServerPort?: number | undefined
/**
* @internal
*/
_configServerPort?: number | undefined
}
export interface ResolvedServerUrls {
local: string[]
network: string[]
}
export function createServer(
inlineConfig: InlineConfig = {},
): Promise<ViteDevServer> {
return _createServer(inlineConfig, { ws: true })
}
export async function _createServer(
inlineConfig: InlineConfig = {},
options: { ws: boolean },
): Promise<ViteDevServer> {
const config = await resolveConfig(inlineConfig, 'serve')
const initPublicFilesPromise = initPublicFiles(config)
const { root, server: serverConfig } = config
const httpsOptions = await resolveHttpsConfig(config.server.https)
const { middlewareMode } = serverConfig
const resolvedWatchOptions = resolveChokidarOptions(config, {
disableGlobbing: true,
...serverConfig.watch,
})
const middlewares = connect() as Connect.Server
const httpServer = middlewareMode
? null
: await resolveHttpServer(serverConfig, middlewares, httpsOptions)
const ws = createWebSocketServer(httpServer, config, httpsOptions)
if (httpServer) {
setClientErrorHandler(httpServer, config.logger)
}
// eslint-disable-next-line eqeqeq
const watchEnabled = serverConfig.watch !== null
const watcher = watchEnabled
? (chokidar.watch(
// config file dependencies and env file might be outside of root
[...new Set([root, ...config.configFileDependencies, config.envDir])],
resolvedWatchOptions,
) as FSWatcher)
: createNoopWatcher(resolvedWatchOptions)
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 devHtmlTransformFn = createDevHtmlTransformFn(config)
let server: ViteDevServer = {
config,
middlewares,
httpServer,
watcher,
pluginContainer: container,
ws,
moduleGraph,
resolvedUrls: null, // will be set on listen
ssrTransform(
code: string,
inMap: SourceMap | { mappings: '' } | null,
url: string,
originalCode = code,
) {
return ssrTransform(code, inMap, url, originalCode, server.config)
},
transformRequest(url, options) {
return transformRequest(url, server, options)
},
async warmupRequest(url, options) {
await transformRequest(url, server, options).catch((e) => {
if (
e?.code === ERR_OUTDATED_OPTIMIZED_DEP ||
e?.code === ERR_CLOSED_SERVER
) {
// these are expected errors
return
}
// Unexpected error, log the issue but avoid an unhandled exception
server.config.logger.error(`Pre-transform error: ${e.message}`, {
error: e,
timestamp: true,
})
})
},
transformIndexHtml(url, html, originalUrl) {
return devHtmlTransformFn(server, url, html, originalUrl)
},
async ssrLoadModule(url, opts?: { fixStacktrace?: boolean }) {
if (isDepsOptimizerEnabled(config, true)) {
await initDevSsrDepsOptimizer(config, server)
}
return ssrLoadModule(
url,
server,
undefined,
undefined,
opts?.fixStacktrace,
)
},
ssrFixStacktrace(e) {
ssrFixStacktrace(e, moduleGraph)
},
ssrRewriteStacktrace(stack: string) {
return ssrRewriteStacktrace(stack, moduleGraph)
},
async reloadModule(module) {
if (serverConfig.hmr !== false && module.file) {
updateModules(module.file, [module], Date.now(), server)
}
},
async listen(port?: number, isRestart?: boolean) {
await startServer(server, port)
if (httpServer) {
server.resolvedUrls = await resolveServerUrls(
httpServer,
config.server,
config,
)
if (!isRestart && config.server.open) server.openBrowser()
}
return server
},
openBrowser() {
const options = server.config.server
const url =
server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0]
if (url) {
const path =
typeof options.open === 'string'
? new URL(options.open, url).href
: url
// We know the url that the browser would be opened to, so we can
// start the request while we are awaiting the browser. This will
// start the crawling of static imports ~500ms before.
// preTransformRequests needs to be enabled for this optimization.
if (server.config.server.preTransformRequests) {
setTimeout(() => {
const getMethod = path.startsWith('https:') ? httpsGet : httpGet
getMethod(
path,
{
headers: {
// Allow the history middleware to redirect to /index.html
Accept: 'text/html',
},
},
(res) => {
res.on('end', () => {
// Ignore response, scripts discovered while processing the entry
// will be preprocessed (server.config.server.preTransformRequests)
})
},
)
.on('error', () => {
// Ignore errors
})
.end()
}, 0)
}
_openBrowser(path, true, server.config.logger)
} else {
server.config.logger.warn('No URL available to open in browser')
}
},
async close() {
if (!middlewareMode) {
process.off('SIGTERM', exitProcess)
if (process.env.CI !== 'true') {
process.stdin.off('end', exitProcess)
}
}
await Promise.allSettled([
watcher.close(),
ws.close(),
container.close(),
getDepsOptimizer(server.config)?.close(),
getDepsOptimizer(server.config, true)?.close(),
closeHttpServer(),
])
// Await pending requests. We throw early in transformRequest
// and in hooks if the server is closing for non-ssr requests,
// so the import analysis plugin stops pre-transforming static
// imports and this block is resolved sooner.
// During SSR, we let pending requests finish to avoid exposing
// the server closed error to the users.
while (server._pendingRequests.size > 0) {
await Promise.allSettled(
[...server._pendingRequests.values()].map(
(pending) => pending.request,
),
)
}
server.resolvedUrls = null
},
printUrls() {
if (server.resolvedUrls) {
printServerUrls(
server.resolvedUrls,
serverConfig.host,
config.logger.info,
)
} else if (middlewareMode) {
throw new Error('cannot print server URLs in middleware mode.')
} else {
throw new Error(
'cannot print server URLs before server.listen is called.',
)
}
},
bindCLIShortcuts(options) {
bindCLIShortcuts(server, options)
},
async restart(forceOptimize?: boolean) {
if (!server._restartPromise) {
server._forceOptimizeOnRestart = !!forceOptimize
server._restartPromise = restartServer(server).finally(() => {
server._restartPromise = null
server._forceOptimizeOnRestart = false
})
}
return server._restartPromise
},
_setInternalServer(_server: ViteDevServer) {
// Rebind internal the server variable so functions reference the user
// server instance after a restart
server = _server
},
_restartPromise: null,
_importGlobMap: new Map(),
_forceOptimizeOnRestart: false,
_pendingRequests: new Map(),
_fsDenyGlob: picomatch(config.server.fs.deny, { matchBase: true }),
_shortcutsOptions: undefined,
}
if (!middlewareMode) {
exitProcess = async () => {
try {
await server.close()
} finally {
process.exit()
}
}
process.once('SIGTERM', exitProcess)
if (process.env.CI !== 'true') {
process.stdin.on('end', exitProcess)
}
}
const publicFiles = await initPublicFilesPromise
const onHMRUpdate = async (file: string, configOnly: boolean) => {
if (serverConfig.hmr !== false) {
try {
await handleHMRUpdate(file, server, configOnly)
} catch (err) {
ws.send({
type: 'error',
err: prepareError(err),
})
}
}
}
const normalizedPublicDir = normalizePath(config.publicDir)
const onFileAddUnlink = async (file: string, isUnlink: boolean) => {
file = normalizePath(file)
await container.watchChange(file, { event: isUnlink ? 'delete' : 'create' })
if (config.publicDir && publicFiles) {
if (file.startsWith(normalizedPublicDir)) {
publicFiles[isUnlink ? 'delete' : 'add'](
file.slice(normalizedPublicDir.length),
)
}
}
await handleFileAddUnlink(file, server, isUnlink)
await onHMRUpdate(file, true)
}
watcher.on('change', async (file) => {
file = normalizePath(file)
await container.watchChange(file, { event: 'update' })
// invalidate module graph cache on file change
moduleGraph.onFileChange(file)
await onHMRUpdate(file, false)
})
getFsUtils(config).initWatcher?.(watcher)
watcher.on('add', (file) => {
onFileAddUnlink(file, false)
})
watcher.on('unlink', (file) => {
onFileAddUnlink(file, true)
})
ws.on('vite:invalidate', async ({ path, message }: InvalidatePayload) => {
const mod = moduleGraph.urlToModuleMap.get(path)
if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
config.logger.info(
colors.yellow(`hmr invalidate `) +
colors.dim(path) +
(message ? ` ${message}` : ''),
{ timestamp: true },
)
const file = getShortName(mod.file!, config.root)
updateModules(
file,
[...mod.importers],
mod.lastHMRTimestamp,
server,
true,
)
}
})
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 hook of config.getSortedPluginHooks('configureServer')) {
postHooks.push(await hook(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) {
const middlewareServer =
(isObject(serverConfig.middlewareMode)
? serverConfig.middlewareMode.server
: null) || httpServer
middlewares.use(proxyMiddleware(middlewareServer, proxy, config))
}
// base
if (config.base !== '/') {
middlewares.use(baseMiddleware(config.rawBase, middlewareMode))
}
// open in editor support
middlewares.use('/__open-in-editor', launchEditorMiddleware())
// ping request handler
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
middlewares.use(function viteHMRPingMiddleware(req, res, next) {
if (req.headers['accept'] === 'text/x-vite-ping') {
res.writeHead(204).end()
} else {
next()
}
})
// 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(server, publicFiles))
}
// main transform middleware
middlewares.use(transformMiddleware(server))
// serve static files
middlewares.use(serveRawFsMiddleware(server))
middlewares.use(serveStaticMiddleware(server))
// html fallback
if (config.appType === 'spa' || config.appType === 'mpa') {
middlewares.use(
htmlFallbackMiddleware(
root,
config.appType === 'spa',
getFsUtils(config),
),
)
}
// 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.appType === 'spa' || config.appType === 'mpa') {
// transform index.html
middlewares.use(indexHtmlMiddleware(root, server))
// handle 404s
middlewares.use(notFoundMiddleware())
}
// error handler
middlewares.use(errorMiddleware(server, middlewareMode))
// httpServer.listen can be called multiple times
// when port when using next port number
// this code is to avoid calling buildStart multiple times
let initingServer: Promise<void> | undefined
let serverInited = false
const initServer = async () => {
if (serverInited) return
if (initingServer) return initingServer
initingServer = (async function () {
await container.buildStart({})
// start deps optimizer after all container plugins are ready
if (isDepsOptimizerEnabled(config, false)) {
await initDepsOptimizer(config, server)
}
warmupFiles(server)
initingServer = undefined
serverInited = true
})()
return initingServer
}
if (!middlewareMode && httpServer) {
// overwrite listen to init optimizer before server start
const listen = httpServer.listen.bind(httpServer)
httpServer.listen = (async (port: number, ...args: any[]) => {
try {
// ensure ws server started
ws.listen()
await initServer()
} catch (e) {
httpServer.emit('error', e)
return
}
return listen(port, ...args)
}) as any
} else {
if (options.ws) {
ws.listen()
}
await initServer()
}
return server
}
async function startServer(
server: ViteDevServer,
inlinePort?: number,
): Promise<void> {
const httpServer = server.httpServer
if (!httpServer) {
throw new Error('Cannot call server.listen in middleware mode.')
}
const options = server.config.server
const hostname = await resolveHostname(options.host)
const configPort = inlinePort ?? options.port
// When using non strict port for the dev server, the running port can be different from the config one.
// When restarting, the original port may be available but to avoid a switch of URL for the running
// browser tabs, we enforce the previously used port, expect if the config port changed.
const port =
(!configPort || configPort === server._configServerPort
? server._currentServerPort
: configPort) ?? DEFAULT_DEV_PORT
server._configServerPort = configPort
const serverPort = await httpServerStart(httpServer, {
port,
strictPort: options.strictPort,
host: hostname.host,
logger: server.config.logger,
})
server._currentServerPort = serverPort
}
function createServerCloseFn(server: HttpServer | 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 Omit<ResolvedServerOptions, 'sourcemapIgnoreList'>),
sourcemapIgnoreList:
raw?.sourcemapIgnoreList === false
? () => false
: raw?.sourcemapIgnoreList || isInNodeModules,
middlewareMode: !!raw?.middlewareMode,
}
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,
cachedChecks:
server.fs?.cachedChecks ?? !!process.env.VITE_SERVER_FS_CACHED_CHECKS,
}
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) {
global.__vite_start_time = performance.now()
const shortcutsOptions = server._shortcutsOptions
let inlineConfig = server.config.inlineConfig
if (server._forceOptimizeOnRestart) {
inlineConfig = mergeConfig(inlineConfig, {
optimizeDeps: {
force: true,
},
})
}
// Reinit the server by creating a new instance using the same inlineConfig
// This will triger a reload of the config file and re-create the plugins and
// middlewares. We then assign all properties of the new server to the existing
// server instance and set the user instance to be used in the new server.
// This allows us to keep the same server instance for the user.
{
let newServer = null
try {
// delay ws server listen
newServer = await _createServer(inlineConfig, { ws: false })
} catch (err: any) {
server.config.logger.error(err.message, {
timestamp: true,
})
server.config.logger.error('server restart failed', { timestamp: true })
return
}
await server.close()