Skip to content

Commit 9f6a084

Browse files
fix(defer): build a deferred namespace for an async module (#21871)
* fix(defer): build a deferred namespace for an async module `import defer` of a module with top-level await was treated as a plain import, so no deferred namespace existed and forcing it during the module's own evaluating-async state returned exports instead of throwing a TypeError. The phase alone now decides, and the eager evaluation the spec requires for such a module is unchanged. Two things fall out of that. A module deferring itself must not be awaited as its own async dependency, which would probe the namespace and force the evaluation it must not trigger. And `deferredModuleAsyncTransitiveDependencies` is now declared where it is emitted, and mapped to the async module runtime that defines it, instead of relying on another module pulling that runtime in. * fix(defer): keep an async external undeferred `configCases/externals/phase-imports-defer` pins that `import defer` of an already-async external stays a plain import. An external is a promise webpack awaits, not a module record with an evaluating state, so a deferred namespace for one can never throw and only costs bytes. Deferring now follows the phase for modules webpack evaluates and leaves async externals alone. * docs: shorten the async-external helper comment * docs: drop the helper JSDoc for a one-line comment
1 parent 19f9600 commit 9f6a084

9 files changed

Lines changed: 68 additions & 10 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+
Throw when a deferred namespace of an async module is forced while it evaluates.

‎lib/RuntimePlugin.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,9 @@ const TREE_DEPENDENCIES = {
189189
RuntimeGlobals.makeNamespaceObject,
190190
RuntimeGlobals.require
191191
],
192+
[RuntimeGlobals.deferredModuleAsyncTransitiveDependencies]: [
193+
RuntimeGlobals.asyncModule
194+
],
192195
[RuntimeGlobals.makeOptimizedDeferredNamespaceObject]: [
193196
RuntimeGlobals.require
194197
],

‎lib/RuntimeTemplate.js‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ const {
5555
const getCssModulesPlugin = memoize(() => require("./css/CssModulesPlugin"));
5656
// `Compilation` requires this module, so its stage constants are read lazily.
5757
const getCompilation = memoize(() => require("./Compilation"));
58+
const getExternalModule = memoize(() => require("./ExternalModule"));
5859

5960
/**
6061
* @typedef {object} ChunkAssetNaming
@@ -422,6 +423,11 @@ function getGlobalObject(definition) {
422423
return `Object(${trimmed})`;
423424
}
424425

426+
// An async external is a promise, not a module record with an evaluating state.
427+
const isAsyncExternal = (/** @type {Module} */ module) =>
428+
Boolean(/** @type {BuildMeta} */ (module.buildMeta).async) &&
429+
module instanceof getExternalModule();
430+
425431
class RuntimeTemplate {
426432
/**
427433
* Creates an instance of RuntimeTemplate.
@@ -1988,6 +1994,9 @@ class RuntimeTemplate {
19881994
(m) => chunkGraph.getModuleId(m)
19891995
).filter((id) => id !== null);
19901996
if (asyncDeps.length) {
1997+
runtimeRequirements.add(
1998+
RuntimeGlobals.deferredModuleAsyncTransitiveDependencies
1999+
);
19912000
if (header) {
19922001
appending = `.then(${this.basicFunction(
19932002
"",
@@ -2224,11 +2233,14 @@ class RuntimeTemplate {
22242233
(dependency instanceof HarmonyImportDependency ||
22252234
dependency instanceof ImportDependency) &&
22262235
ImportPhaseUtils.isDefer(dependency.phase) &&
2227-
!(/** @type {BuildMeta} */ (module.buildMeta).async);
2236+
!isAsyncExternal(module);
22282237

22292238
if (isModuleDeferred) {
22302239
/** @type {Set<Module>} */
22312240
const outgoingAsyncModules = getOutgoingAsyncModules(moduleGraph, module);
2241+
// A module deferring itself is already evaluating, so awaiting it here
2242+
// would deadlock; forcing the namespace throws instead.
2243+
outgoingAsyncModules.delete(originModule);
22322244

22332245
importContent = `/* deferred harmony import */ ${optDeclaration}${importVar} = ${getOptimizedDeferredModule(
22342246
moduleId,
@@ -2313,7 +2325,7 @@ class RuntimeTemplate {
23132325
(dependency instanceof HarmonyImportDependency ||
23142326
dependency instanceof ImportDependency) &&
23152327
ImportPhaseUtils.isDefer(dependency.phase) &&
2316-
!(/** @type {BuildMeta} */ (module.buildMeta).async);
2328+
!isAsyncExternal(module);
23172329

23182330
if (defaultInterop) {
23192331
// when the defaultInterop is used (when a ESM imports a CJS module),

‎lib/dependencies/HarmonyImportDependency.js‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,14 @@ const InitFragment = require("../InitFragment");
1111
const Template = require("../Template");
1212
const AwaitDependenciesInitFragment = require("../async-modules/AwaitDependenciesInitFragment");
1313
const isGeneratorLowered = require("../async-modules/isGeneratorLowered");
14+
const memoize = require("../util/memoize");
1415
const { filterRuntime, mergeRuntime } = require("../util/runtime");
1516
const HarmonyLinkingError = require("./HarmonyLinkingError");
1617
const { ImportPhase, ImportPhaseUtils } = require("./ImportPhase");
1718
const ModuleDependency = require("./ModuleDependency");
1819

20+
const getExternalModule = memoize(() => require("../ExternalModule"));
21+
1922
/** @import { ReplaceSource } from "webpack-sources" */
2023
/**
2124
* @import {
@@ -185,9 +188,14 @@ class HarmonyImportDependency extends ModuleDependency {
185188
const importedModule = /** @type {Module} */ (moduleGraph.getModule(this));
186189
const meta = moduleGraph.getMeta(module);
187190

191+
// An async external is a promise webpack awaits, not a module record with
192+
// an evaluating state, so deferring its namespace would never throw.
188193
const isDeferred =
189194
ImportPhaseUtils.isDefer(this.phase) &&
190-
!(/** @type {BuildMeta} */ (importedModule.buildMeta).async);
195+
!(
196+
/** @type {BuildMeta} */ (importedModule.buildMeta).async &&
197+
importedModule instanceof getExternalModule()
198+
);
191199

192200
const metaKey = isDeferred ? "deferredImportVarMap" : "importVarMap";
193201
let importVarMap = meta[metaKey];
@@ -468,8 +476,13 @@ HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
468476
}
469477

470478
const importStatement = dep.getImportStatement(false, templateContext);
479+
// A module deferring itself is already evaluating: awaiting it would probe
480+
// the deferred namespace and force the evaluation it must not trigger.
481+
const isSelfDeferred =
482+
ImportPhaseUtils.isDefer(dep.phase) && referencedModule === module;
471483
if (
472484
referencedModule &&
485+
!isSelfDeferred &&
473486
templateContext.moduleGraph.isAsync(referencedModule)
474487
) {
475488
templateContext.initFragments.push(
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import defer * as ns from "./dep.js";
2+
3+
await Promise.resolve();
4+
5+
// Still evaluating-async at this point, so forcing the namespace must throw.
6+
try {
7+
ns.foo;
8+
} catch (error) {
9+
globalThis.deferAsyncSelfError = error;
10+
}
11+
12+
export const foo = 1;
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import "./dep.js";
2+
3+
it("should throw when a deferred namespace of an async module is forced while it evaluates", () => {
4+
expect(globalThis.deferAsyncSelfError).toBeInstanceOf(TypeError);
5+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"use strict";
2+
3+
const supportsAsync = require("../../../helpers/supportsAsync");
4+
5+
module.exports = () => supportsAsync();
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration} */
4+
module.exports = {
5+
target: [`async-node${process.versions.node.split(".").map(Number)[0]}`],
6+
experiments: {
7+
deferImport: true,
8+
topLevelAwait: true
9+
}
10+
};

‎test/test262.spectest.js‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -892,13 +892,6 @@ const knownBugs = [
892892
// Host resolution errors must be reported eagerly even for deferred imports;
893893
// webpack turns a missing module into a build error resolved lazily instead.
894894
"import/import-defer/errors/resolution-error/import-defer-of-missing-module-fails.js",
895-
// The deferred module itself has top-level await, so webpack evaluates it
896-
// eagerly through the async-dependency system and never builds a deferred
897-
// namespace for it — throwing on self/other access during its own
898-
// evaluating-async state would require routing async defer imports through a
899-
// deferred namespace while preserving eager awaiting (a larger change).
900-
"import/import-defer/errors/get-self-while-evaluating-async/main.js",
901-
"import/import-defer/errors/get-other-while-evaluating-async/main.js",
902895
// Exact interleaving of top-level-await and deferred evaluation order.
903896
"import/import-defer/evaluation-top-level-await/flattening-order/main.js",
904897
// A deferred module must wait for the whole strongly-connected component when a

0 commit comments

Comments
 (0)