Skip to content

Commit 3d2bec0

Browse files
authored
fix: follow renamed declarations in the inlined entry's exports (#22207)
1 parent 8165624 commit 3d2bec0

9 files changed

Lines changed: 188 additions & 15 deletions

File tree

‎lib/javascript/JavascriptModulesPlugin.js‎

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ const printGeneratedCodeForStack = (module, code) => {
253253
* @property {boolean=} inlined inlined
254254
* @property {boolean=} inlinedInIIFE the inlined entry module is wrapped in an IIFE
255255
* @property {boolean=} needExportsDeclaration whether the top-level exports declaration needs to be generated
256+
* @property {Map<string, string>=} renamedDeclarations the inlined entry's top-level declarations renamed to avoid a collision, original to new name
256257
*/
257258

258259
/**
@@ -367,6 +368,7 @@ const createCompilationHooks = () => ({
367368
* @param {string} moduleIdentifier the module identifier (for scope caching)
368369
* @param {string} readableIdentifier the readable module identifier (for new names)
369370
* @param {Set<string>} allUsedNames names already used in the shared scope (mutated)
371+
* @param {Map<string, string>} renamedDeclarations the declarations renamed so far, original to new name (mutated)
370372
* @returns {void}
371373
*/
372374
const renameInlinedModuleVariable = (
@@ -375,7 +377,8 @@ const renameInlinedModuleVariable = (
375377
variable,
376378
moduleIdentifier,
377379
readableIdentifier,
378-
allUsedNames
380+
allUsedNames,
381+
renamedDeclarations
379382
) => {
380383
/** @type {UsedNamesInScopeInfo} */
381384
const usedNamesInScopeInfo = new Map();
@@ -406,6 +409,7 @@ const renameInlinedModuleVariable = (
406409
readableIdentifier
407410
);
408411
allUsedNames.add(newName);
412+
renamedDeclarations.set(name, newName);
409413
for (const identifier of allIdentifiers) {
410414
const r = /** @type {Range} */ (identifier.range);
411415
const path = getPathInAst(ast, identifier);
@@ -429,6 +433,12 @@ const PLUGIN_NAME = "JavascriptModulesPlugin";
429433

430434
/** @typedef {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} Bootstrap */
431435

436+
/**
437+
* @typedef {object} RenamedInlinedModules
438+
* @property {Map<Module, Source>} sources each inlined module's rendered source, renamed where it collided
439+
* @property {Map<Module, Map<string, string>>} renamedDeclarations each renamed module's declarations, original to new name
440+
*/
441+
432442
class JavascriptModulesPlugin {
433443
constructor(options = {}) {
434444
this.options = options;
@@ -1272,7 +1282,7 @@ class JavascriptModulesPlugin {
12721282
const startupSource = new ConcatSource();
12731283

12741284
const avoidEntryIife = compilation.options.optimization.avoidEntryIife;
1275-
/** @type {Map<Module, Source> | false} */
1285+
/** @type {RenamedInlinedModules | false} */
12761286
let renamedInlinedModule = false;
12771287
let inlinedInIIFE = false;
12781288

@@ -1316,7 +1326,7 @@ class JavascriptModulesPlugin {
13161326
}
13171327

13181328
const renderedModule = renamedInlinedModule
1319-
? renamedInlinedModule.get(m)
1329+
? renamedInlinedModule.sources.get(m)
13201330
: this.renderModule(
13211331
m,
13221332
{
@@ -1373,7 +1383,10 @@ class JavascriptModulesPlugin {
13731383
...renderContext,
13741384
inlined: true,
13751385
inlinedInIIFE,
1376-
needExportsDeclaration: runtimeRequirements.has(RuntimeGlobals.exports)
1386+
needExportsDeclaration: runtimeRequirements.has(RuntimeGlobals.exports),
1387+
renamedDeclarations: renamedInlinedModule
1388+
? renamedInlinedModule.renamedDeclarations.get(lastInlinedModule)
1389+
: undefined
13771390
};
13781391
let renderedStartup = hooks.renderStartup.call(
13791392
startupSource,
@@ -2105,7 +2118,7 @@ class JavascriptModulesPlugin {
21052118
* @param {CompilationHooks} hooks hooks
21062119
* @param {boolean | undefined} allStrict allStrict
21072120
* @param {boolean} hasChunkModules hasChunkModules
2108-
* @returns {Map<Module, Source> | false} renamed inlined modules
2121+
* @returns {RenamedInlinedModules | false} renamed inlined modules
21092122
*/
21102123
_getRenamedInlineModule(
21112124
compilation,
@@ -2131,6 +2144,8 @@ class JavascriptModulesPlugin {
21312144

21322145
/** @type {Map<Module, Source>} */
21332146
const renamedInlinedModules = new Map();
2147+
/** @type {Map<Module, Map<string, string>>} */
2148+
const renamedDeclarations = new Map();
21342149
const { runtimeTemplate } = renderContext;
21352150

21362151
/** @typedef {{ source: Source, module: Module, ast: Program, variables: Set<Variable>, through: Set<Reference>, usedInNonInlined: Set<Variable>, moduleScope: Scope }} Info */
@@ -2243,7 +2258,10 @@ class JavascriptModulesPlugin {
22432258
for (const [m, moduleSource] of inlinedModuleSources) {
22442259
renamedInlinedModules.set(m, moduleSource);
22452260
}
2246-
return renamedInlinedModules;
2261+
return {
2262+
sources: renamedInlinedModules,
2263+
renamedDeclarations
2264+
};
22472265
}
22482266

22492267
for (const [m, moduleSource] of inlinedModuleSources) {
@@ -2301,19 +2319,26 @@ class JavascriptModulesPlugin {
23012319
for (const [m, moduleInfo] of inlinedModulesToInfo) {
23022320
const { ast, source: _source } = moduleInfo;
23032321
const source = new ReplaceSource(_source);
2322+
/** @type {Map<string, string>} */
2323+
const renamed = new Map();
23042324
for (const variable of moduleInfo.variables) {
23052325
renameInlinedModuleVariable(
23062326
source,
23072327
ast,
23082328
variable,
23092329
moduleInfo.module.identifier(),
23102330
m.readableIdentifier(runtimeTemplate.requestShortener),
2311-
allUsedNames
2331+
allUsedNames,
2332+
renamed
23122333
);
23132334
}
23142335
renamedInlinedModules.set(m, source);
2336+
if (renamed.size > 0) renamedDeclarations.set(m, renamed);
23152337
}
2316-
return renamedInlinedModules;
2338+
return {
2339+
sources: renamedInlinedModules,
2340+
renamedDeclarations
2341+
};
23172342
}
23182343

23192344
for (const [m, moduleInfo] of inlinedModulesToInfo) {
@@ -2333,21 +2358,28 @@ class JavascriptModulesPlugin {
23332358
allUsedNames.add(variable.name);
23342359
}
23352360

2361+
/** @type {Map<string, string>} */
2362+
const renamed = new Map();
23362363
for (const variable of info.variables) {
23372364
renameInlinedModuleVariable(
23382365
source,
23392366
ast,
23402367
variable,
23412368
info.module.identifier(),
23422369
m.readableIdentifier(runtimeTemplate.requestShortener),
2343-
allUsedNames
2370+
allUsedNames,
2371+
renamed
23442372
);
23452373
}
23462374

23472375
renamedInlinedModules.set(m, source);
2376+
if (renamed.size > 0) renamedDeclarations.set(m, renamed);
23482377
}
23492378

2350-
return renamedInlinedModules;
2379+
return {
2380+
sources: renamedInlinedModules,
2381+
renamedDeclarations
2382+
};
23512383
}
23522384
}
23532385

‎lib/library/ModuleLibraryPlugin.js‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ const ConcatenatedModule = require("../optimize/ConcatenatedModule");
1616
const { InlinedUsedName } = require("../optimize/InlineExports");
1717
const RuntimeGlobals = require("../runtime/RuntimeGlobals");
1818
const Template = require("../template/Template");
19+
const { renameIdentifiers } = require("../util/concatenate");
1920
const {
2021
RESERVED_IDENTIFIER,
2122
SAFE_IDENTIFIER,
@@ -527,8 +528,21 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
527528
const isInlinedEntryWithoutIIFE = inlined && !inlinedInIIFE;
528529
// The binding each export left out on demand reads, exported directly
529530
/** @type {Record<string, string>} */
530-
const definitions =
531+
let definitions =
531532
(isInlinedEntryWithoutIIFE && data && data.get("exportsFinalName")) || {};
533+
// Inlined beside other modules, the entry's colliding declarations were renamed
534+
const { renamedDeclarations } = renderContext;
535+
if (renamedDeclarations) {
536+
/** @type {Record<string, string>} */
537+
const renamed = {};
538+
for (const usedName of Object.keys(definitions)) {
539+
renamed[usedName] = renameIdentifiers(
540+
definitions[usedName],
541+
renamedDeclarations
542+
);
543+
}
544+
definitions = renamed;
545+
}
532546

533547
/** @type {string[]} */
534548
const shortHandedExports = [];

‎lib/util/concatenate.js‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,30 @@ function findNewName(oldName, usedNamed1, usedNamed2, extraInfo) {
302302
return nameWithNumber;
303303
}
304304

305+
// A string literal, kept whole, or an identifier that is not a property name;
306+
const IDENTIFIER_OR_STRING_REGEXP =
307+
/"(?:[^"\\]|\\.)*"|(?<![.\w$])[A-Za-z_$][\w$]*/g;
308+
309+
/**
310+
* Renames every identifier of a printed expression that the map names, keeping
311+
* property names and string contents as they are.
312+
* @param {string} expression the expression as printed
313+
* @param {Map<string, string>} renames original to new name
314+
* @returns {string} the expression over the new names
315+
* @example
316+
* const renames = new Map([["store", "entry_store"], ["x", "entry_x"]]);
317+
* renameIdentifiers("store.x", renames) === "entry_store.x"
318+
* renameIdentifiers('store["a-b"]', renames) === 'entry_store["a-b"]'
319+
* renameIdentifiers("store/* .x *\/.c", renames) === "entry_store/* .x *\/.c"
320+
* renameIdentifiers("(store_default())", renames) === "(store_default())"
321+
* renameIdentifiers("/* reads x *\/ x", renames) === "/* reads entry_x *\/ entry_x"
322+
*/
323+
const renameIdentifiers = (expression, renames) =>
324+
expression.replace(IDENTIFIER_OR_STRING_REGEXP, (token) => {
325+
const renamed = renames.get(token);
326+
return renamed === undefined ? token : renamed;
327+
});
328+
305329
/** @typedef {Set<Scope>} ScopeSet */
306330

307331
/**
@@ -410,5 +434,6 @@ module.exports = {
410434
getAllReferences,
411435
getPathInAst,
412436
getUsedNamesInScopeInfo,
413-
isCommonJsConcatenationEnabled
437+
isCommonJsConcatenationEnabled,
438+
renameIdentifiers
414439
};
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// A script beside the entry, reading globals spelled like its declarations.
2+
module.exports = [typeof fetch, typeof store];
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// The sibling script reads globals spelled like two declarations of this body, so
2+
// both are renamed when the entry is inlined beside it.
3+
import "./legacy.js";
4+
import { twice } from "./lib.js";
5+
6+
export { x } from "./store.js";
7+
export const fetch = (url) => `fetched ${url}`;
8+
export const answer = twice();
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// CommonJS, so a concatenation reaches it through a variable instead of absorbing it.
2+
module.exports = { x: "x" };

‎test/configCases/library/module-entry-native-exports/webpack.config.js‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,16 @@ const assertBundle = (assetName, assert) =>
2323
* @param {(source: string) => void} assert what the emitted bundle must look like
2424
* @param {("production" | "development")=} mode which mode to build in
2525
* @param {boolean=} avoidEntryIife whether the entry may be inlined without an IIFE
26+
* @param {boolean=} concatenateModules whether the entry may absorb its ESM dependencies
2627
* @returns {import("../../../../").Configuration} config
2728
*/
2829
const variant = (
2930
name,
3031
entry,
3132
assert,
3233
mode = "production",
33-
avoidEntryIife = undefined
34+
avoidEntryIife = undefined,
35+
concatenateModules = false
3436
) => ({
3537
mode,
3638
devtool: false,
@@ -42,7 +44,7 @@ const variant = (
4244
module: true,
4345
library: { type: "module" }
4446
},
45-
optimization: { concatenateModules: false, minimize: false, avoidEntryIife },
47+
optimization: { concatenateModules, minimize: false, avoidEntryIife },
4648
plugins: [assertBundle(`${name}.mjs`, assert)]
4749
});
4850

@@ -112,5 +114,25 @@ module.exports = [
112114
},
113115
"development",
114116
true
117+
),
118+
// The sibling script reads globals spelled like the entry's own declarations,
119+
// so those are renamed in the inlined body — and the export statement follows.
120+
variant("renamed", "./renamed.js", (source) => {
121+
expect(source).toContain("const renamed_fetch =");
122+
expect(source).toMatch(/export \{[^}]*\brenamed_fetch as fetch\b/);
123+
}),
124+
// Concatenated, the CommonJS store is reached through a variable of the body,
125+
// so the re-export reads a property of a renamed declaration.
126+
variant(
127+
"renamed-concat",
128+
"./renamed.js",
129+
(source) => {
130+
expect(source).toContain("var renamed_store =");
131+
expect(source).toContain("export const x = renamed_store.x;");
132+
expect(source).toMatch(/export \{[^}]*\brenamed_fetch as fetch\b/);
133+
},
134+
"production",
135+
undefined,
136+
true
115137
)
116138
];

‎test/unitCases/ConcatenateUtil.unittest.js‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66

77
const JavascriptParser = require("../../lib/javascript/JavascriptParser");
88
const analyzeScope = require("../../lib/javascript/ScopeAnalyzer");
9-
const { getAllReferences } = require("../../lib/util/concatenate");
9+
const {
10+
getAllReferences,
11+
renameIdentifiers
12+
} = require("../../lib/util/concatenate");
1013

1114
/** @typedef {import("../../lib/javascript/ScopeAnalyzer").Scope} Scope */
1215
/** @typedef {import("../../lib/javascript/ScopeAnalyzer").Variable} Variable */
@@ -78,3 +81,63 @@ describe("getAllReferences", () => {
7881
expect(getAllReferences(a)).toBe(a.references);
7982
});
8083
});
84+
85+
describe("renameIdentifiers", () => {
86+
const renames = new Map([
87+
["store", "entry_store"],
88+
["store_default", "entry_store_default"],
89+
["x", "entry_x"],
90+
["a", "entry_a"],
91+
["c", "entry_c"],
92+
["sn", "entry_sn"],
93+
["e5", "entry_e5"],
94+
["named", "entry_named"]
95+
]);
96+
97+
/** Every form a final name takes, and what it reads over the renamed body. */
98+
/** @type {[string, string][]} */
99+
const forms = [
100+
// a declaration of the body
101+
["store", "entry_store"],
102+
// a property of one, whose name is not a reference
103+
["store.x", "entry_store.x"],
104+
["deferred.a", "deferred.a"],
105+
// a bracket access keeps its string key
106+
['store["a-b"]', 'entry_store["a-b"]'],
107+
// the mangling comment of an external's export
108+
["store/* .x */.c", "entry_store/* .x */.c"],
109+
// a wrapped module's accessor call
110+
["(store_default())", "(entry_store_default())"],
111+
// a spec namespace read through the runtime
112+
["(__webpack_require__.sn(store))", "(__webpack_require__.sn(entry_store))"],
113+
// an unused export of a wrapped module
114+
[
115+
"/* unused export */ (store, undefined)",
116+
"/* unused export */ (entry_store, undefined)"
117+
],
118+
["/*#__PURE__*/Object(store)", "/*#__PURE__*/Object(entry_store)"],
119+
// an inlined literal keeps its value, an escaped quote included
120+
['/* inlined export .x */"named"', '/* inlined export .x */"named"'],
121+
['"a \\" store"', '"a \\" store"'],
122+
// constants
123+
["/* __esModule */true", "/* __esModule */true"],
124+
["1e5", "1e5"],
125+
// the circular reexport literal renames its own local on both sides
126+
[
127+
"/* circular reexport */ Object(function x() { x() }())",
128+
"/* circular reexport */ Object(function entry_x() { entry_x() }())"
129+
],
130+
// a comment's words are not protected, which changes nothing that runs
131+
["/* reads store */ store.x", "/* reads entry_store */ entry_store.x"]
132+
];
133+
134+
for (const [form, expected] of forms) {
135+
it(`rewrites ${form}`, () => {
136+
expect(renameIdentifiers(form, renames)).toBe(expected);
137+
});
138+
}
139+
140+
it("returns the expression as it is when nothing in it was renamed", () => {
141+
expect(renameIdentifiers("store.x", new Map())).toBe("store.x");
142+
});
143+
});

‎types.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28724,6 +28724,11 @@ declare interface StartupRenderContext {
2872428724
* whether the top-level exports declaration needs to be generated
2872528725
*/
2872628726
needExportsDeclaration?: boolean;
28727+
28728+
/**
28729+
* the inlined entry's top-level declarations renamed to avoid a collision, original to new name
28730+
*/
28731+
renamedDeclarations?: Map<string, string>;
2872728732
}
2872828733
declare interface StatFs {
2872928734
(

0 commit comments

Comments
 (0)