-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
hmr.ts
808 lines (743 loc) · 21.9 KB
/
hmr.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
import fsp from 'node:fs/promises'
import path from 'node:path'
import type { Server } from 'node:http'
import { EventEmitter } from 'node:events'
import colors from 'picocolors'
import type { CustomPayload, HMRPayload, Update } from 'types/hmrPayload'
import type { RollupError } from 'rollup'
import { CLIENT_DIR } from '../constants'
import { createDebugger, normalizePath } from '../utils'
import type { InferCustomEventPayload, ViteDevServer } from '..'
import { isCSSRequest } from '../plugins/css'
import { getAffectedGlobModules } from '../plugins/importMetaGlob'
import { isExplicitImportRequired } from '../plugins/importAnalysis'
import { getEnvFilesForMode } from '../env'
import { withTrailingSlash, wrapId } from '../../shared/utils'
import type { ModuleNode } from './moduleGraph'
import { restartServerWithUrls } from '.'
export const debugHmr = createDebugger('vite:hmr')
const whitespaceRE = /\s/
const normalizedClientDir = normalizePath(CLIENT_DIR)
export interface HmrOptions {
protocol?: string
host?: string
port?: number
clientPort?: number
path?: string
timeout?: number
overlay?: boolean
server?: Server
/** @internal */
channels?: HMRChannel[]
}
export interface HmrContext {
file: string
timestamp: number
modules: Array<ModuleNode>
read: () => string | Promise<string>
server: ViteDevServer
}
interface PropagationBoundary {
boundary: ModuleNode
acceptedVia: ModuleNode
isWithinCircularImport: boolean
}
export interface HMRBroadcasterClient {
/**
* Send event to the client
*/
send(payload: HMRPayload): void
/**
* Send custom event
*/
send(event: string, payload?: CustomPayload['data']): void
}
export interface HMRChannel {
/**
* Unique channel name
*/
name: string
/**
* Broadcast events to all clients
*/
send(payload: HMRPayload): void
/**
* Send custom event
*/
send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void
/**
* Handle custom event emitted by `import.meta.hot.send`
*/
on<T extends string>(
event: T,
listener: (
data: InferCustomEventPayload<T>,
client: HMRBroadcasterClient,
...args: any[]
) => void,
): void
on(event: 'connection', listener: () => void): void
/**
* Unregister event listener
*/
off(event: string, listener: Function): void
/**
* Start listening for messages
*/
listen(): void
/**
* Disconnect all clients, called when server is closed or restarted.
*/
close(): void
}
export interface HMRBroadcaster extends Omit<HMRChannel, 'close' | 'name'> {
/**
* All registered channels. Always has websocket channel.
*/
readonly channels: HMRChannel[]
/**
* Add a new third-party channel.
*/
addChannel(connection: HMRChannel): HMRBroadcaster
close(): Promise<unknown[]>
}
export function getShortName(file: string, root: string): string {
return file.startsWith(withTrailingSlash(root))
? path.posix.relative(root, file)
: file
}
export async function handleHMRUpdate(
type: 'create' | 'delete' | 'update',
file: string,
server: ViteDevServer,
): Promise<void> {
const { hot, config, moduleGraph } = server
const shortFile = getShortName(file, config.root)
const isConfig = file === config.configFile
const isConfigDependency = config.configFileDependencies.some(
(name) => file === name,
)
const isEnv =
config.inlineConfig.envFile !== false &&
getEnvFilesForMode(config.mode, config.envDir).includes(file)
if (isConfig || isConfigDependency || isEnv) {
// auto restart server
debugHmr?.(`[config change] ${colors.dim(shortFile)}`)
config.logger.info(
colors.green(
`${path.relative(process.cwd(), file)} changed, restarting server...`,
),
{ clear: true, timestamp: true },
)
try {
await restartServerWithUrls(server)
} catch (e) {
config.logger.error(colors.red(e))
}
return
}
debugHmr?.(`[file change] ${colors.dim(shortFile)}`)
// (dev only) the client itself cannot be hot updated.
if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
hot.send({
type: 'full-reload',
path: '*',
triggeredBy: path.resolve(config.root, file),
})
return
}
const mods = new Set(moduleGraph.getModulesByFile(file))
if (type === 'create') {
for (const mod of moduleGraph._hasResolveFailedErrorModules) {
mods.add(mod)
}
}
if (type === 'create' || type === 'delete') {
for (const mod of getAffectedGlobModules(file, server)) {
mods.add(mod)
}
}
// check if any plugin wants to perform custom HMR handling
const timestamp = Date.now()
const hmrContext: HmrContext = {
file,
timestamp,
modules: [...mods],
read: () => readModifiedFile(file),
server,
}
if (type === 'update') {
for (const hook of config.getSortedPluginHooks('handleHotUpdate')) {
const filteredModules = await hook(hmrContext)
if (filteredModules) {
hmrContext.modules = filteredModules
}
}
}
if (!hmrContext.modules.length) {
// html file cannot be hot updated
if (file.endsWith('.html')) {
config.logger.info(colors.green(`page reload `) + colors.dim(shortFile), {
clear: true,
timestamp: true,
})
hot.send({
type: 'full-reload',
path: config.server.middlewareMode
? '*'
: '/' + normalizePath(path.relative(config.root, file)),
})
} else {
// loaded but not in the module graph, probably not js
debugHmr?.(`[no modules matched] ${colors.dim(shortFile)}`)
}
return
}
updateModules(shortFile, hmrContext.modules, timestamp, server)
}
type HasDeadEnd = boolean
export function updateModules(
file: string,
modules: ModuleNode[],
timestamp: number,
{ config, hot, moduleGraph }: ViteDevServer,
afterInvalidation?: boolean,
): void {
const updates: Update[] = []
const invalidatedModules = new Set<ModuleNode>()
const traversedModules = new Set<ModuleNode>()
let needFullReload: HasDeadEnd = false
for (const mod of modules) {
const boundaries: PropagationBoundary[] = []
const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries)
moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true)
if (needFullReload) {
continue
}
if (hasDeadEnd) {
needFullReload = hasDeadEnd
continue
}
updates.push(
...boundaries.map(
({ boundary, acceptedVia, isWithinCircularImport }) => ({
type: `${boundary.type}-update` as const,
timestamp,
path: normalizeHmrUrl(boundary.url),
acceptedPath: normalizeHmrUrl(acceptedVia.url),
explicitImportRequired:
boundary.type === 'js'
? isExplicitImportRequired(acceptedVia.url)
: false,
isWithinCircularImport,
// browser modules are invalidated by changing ?t= query,
// but in ssr we control the module system, so we can directly remove them form cache
ssrInvalidates: getSSRInvalidatedImporters(acceptedVia),
}),
),
)
}
if (needFullReload) {
const reason =
typeof needFullReload === 'string'
? colors.dim(` (${needFullReload})`)
: ''
config.logger.info(
colors.green(`page reload `) + colors.dim(file) + reason,
{ clear: !afterInvalidation, timestamp: true },
)
hot.send({
type: 'full-reload',
triggeredBy: path.resolve(config.root, file),
})
return
}
if (updates.length === 0) {
debugHmr?.(colors.yellow(`no update happened `) + colors.dim(file))
return
}
config.logger.info(
colors.green(`hmr update `) +
colors.dim([...new Set(updates.map((u) => u.path))].join(', ')),
{ clear: !afterInvalidation, timestamp: true },
)
hot.send({
type: 'update',
updates,
})
}
function populateSSRImporters(
module: ModuleNode,
timestamp: number,
seen: Set<ModuleNode> = new Set(),
) {
module.ssrImportedModules.forEach((importer) => {
if (seen.has(importer)) {
return
}
if (
importer.lastHMRTimestamp === timestamp ||
importer.lastInvalidationTimestamp === timestamp
) {
seen.add(importer)
populateSSRImporters(importer, timestamp, seen)
}
})
return seen
}
function getSSRInvalidatedImporters(module: ModuleNode) {
return [...populateSSRImporters(module, module.lastHMRTimestamp)].map(
(m) => m.file!,
)
}
function areAllImportsAccepted(
importedBindings: Set<string>,
acceptedExports: Set<string>,
) {
for (const binding of importedBindings) {
if (!acceptedExports.has(binding)) {
return false
}
}
return true
}
function propagateUpdate(
node: ModuleNode,
traversedModules: Set<ModuleNode>,
boundaries: PropagationBoundary[],
currentChain: ModuleNode[] = [node],
): HasDeadEnd {
if (traversedModules.has(node)) {
return false
}
traversedModules.add(node)
// #7561
// if the imports of `node` have not been analyzed, then `node` has not
// been loaded in the browser and we should stop propagation.
if (node.id && node.isSelfAccepting === undefined) {
debugHmr?.(
`[propagate update] stop propagation because not analyzed: ${colors.dim(
node.id,
)}`,
)
return false
}
if (node.isSelfAccepting) {
boundaries.push({
boundary: node,
acceptedVia: node,
isWithinCircularImport: isNodeWithinCircularImports(node, currentChain),
})
// additionally check for CSS importers, since a PostCSS plugin like
// Tailwind JIT may register any file as a dependency to a CSS file.
for (const importer of node.importers) {
if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
propagateUpdate(
importer,
traversedModules,
boundaries,
currentChain.concat(importer),
)
}
}
return false
}
// A partially accepted module with no importers is considered self accepting,
// because the deal is "there are parts of myself I can't self accept if they
// are used outside of me".
// Also, the imported module (this one) must be updated before the importers,
// so that they do get the fresh imported module when/if they are reloaded.
if (node.acceptedHmrExports) {
boundaries.push({
boundary: node,
acceptedVia: node,
isWithinCircularImport: isNodeWithinCircularImports(node, currentChain),
})
} else {
if (!node.importers.size) {
return true
}
// #3716, #3913
// For a non-CSS file, if all of its importers are CSS files (registered via
// PostCSS plugins) it should be considered a dead end and force full reload.
if (
!isCSSRequest(node.url) &&
[...node.importers].every((i) => isCSSRequest(i.url))
) {
return true
}
}
for (const importer of node.importers) {
const subChain = currentChain.concat(importer)
if (importer.acceptedHmrDeps.has(node)) {
boundaries.push({
boundary: importer,
acceptedVia: node,
isWithinCircularImport: isNodeWithinCircularImports(importer, subChain),
})
continue
}
if (node.id && node.acceptedHmrExports && importer.importedBindings) {
const importedBindingsFromNode = importer.importedBindings.get(node.id)
if (
importedBindingsFromNode &&
areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)
) {
continue
}
}
if (
!currentChain.includes(importer) &&
propagateUpdate(importer, traversedModules, boundaries, subChain)
) {
return true
}
}
return false
}
/**
* Check importers recursively if it's an import loop. An accepted module within
* an import loop cannot recover its execution order and should be reloaded.
*
* @param node The node that accepts HMR and is a boundary
* @param nodeChain The chain of nodes/imports that lead to the node.
* (The last node in the chain imports the `node` parameter)
* @param currentChain The current chain tracked from the `node` parameter
* @param traversedModules The set of modules that have traversed
*/
function isNodeWithinCircularImports(
node: ModuleNode,
nodeChain: ModuleNode[],
currentChain: ModuleNode[] = [node],
traversedModules = new Set<ModuleNode>(),
): boolean {
// To help visualize how each parameters work, imagine this import graph:
//
// A -> B -> C -> ACCEPTED -> D -> E -> NODE
// ^--------------------------|
//
// ACCEPTED: the node that accepts HMR. the `node` parameter.
// NODE : the initial node that triggered this HMR.
//
// This function will return true in the above graph, which:
// `node` : ACCEPTED
// `nodeChain` : [NODE, E, D, ACCEPTED]
// `currentChain` : [ACCEPTED, C, B]
//
// It works by checking if any `node` importers are within `nodeChain`, which
// means there's an import loop with a HMR-accepted module in it.
if (traversedModules.has(node)) {
return false
}
traversedModules.add(node)
for (const importer of node.importers) {
// Node may import itself which is safe
if (importer === node) continue
// a PostCSS plugin like Tailwind JIT may register
// any file as a dependency to a CSS file.
// But in that case, the actual dependency chain is separate.
if (isCSSRequest(importer.url)) continue
// Check circular imports
const importerIndex = nodeChain.indexOf(importer)
if (importerIndex > -1) {
// Log extra debug information so users can fix and remove the circular imports
if (debugHmr) {
// Following explanation above:
// `importer` : E
// `currentChain` reversed : [B, C, ACCEPTED]
// `nodeChain` sliced & reversed : [D, E]
// Combined : [E, B, C, ACCEPTED, D, E]
const importChain = [
importer,
...[...currentChain].reverse(),
...nodeChain.slice(importerIndex, -1).reverse(),
]
debugHmr(
colors.yellow(`circular imports detected: `) +
importChain.map((m) => colors.dim(m.url)).join(' -> '),
)
}
return true
}
// Continue recursively
if (!currentChain.includes(importer)) {
const result = isNodeWithinCircularImports(
importer,
nodeChain,
currentChain.concat(importer),
traversedModules,
)
if (result) return result
}
}
return false
}
export function handlePrunedModules(
mods: Set<ModuleNode>,
{ hot }: ViteDevServer,
): void {
// update the disposed modules' hmr timestamp
// since if it's re-imported, it should re-apply side effects
// and without the timestamp the browser will not re-import it!
const t = Date.now()
mods.forEach((mod) => {
mod.lastHMRTimestamp = t
mod.lastHMRInvalidationReceived = false
debugHmr?.(`[dispose] ${colors.dim(mod.file)}`)
})
hot.send({
type: 'prune',
paths: [...mods].map((m) => m.url),
})
}
const enum LexerState {
inCall,
inSingleQuoteString,
inDoubleQuoteString,
inTemplateString,
inArray,
}
/**
* Lex import.meta.hot.accept() for accepted deps.
* Since hot.accept() can only accept string literals or array of string
* literals, we don't really need a heavy @babel/parse call on the entire source.
*
* @returns selfAccepts
*/
export function lexAcceptedHmrDeps(
code: string,
start: number,
urls: Set<{ url: string; start: number; end: number }>,
): boolean {
let state: LexerState = LexerState.inCall
// the state can only be 2 levels deep so no need for a stack
let prevState: LexerState = LexerState.inCall
let currentDep: string = ''
function addDep(index: number) {
urls.add({
url: currentDep,
start: index - currentDep.length - 1,
end: index + 1,
})
currentDep = ''
}
for (let i = start; i < code.length; i++) {
const char = code.charAt(i)
switch (state) {
case LexerState.inCall:
case LexerState.inArray:
if (char === `'`) {
prevState = state
state = LexerState.inSingleQuoteString
} else if (char === `"`) {
prevState = state
state = LexerState.inDoubleQuoteString
} else if (char === '`') {
prevState = state
state = LexerState.inTemplateString
} else if (whitespaceRE.test(char)) {
continue
} else {
if (state === LexerState.inCall) {
if (char === `[`) {
state = LexerState.inArray
} else {
// reaching here means the first arg is neither a string literal
// nor an Array literal (direct callback) or there is no arg
// in both case this indicates a self-accepting module
return true // done
}
} else if (state === LexerState.inArray) {
if (char === `]`) {
return false // done
} else if (char === ',') {
continue
} else {
error(i)
}
}
}
break
case LexerState.inSingleQuoteString:
if (char === `'`) {
addDep(i)
if (prevState === LexerState.inCall) {
// accept('foo', ...)
return false
} else {
state = prevState
}
} else {
currentDep += char
}
break
case LexerState.inDoubleQuoteString:
if (char === `"`) {
addDep(i)
if (prevState === LexerState.inCall) {
// accept('foo', ...)
return false
} else {
state = prevState
}
} else {
currentDep += char
}
break
case LexerState.inTemplateString:
if (char === '`') {
addDep(i)
if (prevState === LexerState.inCall) {
// accept('foo', ...)
return false
} else {
state = prevState
}
} else if (char === '$' && code.charAt(i + 1) === '{') {
error(i)
} else {
currentDep += char
}
break
default:
throw new Error('unknown import.meta.hot lexer state')
}
}
return false
}
export function lexAcceptedHmrExports(
code: string,
start: number,
exportNames: Set<string>,
): boolean {
const urls = new Set<{ url: string; start: number; end: number }>()
lexAcceptedHmrDeps(code, start, urls)
for (const { url } of urls) {
exportNames.add(url)
}
return urls.size > 0
}
export function normalizeHmrUrl(url: string): string {
if (url[0] !== '.' && url[0] !== '/') {
url = wrapId(url)
}
return url
}
function error(pos: number) {
const err = new Error(
`import.meta.hot.accept() can only accept string literals or an ` +
`Array of string literals.`,
) as RollupError
err.pos = pos
throw err
}
// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
// change event and sometimes this can be too early and get an empty buffer.
// Poll until the file's modified time has changed before reading again.
async function readModifiedFile(file: string): Promise<string> {
const content = await fsp.readFile(file, 'utf-8')
if (!content) {
const mtime = (await fsp.stat(file)).mtimeMs
for (let n = 0; n < 10; n++) {
await new Promise((r) => setTimeout(r, 10))
const newMtime = (await fsp.stat(file)).mtimeMs
if (newMtime !== mtime) {
break
}
}
return await fsp.readFile(file, 'utf-8')
} else {
return content
}
}
export function createHMRBroadcaster(): HMRBroadcaster {
const channels: HMRChannel[] = []
const readyChannels = new WeakSet<HMRChannel>()
const broadcaster: HMRBroadcaster = {
get channels() {
return [...channels]
},
addChannel(channel) {
if (channels.some((c) => c.name === channel.name)) {
throw new Error(`HMR channel "${channel.name}" is already defined.`)
}
channels.push(channel)
return broadcaster
},
on(event: string, listener: (...args: any[]) => any) {
// emit connection event only when all channels are ready
if (event === 'connection') {
// make a copy so we don't wait for channels that might be added after this is triggered
const channels = this.channels
channels.forEach((channel) =>
channel.on('connection', () => {
readyChannels.add(channel)
if (channels.every((c) => readyChannels.has(c))) {
listener()
}
}),
)
return
}
channels.forEach((channel) => channel.on(event, listener))
return
},
off(event, listener) {
channels.forEach((channel) => channel.off(event, listener))
return
},
send(...args: any[]) {
channels.forEach((channel) => channel.send(...(args as [any])))
},
listen() {
channels.forEach((channel) => channel.listen())
},
close() {
return Promise.all(channels.map((channel) => channel.close()))
},
}
return broadcaster
}
export interface ServerHMRChannel extends HMRChannel {
api: {
innerEmitter: EventEmitter
outsideEmitter: EventEmitter
}
}
export function createServerHMRChannel(): ServerHMRChannel {
const innerEmitter = new EventEmitter()
const outsideEmitter = new EventEmitter()
return {
name: 'ssr',
send(...args: any[]) {
let payload: HMRPayload
if (typeof args[0] === 'string') {
payload = {
type: 'custom',
event: args[0],
data: args[1],
}
} else {
payload = args[0]
}
outsideEmitter.emit('send', payload)
},
off(event, listener: () => void) {
innerEmitter.off(event, listener)
},
on: ((event: string, listener: () => unknown) => {
innerEmitter.on(event, listener)
}) as ServerHMRChannel['on'],
close() {
innerEmitter.removeAllListeners()
outsideEmitter.removeAllListeners()
},
listen() {
innerEmitter.emit('connection')
},
api: {
innerEmitter,
outsideEmitter,
},
}
}