Skip to content

Commit 7d49735

Browse files
fix: reject a fulfilled async cycle member with the cycle's evaluation error (#21921)
* fix: reject a fulfilled async cycle member with the cycle's evaluation error A strongly-connected component of async modules records one [[EvaluationError]] for all of its members, so a member that already fulfilled before a peer threw must still report that error to a later import. webpack settled each async module on its own, so importing the fulfilled member resolved with a half-evaluated namespace. Async modules in a cycle now hand their peers' ids to the runtime and mark them on rejection. Both the peer list and the marker are emitted only under output.strictModuleErrorHandling, which is what makes a recorded error observable to a later require, so a build without it is byte-identical. * perf: name an async cycle by a group key instead of a peer list Every member of a strongly-connected component carried the ids of all its peers, so a cycle of five emitted twenty id slots where five keys do. Each member now emits the component's smallest async member id and the runtime groups the modules under it, cutting the emitted cost of the cycle-error propagation by about 70%. Also stop emitting a blank line and redundant parentheses when output.strictModuleErrorHandling is off, so a default build is byte-identical. * fix: key an async cycle group by module id so hot updates do not leak The cycle group lives for the life of the runtime, so pushing the module object into it retained every disposed generation once hot replacement swapped a member, and the error was then recorded on the stale object instead of the module actually in the cache. The group holds ids now, deduplicated on entry, and the error is applied through the module cache. Hot replacement is how most builds reach this path at all, since HotModuleReplacementPlugin turns output.strictModuleErrorHandling on. * test: cover a deferred member of an errored async cycle Reaching a cycle member through a deferred namespace after a peer has already failed is a different path from importing a fulfilled one: the deferred import gathers the component's async dependencies, so both it and the namespace access must report the recorded error. Before the fix this handed back the member's exports instead.
1 parent 9d3e6a5 commit 7d49735

16 files changed

Lines changed: 261 additions & 74 deletions

File tree

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+
Reject a fulfilled async cycle member with the cycle's evaluation error.

‎lib/RuntimePlugin.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,11 @@ class RuntimePlugin {
402402
compilation.addLazyRuntimeModule(
403403
chunk,
404404
getAsyncModuleRuntimeModule,
405-
(Ctor) => new Ctor(experiments.deferImport)
405+
(Ctor) =>
406+
new Ctor(
407+
experiments.deferImport,
408+
compilation.outputOptions.strictModuleErrorHandling
409+
)
406410
);
407411
return true;
408412
});

‎lib/dependencies/HarmonyCompatibilityDependency.js‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,18 @@ const NullDependency = require("./NullDependency");
1717
const getJavascriptModulesPlugin = memoize(() =>
1818
require("../javascript/JavascriptModulesPlugin")
1919
);
20+
// Same reason: the deferred-namespace runtime imports dependencies from here.
21+
const getDeferredCycleHelpers = memoize(() =>
22+
require("../runtime/MakeDeferredNamespaceObjectRuntime")
23+
);
2024

2125
/** @import { ReplaceSource } from "webpack-sources" */
2226
/** @import Dependency from "../Dependency" */
2327
/** @import { DependencyTemplateContext } from "../DependencyTemplate" */
2428
/** @import { BuildMeta } from "../Module" */
29+
/** @import Module from "../Module" */
30+
/** @import ModuleGraph from "../ModuleGraph" */
31+
/** @import ChunkGraph, { ModuleId } from "../ChunkGraph" */
2532
/**
2633
* @import {
2734
* JavascriptModuleBuildInfo
@@ -39,6 +46,39 @@ makeSerializable(
3946
"webpack/lib/dependencies/HarmonyCompatibilityDependency"
4047
);
4148

49+
/**
50+
* Key shared by the async modules of one strongly-connected component. The spec
51+
* records one `[[EvaluationError]]` per component, so a member that already
52+
* fulfilled still has to report the root's error afterwards.
53+
* @param {ModuleGraph} moduleGraph the module graph
54+
* @param {ChunkGraph} chunkGraph the chunk graph
55+
* @param {Module} module the async module
56+
* @returns {ModuleId | null} the group key, or null when it is not in an async cycle
57+
*/
58+
const getAsyncCycleGroupId = (moduleGraph, chunkGraph, module) => {
59+
const { getDeferredCycleModules } = getDeferredCycleHelpers();
60+
const peers = getDeferredCycleModules(moduleGraph, module);
61+
if (peers === null) return null;
62+
// The component's smallest async member id names the group, so every member
63+
// emits the same key and none has to carry the whole peer list.
64+
let groupId = null;
65+
let asyncPeerCount = 0;
66+
for (const peer of peers) {
67+
if (!moduleGraph.isAsync(peer)) continue;
68+
asyncPeerCount++;
69+
const id = chunkGraph.getModuleId(peer);
70+
if (id !== null && (groupId === null || `${id}` < `${groupId}`)) {
71+
groupId = id;
72+
}
73+
}
74+
if (asyncPeerCount === 0) return null;
75+
const ownId = chunkGraph.getModuleId(module);
76+
if (ownId !== null && (groupId === null || `${ownId}` < `${groupId}`)) {
77+
groupId = ownId;
78+
}
79+
return groupId;
80+
};
81+
4282
HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate extends (
4383
NullDependency.Template
4484
) {
@@ -56,6 +96,7 @@ HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate
5696
module,
5797
runtimeTemplate,
5898
moduleGraph,
99+
chunkGraph,
59100
initFragments,
60101
runtimeRequirements,
61102
runtime,
@@ -99,9 +140,23 @@ HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate
99140
}
100141
if (moduleGraph.isAsync(module)) {
101142
runtimeRequirements.add(RuntimeGlobals.module);
102-
const hasAwait = /** @type {BuildMeta} */ (module.buildMeta).async
103-
? ", 1"
104-
: "";
143+
// Only `strictModuleErrorHandling` keeps a recorded error for later
144+
// requires, so the component's peers are worth naming only then.
145+
const cycleGroupId = runtimeTemplate.outputOptions
146+
.strictModuleErrorHandling
147+
? getAsyncCycleGroupId(moduleGraph, chunkGraph, module)
148+
: null;
149+
// The group is keyed by module id, so the runtime needs `module.id`.
150+
if (cycleGroupId !== null) {
151+
runtimeRequirements.add(RuntimeGlobals.moduleId);
152+
}
153+
const isAsyncBody = /** @type {BuildMeta} */ (module.buildMeta).async;
154+
const hasAwait =
155+
cycleGroupId === null
156+
? isAsyncBody
157+
? ", 1"
158+
: ""
159+
: `, ${isAsyncBody ? 1 : 0}, ${JSON.stringify(cycleGroupId)}`;
105160
// A module-scope `await using` is disposed when its scope ends, so the body
106161
// needs a block that closes before the module reports completion —
107162
// otherwise dependents run before disposal is awaited.

‎lib/runtime/AsyncModuleRuntimeModule.js‎

Lines changed: 100 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,14 @@ const HelperRuntimeModule = require("./HelperRuntimeModule");
1313
class AsyncModuleRuntimeModule extends HelperRuntimeModule {
1414
/**
1515
* @param {boolean=} deferInterop if defer import is used.
16+
* @param {boolean=} strictModuleErrorHandling if a recorded evaluation error is kept.
1617
*/
17-
constructor(deferInterop = false) {
18+
constructor(deferInterop = false, strictModuleErrorHandling = false) {
1819
super("async module");
1920
/** @type {boolean} */
2021
this._deferInterop = deferInterop;
22+
/** @type {boolean} */
23+
this._strictModuleErrorHandling = strictModuleErrorHandling;
2124
}
2225

2326
/**
@@ -29,6 +32,11 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
2932
const { runtimeTemplate } = compilation;
3033
const fn = RuntimeGlobals.asyncModule;
3134
const defer = this._deferInterop;
35+
const strictErrors = this._strictModuleErrorHandling;
36+
const rejectCall = "reject(promise[webpackError] = err)";
37+
const rejectExpression = strictErrors
38+
? `(markCycle(err), ${rejectCall})`
39+
: rejectCall;
3240
const cst = runtimeTemplate.renderConst();
3341
const lt = runtimeTemplate.renderLet();
3442
const supportsSymbol = runtimeTemplate.supportsSymbol();
@@ -46,6 +54,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
4654
defer ? `${RuntimeGlobals.asyncModuleExportSymbol}= ` : ""
4755
}${renderSymbol("webpack exports", RuntimeGlobals.exports)};`,
4856
`${cst} webpackError = ${renderSymbol("webpack error", "__webpack_error__")};`,
57+
...(strictErrors ? [`${cst} cycleGroups = {};`] : []),
4958
defer
5059
? Template.asString([
5160
`${cst} webpackDone = ${RuntimeGlobals.asyncModuleDoneSymbol} = ${renderSymbol("webpack done", "__webpack_done__")};`,
@@ -148,73 +157,98 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
148157
])})`,
149158
"deps"
150159
)};`,
151-
`${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [
152-
`${lt} queue;`,
153-
"hasAwait && ((queue = []).d = -1);",
154-
`${cst} depQueues = new Set();`,
155-
`${cst} exports = module.exports;`,
156-
`${lt} currentDeps;`,
157-
`${lt} outerResolve;`,
158-
`${lt} reject;`,
159-
`${cst} promise = new Promise(${runtimeTemplate.basicFunction(
160-
"resolve, rej",
161-
["reject = rej;", "outerResolve = resolve;"]
162-
)});`,
163-
"promise[webpackExports] = exports;",
164-
`promise[webpackQueues] = ${runtimeTemplate.expressionFunction(
165-
`queue && fn(queue), depQueues.forEach(fn), promise["catch"](${runtimeTemplate.emptyFunction()})`,
166-
"fn"
167-
)};`,
168-
"module.exports = promise;",
169-
`${cst} handle = ${runtimeTemplate.basicFunction("deps", [
170-
"currentDeps = wrapDeps(deps);",
171-
`${lt} fn;`,
172-
`${cst} getResult = ${runtimeTemplate.returningFunction(
173-
`currentDeps.map(${runtimeTemplate.basicFunction("d", [
174-
defer ? "if(d[webpackDefer]) return d;" : "",
175-
"if(d[webpackError]) throw d[webpackError];",
176-
"return d[webpackExports];"
177-
])})`
178-
)}`,
160+
`${fn} = ${runtimeTemplate.basicFunction(
161+
strictErrors
162+
? "module, body, hasAwait, cycleGroup"
163+
: "module, body, hasAwait",
164+
[
165+
`${lt} queue;`,
166+
"hasAwait && ((queue = []).d = -1);",
167+
`${cst} depQueues = new Set();`,
168+
`${cst} exports = module.exports;`,
169+
`${lt} currentDeps;`,
170+
`${lt} outerResolve;`,
171+
`${lt} reject;`,
179172
`${cst} promise = new Promise(${runtimeTemplate.basicFunction(
180-
"resolve",
181-
[
182-
`fn = ${runtimeTemplate.expressionFunction(
183-
"resolve(getResult)",
184-
""
185-
)};`,
186-
"fn.r = 0;",
187-
`${cst} fnQueue = ${runtimeTemplate.expressionFunction(
188-
"q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn)))",
189-
"q"
190-
)};`,
191-
`currentDeps.forEach(${runtimeTemplate.expressionFunction(
192-
`${
193-
defer ? "dep[webpackDefer]||" : ""
194-
}dep[webpackQueues](fnQueue)`,
195-
"dep"
196-
)});`
197-
]
173+
"resolve, rej",
174+
["reject = rej;", "outerResolve = resolve;"]
198175
)});`,
199-
"return fn.r ? promise : getResult();"
200-
])}`,
201-
`${cst} done = ${runtimeTemplate.expressionFunction(
202-
`(err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue)${
203-
defer
204-
? ", promise[webpackDone] = true, module.evaluatingAsync = false"
205-
: ""
206-
}`,
207-
"err"
208-
)}`,
209-
// Track the async body's whole lifetime (evaluating +
210-
// evaluating-async states) with a dedicated flag — the sync require
211-
// wrapper clears `module.evaluating` as soon as `.a` returns, so a
212-
// deferred namespace reaching this module through a cycle relies on
213-
// `evaluatingAsync` to keep throwing until it is fully evaluated.
214-
defer ? "module.evaluatingAsync = true;" : "",
215-
"body(handle, done);",
216-
`${runtimeTemplate.optionalChaining("queue", "d < 0")} && (queue.d = 0);`
217-
])};`
176+
"promise[webpackExports] = exports;",
177+
`promise[webpackQueues] = ${runtimeTemplate.expressionFunction(
178+
`queue && fn(queue), depQueues.forEach(fn), promise["catch"](${runtimeTemplate.emptyFunction()})`,
179+
"fn"
180+
)};`,
181+
"module.exports = promise;",
182+
`${cst} handle = ${runtimeTemplate.basicFunction("deps", [
183+
"currentDeps = wrapDeps(deps);",
184+
`${lt} fn;`,
185+
`${cst} getResult = ${runtimeTemplate.returningFunction(
186+
`currentDeps.map(${runtimeTemplate.basicFunction("d", [
187+
defer ? "if(d[webpackDefer]) return d;" : "",
188+
"if(d[webpackError]) throw d[webpackError];",
189+
"return d[webpackExports];"
190+
])})`
191+
)}`,
192+
`${cst} promise = new Promise(${runtimeTemplate.basicFunction(
193+
"resolve",
194+
[
195+
`fn = ${runtimeTemplate.expressionFunction(
196+
"resolve(getResult)",
197+
""
198+
)};`,
199+
"fn.r = 0;",
200+
`${cst} fnQueue = ${runtimeTemplate.expressionFunction(
201+
"q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn)))",
202+
"q"
203+
)};`,
204+
`currentDeps.forEach(${runtimeTemplate.expressionFunction(
205+
`${
206+
defer ? "dep[webpackDefer]||" : ""
207+
}dep[webpackQueues](fnQueue)`,
208+
"dep"
209+
)});`
210+
]
211+
)});`,
212+
"return fn.r ? promise : getResult();"
213+
])}`,
214+
// One `[[EvaluationError]]` is recorded for a whole strongly-connected
215+
// component, so a peer that already fulfilled must report it too.
216+
...(strictErrors
217+
? [
218+
`${cst} group = cycleGroup === undefined ? undefined : (cycleGroups[cycleGroup] = cycleGroups[cycleGroup] || []);`,
219+
// Ids, not module objects: hot replacement swaps a member for a
220+
// new object under the same id, and the error belongs to that one.
221+
"group && group.indexOf(module.id) < 0 && group.push(module.id);",
222+
`${cst} markCycle = ${runtimeTemplate.expressionFunction(
223+
`group && group.forEach(${runtimeTemplate.basicFunction(
224+
"id",
225+
[
226+
`${cst} peer = __webpack_module_cache__[id];`,
227+
"if (peer && peer.error === undefined) peer.error = err;"
228+
]
229+
)})`,
230+
"err"
231+
)};`
232+
]
233+
: []),
234+
`${cst} done = ${runtimeTemplate.expressionFunction(
235+
`(err ? ${rejectExpression} : outerResolve(exports)), resolveQueue(queue)${
236+
defer
237+
? ", promise[webpackDone] = true, module.evaluatingAsync = false"
238+
: ""
239+
}`,
240+
"err"
241+
)}`,
242+
// Track the async body's whole lifetime (evaluating +
243+
// evaluating-async states) with a dedicated flag — the sync require
244+
// wrapper clears `module.evaluating` as soon as `.a` returns, so a
245+
// deferred namespace reaching this module through a cycle relies on
246+
// `evaluatingAsync` to keep throwing until it is fully evaluated.
247+
defer ? "module.evaluatingAsync = true;" : "",
248+
"body(handle, done);",
249+
`${runtimeTemplate.optionalChaining("queue", "d < 0")} && (queue.d = 0);`
250+
]
251+
)};`
218252
]);
219253
}
220254
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import "./c.js";
2+
await Promise.resolve(0);
3+
export const a = "a";
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import "./a.js";
2+
await Promise.resolve(0);
3+
throw new Error("async error in B");
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import "./b.js";
2+
await Promise.resolve(0);
3+
export const c = "c";
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import defer * as ns from "./c.js";
2+
3+
export const readC = () => ns.c;
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
it("should throw the cycle's evaluation error from a deferred member reached afterwards", async () => {
2+
// The component records one `[[EvaluationError]]`, so reaching C through a
3+
// deferred namespace after B failed must report it instead of C's exports.
4+
let errorFromB = null;
5+
try {
6+
await import("./b.js");
7+
} catch (err) {
8+
errorFromB = err;
9+
}
10+
expect(errorFromB).toBeInstanceOf(Error);
11+
expect(errorFromB.message).toBe("async error in B");
12+
13+
// Deferring an async module still gathers its async dependencies, so both
14+
// the import and the namespace access can carry the component's error.
15+
let errorFromDeferred = null;
16+
try {
17+
const { readC } = await import("./deferred.js");
18+
readC();
19+
} catch (err) {
20+
errorFromDeferred = err;
21+
}
22+
expect(errorFromDeferred).toBe(errorFromB);
23+
});
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration} */
4+
module.exports = {
5+
mode: "development",
6+
devtool: false,
7+
target: "node",
8+
output: {
9+
strictModuleErrorHandling: true
10+
},
11+
experiments: {
12+
topLevelAwait: true,
13+
deferImport: true
14+
}
15+
};

0 commit comments

Comments
 (0)