Skip to content

Commit 0cd5139

Browse files
fix(hmr): catch up before running a chunk from a newer build (#22984)
* fix(hmr): catch up before running a chunk from a newer build Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_013FhutSoCnghgVZUjHDTfqa * fix(hmr): give each loaded chunk version module its own identifier Code generation is cached by identifier and runtime, so marks of two chunks in one runtime overwrote each other's cache entry on every build. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_013FhutSoCnghgVZUjHDTfqa --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent d3bbded commit 0cd5139

23 files changed

Lines changed: 479 additions & 15 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Apply pending HMR updates before running a chunk from a newer build.

‎lib/hmr/HotModuleReplacement.runtime.js‎

Lines changed: 107 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ var $hmrDownloadManifest$;
9494
var $hmrDownloadUpdateHandlers$;
9595
/** @type {Record<string, InvalidateModuleHandler>} */
9696
var $hmrInvalidateModuleHandlers$;
97+
/** @type {Record<ModuleId, string> | undefined} */
98+
var $hmrChunkVersions$;
99+
/** @type {Record<ModuleId, string>} */
100+
var $hmrLoadedChunkVersions$;
97101
/** @type {(id: ModuleId) => unknown} */
98102
var __webpack_require__;
99103
/* eslint-enable no-unassigned-vars */
@@ -125,6 +129,12 @@ module.exports = function () {
125129
/** @type {ModuleId[] | undefined} */
126130
var queuedInvalidatedModules;
127131

132+
/**
133+
* Chunk loads waiting for the update in progress to settle.
134+
* @type {(() => void)[]}
135+
*/
136+
var settledWaiters = [];
137+
128138
$hmrModuleData$ = currentModuleData;
129139

130140
$interceptModuleExecution$.push(function (options) {
@@ -139,6 +149,7 @@ module.exports = function () {
139149

140150
$hmrDownloadUpdateHandlers$ = {};
141151
$hmrInvalidateModuleHandlers$ = {};
152+
$hmrLoadedChunkVersions$ = {};
142153

143154
/**
144155
* @param {WebpackRequire} require the original require function
@@ -206,15 +217,21 @@ module.exports = function () {
206217
// half of `.e`. A runtime that loads no chunks has neither to wrap.
207218
if (require.e) {
208219
/** @type {WebpackRequire} */ (fn).e = function (chunkId, fetchPriority) {
209-
return trackBlockingPromise(
210-
/** @type {EnsureChunk} */ (require.e)(chunkId, fetchPriority)
220+
return checkChunkVersion(
221+
chunkId,
222+
trackBlockingPromise(
223+
/** @type {EnsureChunk} */ (require.e)(chunkId, fetchPriority)
224+
)
211225
);
212226
};
213227
}
214228
if (require.ei) {
215229
/** @type {WebpackRequire} */ (fn).ei = function (chunkId, importFn) {
216-
return trackBlockingPromise(
217-
/** @type {AnalyzableChunkImport} */ (require.ei)(chunkId, importFn)
230+
return checkChunkVersion(
231+
chunkId,
232+
trackBlockingPromise(
233+
/** @type {AnalyzableChunkImport} */ (require.ei)(chunkId, importFn)
234+
)
218235
);
219236
};
220237
}
@@ -346,6 +363,12 @@ module.exports = function () {
346363
for (var i = 0; i < registeredStatusHandlers.length; i++)
347364
results[i] = registeredStatusHandlers[i].call(null, newStatus);
348365

366+
if (newStatus === "idle" || newStatus === "abort" || newStatus === "fail") {
367+
var waiters = settledWaiters;
368+
settledWaiters = [];
369+
for (var j = 0; j < waiters.length; j++) waiters[j]();
370+
}
371+
349372
return Promise.all(results).then(function () {});
350373
}
351374

@@ -397,6 +420,86 @@ module.exports = function () {
397420
);
398421
}
399422

423+
/**
424+
* Whether a loaded chunk came from the build the runtime runs, as far as it can tell.
425+
* @param {ModuleId} chunkId chunk id
426+
* @returns {boolean} true when its modules fit the running code
427+
*/
428+
function isCurrentChunkVersion(chunkId) {
429+
var loaded = $hmrLoadedChunkVersions$[chunkId];
430+
return (
431+
loaded === undefined ||
432+
!$hmrChunkVersions$ ||
433+
loaded === $hmrChunkVersions$[chunkId]
434+
);
435+
}
436+
437+
/**
438+
* Holds a chunk load until the chunk fits the running code; one already loaded and
439+
* fitting resolves as fast as before.
440+
* @template T
441+
* @param {ModuleId} chunkId chunk id
442+
* @param {Promise<T>} promise the chunk load
443+
* @returns {Promise<T>} the same result, once the chunk fits
444+
*/
445+
function checkChunkVersion(chunkId, promise) {
446+
if (
447+
!$hmrChunkVersions$ ||
448+
$hmrChunkVersions$[chunkId] === undefined ||
449+
$hmrLoadedChunkVersions$[chunkId] === $hmrChunkVersions$[chunkId]
450+
) {
451+
return promise;
452+
}
453+
return promise.then(function (result) {
454+
if (isCurrentChunkVersion(chunkId)) return result;
455+
return waitForChunkVersion(chunkId).then(function () {
456+
return result;
457+
});
458+
});
459+
}
460+
461+
/**
462+
* Holds a loaded chunk from another build until the updates leading to it are applied,
463+
* since its modules may need chunks or modules the running build doesn't have.
464+
* @param {ModuleId} chunkId chunk id
465+
* @returns {Promise<void>} resolves when the chunk fits the running code
466+
*/
467+
function waitForChunkVersion(chunkId) {
468+
if (isCurrentChunkVersion(chunkId)) return Promise.resolve();
469+
if (currentStatus === "abort" || currentStatus === "fail") {
470+
return Promise.reject(
471+
new Error(
472+
"Loaded chunk " +
473+
chunkId +
474+
" is from another build, and the update failed (" +
475+
currentStatus +
476+
")"
477+
)
478+
);
479+
}
480+
if (currentStatus !== "idle") {
481+
return /** @type {Promise<void>} */ (
482+
new Promise(function (resolve) {
483+
settledWaiters.push(function () {
484+
resolve();
485+
});
486+
})
487+
).then(function () {
488+
return waitForChunkVersion(chunkId);
489+
});
490+
}
491+
return hotCheck(true).then(function (updatedModules) {
492+
if (!updatedModules && !isCurrentChunkVersion(chunkId)) {
493+
throw new Error(
494+
"Loaded chunk " +
495+
chunkId +
496+
" is from another build, and no update leads to it"
497+
);
498+
}
499+
return waitForChunkVersion(chunkId);
500+
});
501+
}
502+
400503
/**
401504
* @param {boolean | ApplyOptions=} applyOnUpdate apply the update right away
402505
* @returns {Promise<ModuleId[] | null>} updated module ids or null
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author Alexander Akait @alexander-akait
4+
*/
5+
6+
"use strict";
7+
8+
const RuntimeGlobals = require("../runtime/RuntimeGlobals");
9+
const RuntimeModule = require("../runtime/RuntimeModule");
10+
const { compareModulesByIdentifier } = require("../util/comparators");
11+
const createHash = require("../util/createHash");
12+
13+
/** @import Compilation from "../Compilation" */
14+
/** @import Chunk, { ChunkId } from "../graph/Chunk" */
15+
16+
/**
17+
* Tells the HMR runtime which build each async chunk belongs to, so a chunk file a newer
18+
* build overwrote is held until the updates leading to it are applied.
19+
*/
20+
class HotModuleReplacementChunkVersionsRuntimeModule extends RuntimeModule {
21+
constructor() {
22+
super("hot module replacement chunk versions");
23+
}
24+
25+
/**
26+
* Whether a chunk's file states its version: a chunk only reached through `import()`.
27+
* @param {Compilation} compilation the compilation
28+
* @param {Chunk} chunk the chunk
29+
* @returns {boolean} true when the chunk is versioned
30+
*/
31+
static isVersioned(compilation, chunk) {
32+
return (
33+
!chunk.hasRuntime() &&
34+
!chunk.canBeInitial() &&
35+
chunk.id !== null &&
36+
compilation.chunkGraph.getChunkModulesIterableBySourceType(
37+
chunk,
38+
"javascript"
39+
) !== undefined
40+
);
41+
}
42+
43+
/**
44+
* The version of a chunk: what its JavaScript modules are in this build.
45+
* @param {Compilation} compilation the compilation
46+
* @param {Chunk} chunk the chunk
47+
* @returns {string} the version
48+
*/
49+
static getVersion(compilation, chunk) {
50+
const { chunkGraph, outputOptions } = compilation;
51+
const hash = createHash(outputOptions.hashFunction);
52+
for (const module of chunkGraph.getOrderedChunkModulesIterableBySourceType(
53+
chunk,
54+
"javascript",
55+
compareModulesByIdentifier
56+
) || []) {
57+
hash.update(`${chunkGraph.getModuleId(module)}|`);
58+
hash.update(`${chunkGraph.getModuleHash(module, chunk.runtime)}|`);
59+
}
60+
return /** @type {string} */ (hash.digest("hex")).slice(
61+
0,
62+
outputOptions.hashDigestLength
63+
);
64+
}
65+
66+
/**
67+
* The `[handlerMap, key]` pairs this module installs onto a chunk handler map
68+
* such as `__webpack_require__.f`, or `null` where it cannot name them.
69+
* @returns {[string, string][] | null} installed chunk handlers (do not mutate)
70+
*/
71+
getInstalledChunkHandlers() {
72+
return RuntimeModule.NO_CHUNK_HANDLERS;
73+
}
74+
75+
/**
76+
* Generates runtime code for this runtime module.
77+
* @returns {string | null} runtime code
78+
*/
79+
generate() {
80+
const compilation = /** @type {Compilation} */ (this.compilation);
81+
/** @type {Record<ChunkId, string>} */
82+
const versions = {};
83+
for (const chunk of /** @type {Chunk} */ (this.chunk).getAllAsyncChunks()) {
84+
if (
85+
!HotModuleReplacementChunkVersionsRuntimeModule.isVersioned(
86+
compilation,
87+
chunk
88+
)
89+
) {
90+
continue;
91+
}
92+
versions[/** @type {ChunkId} */ (chunk.id)] =
93+
HotModuleReplacementChunkVersionsRuntimeModule.getVersion(
94+
compilation,
95+
chunk
96+
);
97+
}
98+
// A hot update re-runs this module, so the runtime then expects the new versions.
99+
return `${RuntimeGlobals.hmrChunkVersions} = ${JSON.stringify(versions)};`;
100+
}
101+
}
102+
103+
module.exports = HotModuleReplacementChunkVersionsRuntimeModule;
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author Alexander Akait @alexander-akait
4+
*/
5+
6+
"use strict";
7+
8+
const RuntimeGlobals = require("../runtime/RuntimeGlobals");
9+
const RuntimeModule = require("../runtime/RuntimeModule");
10+
const HotModuleReplacementChunkVersionsRuntimeModule = require("./HotModuleReplacementChunkVersionsRuntimeModule");
11+
12+
/** @import Compilation from "../Compilation" */
13+
/** @import Chunk, { ChunkId } from "../graph/Chunk" */
14+
15+
/**
16+
* Runs in an async chunk when it is installed and records which build the file is from.
17+
*/
18+
class HotModuleReplacementLoadedChunkVersionRuntimeModule extends RuntimeModule {
19+
/**
20+
* @param {ChunkId} chunkId the id of the chunk it runs in
21+
*/
22+
constructor(chunkId) {
23+
super("hot module replacement loaded chunk version");
24+
/** @type {ChunkId} */
25+
this.chunkId = chunkId;
26+
}
27+
28+
/**
29+
* Returns the unique identifier used to reference this module.
30+
* @returns {string} a unique identifier of the module
31+
*/
32+
identifier() {
33+
// One per chunk, and code generation is cached by identifier and runtime.
34+
return `${super.identifier()}|${this.chunkId}`;
35+
}
36+
37+
/**
38+
* The `[handlerMap, key]` pairs this module installs onto a chunk handler map
39+
* such as `__webpack_require__.f`, or `null` where it cannot name them.
40+
* @returns {[string, string][] | null} installed chunk handlers (do not mutate)
41+
*/
42+
getInstalledChunkHandlers() {
43+
return RuntimeModule.NO_CHUNK_HANDLERS;
44+
}
45+
46+
/**
47+
* Generates runtime code for this runtime module.
48+
* @returns {string | null} runtime code
49+
*/
50+
generate() {
51+
const compilation = /** @type {Compilation} */ (this.compilation);
52+
const chunk = /** @type {Chunk} */ (this.chunk);
53+
const version = HotModuleReplacementChunkVersionsRuntimeModule.getVersion(
54+
compilation,
55+
chunk
56+
);
57+
return `${RuntimeGlobals.hmrLoadedChunkVersions}[${JSON.stringify(
58+
chunk.id
59+
)}] = ${JSON.stringify(version)};`;
60+
}
61+
}
62+
63+
module.exports = HotModuleReplacementLoadedChunkVersionRuntimeModule;

‎lib/hmr/HotModuleReplacementPlugin.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ const {
4545
subtractRuntime
4646
} = require("../util/runtime");
4747
const HotModuleReplacementChunkGroupRuntimeModule = require("./HotModuleReplacementChunkGroupRuntimeModule");
48+
const HotModuleReplacementChunkVersionsRuntimeModule = require("./HotModuleReplacementChunkVersionsRuntimeModule");
49+
const HotModuleReplacementLoadedChunkVersionRuntimeModule = require("./HotModuleReplacementLoadedChunkVersionRuntimeModule");
4850
const HotModuleReplacementRuntimeModule = require("./HotModuleReplacementRuntimeModule");
4951
const getParserHooks = require("./parserHooks");
5052

@@ -568,6 +570,8 @@ class HotModuleReplacementPlugin {
568570
if (modulesById === undefined) {
569571
modulesById = new Map();
570572
for (const module of compilation.modules) {
573+
// Runtime modules all share the empty id.
574+
if (module.is("runtime")) continue;
571575
modulesById.set(
572576
/** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
573577
module
@@ -1344,7 +1348,29 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
13441348
chunk,
13451349
new HotModuleReplacementChunkGroupRuntimeModule()
13461350
);
1351+
compilation.addRuntimeModule(
1352+
chunk,
1353+
new HotModuleReplacementChunkVersionsRuntimeModule()
1354+
);
13471355
});
1356+
compilation.hooks.additionalChunkRuntimeRequirements.tap(
1357+
PLUGIN_NAME,
1358+
(chunk) => {
1359+
if (
1360+
HotModuleReplacementChunkVersionsRuntimeModule.isVersioned(
1361+
compilation,
1362+
chunk
1363+
)
1364+
) {
1365+
compilation.addRuntimeModule(
1366+
chunk,
1367+
new HotModuleReplacementLoadedChunkVersionRuntimeModule(
1368+
/** @type {ChunkId} */ (chunk.id)
1369+
)
1370+
);
1371+
}
1372+
}
1373+
);
13481374

13491375
normalModuleFactory.hooks.parser
13501376
.for(JAVASCRIPT_MODULE_TYPE_AUTO)

‎lib/hmr/HotModuleReplacementRuntimeModule.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ class HotModuleReplacementRuntimeModule extends RuntimeModule {
5252
.replace(
5353
/\$hmrDownloadUpdateHandlers\$/g,
5454
RuntimeGlobals.hmrDownloadUpdateHandlers
55+
)
56+
.replace(/\$hmrChunkVersions\$/g, RuntimeGlobals.hmrChunkVersions)
57+
.replace(
58+
/\$hmrLoadedChunkVersions\$/g,
59+
RuntimeGlobals.hmrLoadedChunkVersions
5560
);
5661
}
5762
}

0 commit comments

Comments
 (0)