Skip to content

Commit 496744a

Browse files
fix(parser): give a synthesized namespace the spec's shape and identity (#22087)
* fix(parser): give a synthesized namespace the spec's shape A module with no ESM namespace of its own — JSON, text, CommonJS — has one synthesized at the import site, and that path never consulted `specNamespaceObject`, so `__esModule` sat beside `default` where the spec reports one name. Wrap it like the namespace a module owns; the marker stays on the object underneath, so interop still reads it. Unskips `import/import-attributes/{json,text}-via-namespace.js`. * fix(parser): hand one synthesized namespace to every importer A namespace webpack synthesizes is built at the import site, so two importers of one JSON, text or CommonJS module were handed objects that looked alike but were not the same, where the spec has one namespace per module. Cache it on the module's record, which a reload replaces, keyed by the mode whose merge bit decides which names it carries. * fix(parser): fold the ChunkGraph type import into the one above it * fix(parser): keep the fake namespace mode argument a constant
1 parent 2cf714f commit 496744a

11 files changed

Lines changed: 144 additions & 14 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+
Give a JSON, text or CommonJS namespace the spec's exotic shape and identity.

‎lib/RuntimeTemplate.js‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ const PASS_NAME = "analyzableChunkNaming";
308308
/** @import { Source } from "webpack-sources" */
309309
/** @import Compiler from "./Compiler" */
310310
/** @import Chunk, { ChunkFilenameTemplate, ChunkId } from "./Chunk" */
311-
/** @import ChunkGraph from "./ChunkGraph" */
311+
/** @import ChunkGraph, { ModuleId } from "./ChunkGraph" */
312312
/** @import Compilation from "./Compilation" */
313313
/** @import Dependency from "./Dependency" */
314314
/** @import ModuleGraph from "./ModuleGraph" */
@@ -430,6 +430,10 @@ const isAsyncExternal = (/** @type {Module} */ module) =>
430430
Boolean(/** @type {BuildMeta} */ (module.buildMeta).async) &&
431431
module instanceof getExternalModule();
432432

433+
// `createFakeNamespaceObject`'s "merge all properties" bit, the only one that
434+
// changes which names the namespace it builds carries.
435+
const MERGE_PROPERTIES_MODE = 2;
436+
433437
/**
434438
* The imported module decides, never the importer: two importers of one
435439
* module have to be handed the same namespace object.
@@ -439,6 +443,30 @@ const isAsyncExternal = (/** @type {Module} */ module) =>
439443
const usesSpecNamespaceObject = (module) =>
440444
Boolean(module.buildInfo && module.buildInfo.specNamespaceObject);
441445

446+
/**
447+
* A module with no ESM namespace of its own — JSON, text, CommonJS — has one
448+
* synthesized at each import site, so there the importer decides.
449+
* @param {Module=} originModule the module the import is emitted into
450+
* @returns {boolean} true when a namespace synthesized here has to be a spec object
451+
*/
452+
const synthesizesSpecNamespaceObject = (originModule) =>
453+
originModule !== undefined && usesSpecNamespaceObject(originModule);
454+
455+
/**
456+
* Names the record a synthesized namespace belongs to and the shape it is built in,
457+
* so every importer of one module reaches the same object and a reloaded module is
458+
* not handed the namespace of the exports it replaced.
459+
* @param {ModuleId | null} moduleId id of the imported module
460+
* @param {number} mode the createFakeNamespaceObject mode the namespace is built with
461+
* @returns {string} the arguments identifying it, ready to append to the call
462+
*/
463+
const synthesizedNamespaceOwner = (moduleId, mode) =>
464+
moduleId === null
465+
? ""
466+
: `, ${RuntimeGlobals.moduleCache}[${JSON.stringify(moduleId)}], ${
467+
mode & MERGE_PROPERTIES_MODE
468+
}`;
469+
442470
class RuntimeTemplate {
443471
/**
444472
* Creates an instance of RuntimeTemplate.
@@ -2195,6 +2223,15 @@ class RuntimeTemplate {
21952223
)})`;
21962224
}
21972225
}
2226+
if (synthesizesSpecNamespaceObject(originModule)) {
2227+
runtimeRequirements.add(RuntimeGlobals.specNamespaceObject);
2228+
runtimeRequirements.add(RuntimeGlobals.moduleCache);
2229+
const owner = synthesizedNamespaceOwner(moduleId, fakeType);
2230+
appending += `.then(${this.returningFunction(
2231+
`${RuntimeGlobals.specNamespaceObject}(m${owner})`,
2232+
"m"
2233+
)})`;
2234+
}
21982235
break;
21992236
}
22002237
}
@@ -2501,11 +2538,21 @@ class RuntimeTemplate {
25012538
`${importVar}_namespace_cache`
25022539
)
25032540
);
2541+
const fakeMode = exportsType === "default-only" ? 0 : 2;
2542+
const fakeArguments = fakeMode === 0 ? "" : ", 2";
2543+
let fakeNamespace = `${RuntimeGlobals.createFakeNamespaceObject}(${importVar}${fakeArguments})`;
2544+
if (synthesizesSpecNamespaceObject(originModule)) {
2545+
runtimeRequirements.add(RuntimeGlobals.specNamespaceObject);
2546+
runtimeRequirements.add(RuntimeGlobals.moduleCache);
2547+
const owner = synthesizedNamespaceOwner(
2548+
chunkGraph.getModuleId(module),
2549+
fakeMode
2550+
);
2551+
fakeNamespace = `${RuntimeGlobals.specNamespaceObject}(${fakeNamespace}${owner})`;
2552+
}
25042553
return `/*#__PURE__*/ ${
25052554
asiSafe ? "" : asiSafe === false ? ";" : "Object"
2506-
}(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${
2507-
RuntimeGlobals.createFakeNamespaceObject
2508-
}(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`;
2555+
}(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${fakeNamespace}))`;
25092556
}
25102557
}
25112558

‎lib/runtime/SpecNamespaceObjectRuntimeModule.js‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,18 @@ class SpecNamespaceObjectRuntimeModule extends HelperRuntimeModule {
2424
const compilation = /** @type {Compilation} */ (this.compilation);
2525
const { runtimeTemplate } = compilation;
2626
const cst = runtimeTemplate.renderConst();
27+
const lt = runtimeTemplate.renderLet();
2728
const fn = RuntimeGlobals.specNamespaceObject;
2829
return Template.asString([
29-
`${fn} = ${runtimeTemplate.basicFunction("exports", [
30-
// One namespace per module, and the module's own exports object is
31-
// what identifies it, so importers share a single proxy.
32-
`${cst} cached = ${fn}.c.get(exports);`,
30+
`${fn} = ${runtimeTemplate.basicFunction("exports, record, mode", [
31+
// One namespace per module: a module's own exports object identifies it,
32+
// while a synthesized one is fresh per site, so its record identifies it.
33+
`${cst} owner = record || exports;`,
34+
`${lt} slots = ${fn}.c.get(owner);`,
35+
`if (slots === undefined) ${fn}.c.set(owner, (slots = { __proto__: null }));`,
36+
// A synthesized namespace carries different names per mode, so one
37+
// module can owe its importers more than one namespace.
38+
`${cst} cached = slots[mode];`,
3339
"if (cached) return cached;",
3440
// The exports object keeps the live bindings; the sealed target
3541
// carries only their names, so the traps stay invariant-safe.
@@ -72,10 +78,10 @@ class SpecNamespaceObjectRuntimeModule extends HelperRuntimeModule {
7278
"deleteProperty: function(_, name) { return !own(name) && !Reflect.has(target, name); }"
7379
]),
7480
"});",
75-
`${fn}.c.set(exports, ns);`,
81+
"slots[mode] = ns;",
7682
"return ns;"
7783
])};`,
78-
// The same exports object must always yield the same namespace.
84+
// The same owner must always yield the same namespace.
7985
`${fn}.c = new WeakMap();`
8086
]);
8187
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"use strict";
2+
3+
exports.a = 1;
4+
exports.b = 2;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
262
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import jsonDefault from "./data.json" with { type: "json" };
2+
import * as json from "./data.json" with { type: "json" };
3+
import * as text from "./note.txt" with { type: "text" };
4+
import * as named from "./named.json";
5+
import * as cjs from "./cjs.js";
6+
import { seenElsewhere } from "./other.js";
7+
8+
it("should hand out a spec namespace for a JSON module", () => {
9+
expect(Object.getOwnPropertyNames(json)).toEqual(["default"]);
10+
expect(json.default).toBe(262);
11+
expect(Object.getPrototypeOf(json)).toBe(null);
12+
expect(json[Symbol.toStringTag]).toBe("Module");
13+
expect(Object.isExtensible(json)).toBe(false);
14+
});
15+
16+
it("should hand out a spec namespace for a text module", () => {
17+
expect(Object.getOwnPropertyNames(text)).toEqual(["default"]);
18+
expect(typeof text.default).toBe("string");
19+
});
20+
21+
it("should hand out a spec namespace for a dynamically imported JSON module", () =>
22+
import("./data.json", { with: { type: "json" } }).then((ns) => {
23+
expect(Object.getOwnPropertyNames(ns)).toEqual(["default"]);
24+
expect(ns.default).toBe(262);
25+
}));
26+
27+
it("should keep the named exports webpack adds to a bare JSON import", () => {
28+
expect(Object.getOwnPropertyNames(named)).toEqual(["a", "b", "default"]);
29+
});
30+
31+
it("should hand out a spec namespace for a CommonJS module", () => {
32+
expect(Object.getOwnPropertyNames(cjs)).toEqual(["a", "b", "default"]);
33+
expect(cjs.a).toBe(1);
34+
expect(cjs.default.b).toBe(2);
35+
});
36+
37+
it("should hide the marker without changing what the module exports", () => {
38+
// Only the namespace view drops `__esModule`; the value behind it is
39+
// untouched, so interop still reads the module the way it always did.
40+
expect("__esModule" in json).toBe(false);
41+
expect(require("./data.json")).toBe(262);
42+
expect(jsonDefault).toBe(262);
43+
});
44+
45+
it("should hand every importer of one module the same namespace", () => {
46+
// The spec has one namespace object per module, so a second importer has to
47+
// reach the very same object rather than an equal-looking one.
48+
expect(json).toBe(seenElsewhere.json);
49+
expect(text).toBe(seenElsewhere.text);
50+
expect(cjs).toBe(seenElsewhere.cjs);
51+
});
52+
53+
it("should reach that same namespace through a dynamic import", () =>
54+
import("./data.json", { with: { type: "json" } }).then((ns) => {
55+
expect(ns).toBe(json);
56+
}));
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"a":1,"b":2}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
262
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import * as json from "./data.json" with { type: "json" };
2+
import * as text from "./note.txt" with { type: "text" };
3+
import * as cjs from "./cjs.js";
4+
5+
export const seenElsewhere = { json, text, cjs };
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration} */
4+
module.exports = {
5+
module: {
6+
rules: [{ test: /\.js$/, parser: { specNamespaceObject: true } }]
7+
}
8+
};

0 commit comments

Comments
 (0)