Skip to content

Commit 3dbddef

Browse files
authored
fix(bundled-dev): hot update through circular imports instead of reloading (#23259)
1 parent 7822e14 commit 3dbddef

2 files changed

Lines changed: 178 additions & 75 deletions

File tree

‎packages/vite/src/client/bundledDevHmrClient.ts‎

Lines changed: 149 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,18 @@ export interface RolldownRuntimeLike {
1616
loadExports(id: string): unknown
1717
}
1818

19+
interface PropagationBoundary {
20+
boundary: string
21+
acceptedVia: string
22+
isWithinCircularImport: boolean
23+
}
24+
1925
type HmrUpdate =
2026
| { type: 'noop' }
2127
| { type: 'full-reload'; reason: string }
2228
| {
2329
type: 'boundaries'
24-
/** `[boundary, acceptedVia]` pairs */
25-
boundaries: [string, string][]
30+
boundaries: PropagationBoundary[]
2631
updateSet: string[]
2732
}
2833

@@ -69,7 +74,7 @@ export class BundledDevHMRClient extends HMRClient {
6974
changedIds: string[],
7075
opts?: { firstInvalidatedBy?: string },
7176
): HmrUpdate {
72-
const boundaries: [string, string][] = []
77+
const boundaries: PropagationBoundary[] = []
7378
const updateSet = new Set<string>()
7479
const traversedModules = new Set<string>()
7580
for (const changed of changedIds) {
@@ -95,7 +100,7 @@ export class BundledDevHMRClient extends HMRClient {
95100
id: string,
96101
stack: string[],
97102
updateSet: Set<string>,
98-
boundaries: [string, string][],
103+
boundaries: PropagationBoundary[],
99104
firstInvalidatedBy: string | undefined,
100105
traversedModules: Set<string>,
101106
): HmrUpdate | undefined {
@@ -109,7 +114,11 @@ export class BundledDevHMRClient extends HMRClient {
109114
}
110115
}
111116
if (this.isSelfAccepted(id)) {
112-
boundaries.push([id, id])
117+
boundaries.push({
118+
boundary: id,
119+
acceptedVia: id,
120+
isWithinCircularImport: this.isNodeWithinCircularImports(id, stack),
121+
})
113122
return
114123
}
115124
const parents = this.runtime
@@ -122,28 +131,107 @@ export class BundledDevHMRClient extends HMRClient {
122131
}
123132
}
124133
for (const parent of parents) {
134+
const subChain = [...stack, parent]
125135
if (this.acceptsDep(parent, id)) {
126-
boundaries.push([parent, id])
136+
boundaries.push({
137+
boundary: parent,
138+
acceptedVia: id,
139+
isWithinCircularImport: this.isNodeWithinCircularImports(
140+
parent,
141+
subChain,
142+
),
143+
})
127144
continue
128145
}
129-
if (stack.includes(parent)) {
130-
return {
131-
type: 'full-reload',
132-
reason: `circular import chain between \`${id}\` and \`${parent}\``,
133-
}
146+
if (!stack.includes(parent)) {
147+
const fullReload = this.bubble(
148+
parent,
149+
subChain,
150+
updateSet,
151+
boundaries,
152+
firstInvalidatedBy,
153+
traversedModules,
154+
)
155+
if (fullReload) return fullReload
134156
}
135-
const fullReload = this.bubble(
136-
parent,
137-
[...stack, parent],
138-
updateSet,
139-
boundaries,
140-
firstInvalidatedBy,
141-
traversedModules,
142-
)
143-
if (fullReload) return fullReload
144157
}
145158
}
146159

160+
/**
161+
* Check importers recursively if it's an import loop. An accepted module within
162+
* an import loop cannot recover its execution order and should be reloaded.
163+
*
164+
* @param node The node that accepts HMR and is a boundary
165+
* @param nodeChain The chain of nodes/imports that lead to the node.
166+
* (The last node in the chain imports the `node` parameter)
167+
* @param currentChain The current chain tracked from the `node` parameter
168+
* @param traversedModules The set of modules that have traversed
169+
*/
170+
private isNodeWithinCircularImports(
171+
node: string,
172+
nodeChain: string[],
173+
currentChain: string[] = [node],
174+
traversedModules = new Set<string>(),
175+
): boolean {
176+
// To help visualize how each parameter works, imagine this import graph:
177+
//
178+
// A -> B -> C -> ACCEPTED -> D -> E -> NODE
179+
// ^--------------------------|
180+
//
181+
// ACCEPTED: the node that accepts HMR. the `node` parameter.
182+
// NODE : the initial node that triggered this HMR.
183+
//
184+
// This function will return true in the above graph, which:
185+
// `node` : ACCEPTED
186+
// `nodeChain` : [NODE, E, D, ACCEPTED]
187+
// `currentChain` : [ACCEPTED, C, B]
188+
//
189+
// It works by checking if any `node` importers are within `nodeChain`, which
190+
// means there's an import loop with a HMR-accepted module in it.
191+
192+
if (traversedModules.has(node)) {
193+
return false
194+
}
195+
traversedModules.add(node)
196+
197+
for (const importer of this.runtime.getImporters(node)) {
198+
// Node may import itself which is safe
199+
if (importer === node) continue
200+
201+
// Check circular imports
202+
const importerIndex = nodeChain.indexOf(importer)
203+
if (importerIndex > -1) {
204+
// Log extra debug information so users can fix and remove the circular imports
205+
// Following explanation above:
206+
// `importer` : E
207+
// `currentChain` reversed : [B, C, ACCEPTED]
208+
// `nodeChain` sliced & reversed : [D, E]
209+
// Combined : [E, B, C, ACCEPTED, D, E]
210+
const importChain = [
211+
importer,
212+
...[...currentChain].reverse(),
213+
...nodeChain.slice(importerIndex, -1).reverse(),
214+
]
215+
this.logger.debug(
216+
`circular imports detected: ${importChain.join(' -> ')}`,
217+
)
218+
return true
219+
}
220+
221+
// Continue recursively
222+
if (!currentChain.includes(importer)) {
223+
const result = this.isNodeWithinCircularImports(
224+
importer,
225+
nodeChain,
226+
currentChain.concat(importer),
227+
traversedModules,
228+
)
229+
if (result) return result
230+
}
231+
}
232+
return false
233+
}
234+
147235
handlePush(payload: BundledDevUpdatePayload): void {
148236
this.applyQueue = this.applyQueue
149237
.then(() => this.applyPush(payload))
@@ -247,22 +335,41 @@ export class BundledDevHMRClient extends HMRClient {
247335
}
248336

249337
// collect callbacks before the caches are removed
250-
const applies = update.boundaries.map(([boundary, acceptedVia]) => ({
251-
boundary,
252-
acceptedVia,
253-
callbacks:
254-
this.hotModulesMap
255-
.get(boundary)
256-
?.callbacks.filter((c) => c.deps.includes(acceptedVia)) ?? [],
257-
}))
338+
const applies = update.boundaries.map(
339+
({ boundary, acceptedVia, isWithinCircularImport }) => ({
340+
boundary,
341+
acceptedVia,
342+
isWithinCircularImport,
343+
callbacks:
344+
this.hotModulesMap
345+
.get(boundary)
346+
?.callbacks.filter((c) => c.deps.includes(acceptedVia)) ?? [],
347+
}),
348+
)
258349

259350
for (const id of update.updateSet) {
260351
this.runtime.removeModuleCache(id)
261352
}
262353

263-
for (const { boundary, acceptedVia, callbacks } of applies) {
264-
this.runtime.initModule(acceptedVia)
265-
const fresh = this.runtime.loadExports(acceptedVia)
354+
for (const {
355+
boundary,
356+
acceptedVia,
357+
isWithinCircularImport,
358+
callbacks,
359+
} of applies) {
360+
let fresh: unknown
361+
try {
362+
this.runtime.initModule(acceptedVia)
363+
fresh = this.runtime.loadExports(acceptedVia)
364+
} catch (err) {
365+
if (isWithinCircularImport) {
366+
this.requestFullReload(
367+
`${acceptedVia} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order.`,
368+
)
369+
return
370+
}
371+
throw err
372+
}
266373
try {
267374
this.currentFirstInvalidatedBy = firstInvalidatedBy
268375
for (const { deps, fn } of callbacks) {
@@ -284,16 +391,19 @@ export class BundledDevHMRClient extends HMRClient {
284391
}
285392

286393
private toUpdatePayload(
287-
boundaries: [string, string][],
394+
boundaries: PropagationBoundary[],
288395
firstInvalidatedBy: string | undefined,
289396
): UpdatePayload {
290-
const updates: Update[] = boundaries.map(([boundary, acceptedVia]) => ({
291-
type: 'js-update',
292-
path: boundary,
293-
acceptedPath: acceptedVia,
294-
timestamp: Date.now(),
295-
firstInvalidatedBy,
296-
}))
397+
const updates: Update[] = boundaries.map(
398+
({ boundary, acceptedVia, isWithinCircularImport }) => ({
399+
type: 'js-update',
400+
path: boundary,
401+
acceptedPath: acceptedVia,
402+
timestamp: Date.now(),
403+
isWithinCircularImport,
404+
firstInvalidatedBy,
405+
}),
406+
)
297407
return { type: 'update', updates }
298408
}
299409

‎playground/hmr/__tests__/hmr.spec.ts‎

Lines changed: 29 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -351,20 +351,15 @@ if (!isBuild) {
351351
.toMatch('child updated')
352352
})
353353

354-
// bundled dev: the invalidate inside the circular import ends in a full
355-
// page reload instead of a hot update
356-
test.skipIf(isBundledDev)(
357-
'invalidate in circular dep should be hot updated if possible',
358-
async () => {
359-
const el = page.locator('.invalidation-circular-deps-handled')
360-
await expect.poll(() => el.textContent()).toMatch('child')
361-
editFile(
362-
'invalidation-circular-deps/invalidate-handled-in-circle/child.js',
363-
(code) => code.replace('child', 'child updated'),
364-
)
365-
await expect.poll(() => el.textContent()).toMatch('child updated')
366-
},
367-
)
354+
test('invalidate in circular dep should be hot updated if possible', async () => {
355+
const el = page.locator('.invalidation-circular-deps-handled')
356+
await expect.poll(() => el.textContent()).toMatch('child')
357+
editFile(
358+
'invalidation-circular-deps/invalidate-handled-in-circle/child.js',
359+
(code) => code.replace('child', 'child updated'),
360+
)
361+
await expect.poll(() => el.textContent()).toMatch('child updated')
362+
})
368363

369364
// bundled dev: file changes do not run the `hotUpdate` plugin hook, so the
370365
// plugin's custom events never reach the page
@@ -1196,29 +1191,27 @@ if (!isBuild) {
11961191
)
11971192
})
11981193

1199-
// bundled dev:
1200-
// 1. `unexpected no error` is shown instead of `expected error`,
1201-
// `_value` in `mod-c` is initialzed with `var` and is hoisted to the top of the module,
1202-
// whereas in unbundled dev, `_value` is still in TDZ, which causes a `ReferenceError`.
1203-
//
1204-
// 2. an edit inside the circular import chain triggers a full
1205-
// page reload instead of a hot update
1206-
test.skipIf(isBundledDev)(
1207-
'hmr should not reload if no accepted within circular imported files',
1208-
async () => {
1209-
await page.goto(viteTestUrl + '/circular/index.html')
1210-
const el = page.locator('.circular')
1211-
await expect
1212-
.poll(() => el.textContent())
1213-
.toBe('mod-a -> mod-b -> mod-c -> mod-a (expected error)')
1214-
editFile('circular/mod-b.js', (code) =>
1215-
code.replace(`mod-b ->`, `mod-b (edited) ->`),
1194+
test('hmr should not reload if no accepted within circular imported files', async () => {
1195+
await page.goto(viteTestUrl + '/circular/index.html')
1196+
const el = page.locator('.circular')
1197+
await expect
1198+
.poll(() => el.textContent())
1199+
.toBe(
1200+
isBundledDev
1201+
? // bundled-dev: `unexpected no error` is shown instead of `expected error`.
1202+
// Vite uses `output.topLevelVar = true` by default in bundled dev, which causes the circular import to be `undefined` instead of throwing a TDZ error,
1203+
// (see https://rolldown.rs/guide/troubleshooting#avoid-relying-on-temporal-dead-zone-tdz-errors),
1204+
// whereas in unbundled dev, it follows TDZ and shows `expected error`.
1205+
'mod-a -> mod-b -> mod-c -> undefined (unexpected no error)'
1206+
: 'mod-a -> mod-b -> mod-c -> mod-a (expected error)',
12161207
)
1217-
await expect
1218-
.poll(() => el.textContent())
1219-
.toBe('mod-a -> mod-b (edited) -> mod-c -> mod-a (expected error)')
1220-
},
1221-
)
1208+
editFile('circular/mod-b.js', (code) =>
1209+
code.replace(`mod-b ->`, `mod-b (edited) ->`),
1210+
)
1211+
await expect
1212+
.poll(() => el.textContent())
1213+
.toBe('mod-a -> mod-b (edited) -> mod-c -> mod-a (expected error)')
1214+
})
12221215

12231216
// bundled dev: editing an asset file does not push an update to the page
12241217
test.skipIf(isBundledDev)('not inlined assets HMR', async () => {

0 commit comments

Comments
 (0)