Skip to content

Commit a905883

Browse files
committed
review
1 parent bfd8753 commit a905883

8 files changed

Lines changed: 126 additions & 56 deletions

File tree

‎lib/dependencies/CommonJsFullRequireDependency.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,6 @@ class CommonJsFullRequireDependency extends ModuleDependency {
7474
if (guards === undefined) return null;
7575
return (connection, runtime) =>
7676
!getHarmonyImportGuard().isDeadByGuards(guards, moduleGraph, runtime);
77-
/** @type {boolean} */
7877
}
7978

8079
/**

‎lib/optimize/ConcatenatedModule.js‎

Lines changed: 60 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,8 @@ if (!ReferencerClass.prototype.PropertyDefinition) {
198198
/**
199199
* @typedef {object} ExternalModuleInfo
200200
* @property {"external"} type
201-
* @property {boolean} wrapped the body renders inside the lazy CJS wrapper with real module/exports instead of being scope-hoisted into the shared scope
202-
* @property {boolean} eager a wrapped body reached by an eager import edge, so its accessor is called at its own slot in evaluation order
201+
* @property {boolean} wrapped the module's `require()` call is deferred behind an accessor instead of running at its own slot; unlike a wrapped concatenated member there is no body and no CJS wrapper, so any external may be wrapped
202+
* @property {boolean} eager a wrapped module reached by an eager import edge, so its accessor is called at its own slot in evaluation order
203203
* @property {Module} module
204204
* @property {RuntimeSpec | boolean} runtimeCondition
205205
* @property {NonDeferAccess} nonDeferAccess
@@ -305,7 +305,7 @@ const subtractNonDeferAccess = (a, b) => a && !b;
305305
/**
306306
* @typedef {object} ConcatenationEntry
307307
* @property {"concatenated" | "external"} type
308-
* @property {boolean} wrapped the module renders inside the lazy CJS wrapper instead of being scope-hoisted
308+
* @property {boolean} wrapped evaluation is deferred behind an accessor: a "concatenated" entry renders its body inside the lazy CJS wrapper instead of being scope-hoisted, an "external" entry only defers its `require()` call
309309
* @property {Module} module
310310
* @property {RuntimeSpec | boolean} runtimeCondition
311311
* @property {NonDeferAccess} nonDeferAccess
@@ -1305,14 +1305,12 @@ class ConcatenatedModule extends Module {
13051305
(connection.dependency);
13061306
return {
13071307
connection,
1308-
// Coerce a missing sourceOrder (require() edges) to NaN:
1309-
// compareNumbers sorts NaN consistently (last), while undefined
1310-
// would make the comparator inconsistent and the order depend on
1311-
// async connection insertion order.
1308+
// A require() edge carries no sourceOrder; Infinity sorts it last,
1309+
// matching the low-priority sentinel. NaN must not be used here:
1310+
// compareNumbers returns 0 against every number, which makes the
1311+
// comparator non-transitive and the order depend on insertion order.
13121312
sourceOrder:
1313-
typeof dep.sourceOrder === "number"
1314-
? dep.sourceOrder
1315-
: Number.NaN,
1313+
typeof dep.sourceOrder === "number" ? dep.sourceOrder : Infinity,
13161314
rangeStart: dep.range && dep.range[0],
13171315
defer: ImportPhaseUtils.isDefer(dep.phase)
13181316
};
@@ -1783,9 +1781,13 @@ class ConcatenatedModule extends Module {
17831781
// A wrapped body has no scope analysis, so its references are found
17841782
// textually. They still have to be resolved here: binding one is what
17851783
// flags the interop objects it needs, and [3] allocates their names.
1784+
/** @type {Set<string>} */
1785+
const visitedReferences = new Set();
17861786
for (const reference of ConcatenationScope.findModuleReferences(
17871787
/** @type {Source} */ (info.internalSource)
17881788
)) {
1789+
if (visitedReferences.has(reference.name)) continue;
1790+
visitedReferences.add(reference.name);
17891791
const match = ConcatenationScope.matchModuleReference(
17901792
reference.name
17911793
);
@@ -1794,6 +1796,13 @@ class ConcatenatedModule extends Module {
17941796
if (referencedInfo.type === "reference") {
17951797
throw new Error("Module reference can't point to a reference");
17961798
}
1799+
if (
1800+
match.mangleableNamespace &&
1801+
match.ids.length === 0 &&
1802+
getEscapeNamespaceObjectName(referencedInfo) !== undefined
1803+
) {
1804+
continue;
1805+
}
17971806
getFinalBinding(
17981807
moduleGraph,
17991808
referencedInfo,
@@ -2266,43 +2275,51 @@ class ConcatenatedModule extends Module {
22662275
} else {
22672276
// Wrapped bodies are not re-parsed: find their reference tokens
22682277
// textually. [2] scanned the same source, so this reuses its result.
2278+
/** @type {Map<string, string>} */
2279+
const finalNames = new Map();
2280+
const source = /** @type {ReplaceSource} */ (info.source);
22692281
for (const reference of ConcatenationScope.findModuleReferences(
22702282
/** @type {Source} */ (info.internalSource)
22712283
)) {
2272-
const match = ConcatenationScope.matchModuleReference(reference.name);
2273-
if (!match) continue;
2274-
const referencedInfo = modulesWithInfo[match.index];
2275-
if (referencedInfo.type === "reference") {
2276-
throw new Error("Module reference can't point to a reference");
2284+
let finalName = finalNames.get(reference.name);
2285+
if (finalName === undefined) {
2286+
const match = ConcatenationScope.matchModuleReference(
2287+
reference.name
2288+
);
2289+
if (!match) continue;
2290+
const referencedInfo = modulesWithInfo[match.index];
2291+
if (referencedInfo.type === "reference") {
2292+
throw new Error("Module reference can't point to a reference");
2293+
}
2294+
// Same escaping whole-namespace rule as the hoisted branch above: a
2295+
// wrapped target resolves to its `X_namespaceFn()` exports object,
2296+
// whose keys are the mangled ones.
2297+
const escapeName =
2298+
match.mangleableNamespace && match.ids.length === 0
2299+
? getEscapeNamespaceObjectName(referencedInfo)
2300+
: undefined;
2301+
finalName =
2302+
escapeName !== undefined
2303+
? escapeName
2304+
: getFinalName(
2305+
moduleGraph,
2306+
referencedInfo,
2307+
match.ids,
2308+
moduleToInfoMap,
2309+
runtime,
2310+
requestShortener,
2311+
runtimeTemplate,
2312+
neededNamespaceObjects,
2313+
match.call,
2314+
match.deferredImport,
2315+
!match.directImport,
2316+
/** @type {BuildMeta} */
2317+
(info.module.buildMeta).strictHarmonyModule,
2318+
match.asiSafe,
2319+
match.moduleExportsAccess
2320+
);
2321+
finalNames.set(reference.name, finalName);
22772322
}
2278-
// Same escaping whole-namespace rule as the hoisted branch above: a
2279-
// wrapped target resolves to its `X_namespaceFn()` exports object,
2280-
// whose keys are the mangled ones.
2281-
const escapeName =
2282-
match.mangleableNamespace && match.ids.length === 0
2283-
? getEscapeNamespaceObjectName(referencedInfo)
2284-
: undefined;
2285-
const finalName =
2286-
escapeName !== undefined
2287-
? escapeName
2288-
: getFinalName(
2289-
moduleGraph,
2290-
referencedInfo,
2291-
match.ids,
2292-
moduleToInfoMap,
2293-
runtime,
2294-
requestShortener,
2295-
runtimeTemplate,
2296-
neededNamespaceObjects,
2297-
match.call,
2298-
match.deferredImport,
2299-
!match.directImport,
2300-
/** @type {BuildMeta} */
2301-
(info.module.buildMeta).strictHarmonyModule,
2302-
match.asiSafe,
2303-
match.moduleExportsAccess
2304-
);
2305-
const source = /** @type {ReplaceSource} */ (info.source);
23062323
// token end is extended by 2 chars to cover the appended "._"
23072324
source.replace(reference.start, reference.end + 1, finalName);
23082325
}

‎lib/runtime/ConstructRequireRuntimeModule.js‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,11 @@ class ConstructRequireRuntimeModule extends HelperRuntimeModule {
2929
"// instance, exactly as in Node.js. A concatenated module has no require",
3030
"// call left, so apply that rule to its exports value instead.",
3131
`${fn} = ${runtimeTemplate.basicFunction("exports", [
32-
"return exports !== null &&",
33-
Template.indent([
34-
'(typeof exports === "object" || typeof exports === "function")',
35-
"? exports",
36-
`: Object.create(${RuntimeGlobals.require}.prototype);`
37-
])
32+
`${runtimeTemplate.renderConst()} isObject =`,
33+
Template.indent(
34+
'exports !== null && (typeof exports === "object" || typeof exports === "function");'
35+
),
36+
`return isObject ? exports : Object.create(${RuntimeGlobals.require}.prototype);`
3837
])};`
3938
]);
4039
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"use strict";
22

3+
require("./counter").bump();
4+
35
exports.partial = 1;
46

57
throw new Error("boom");
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
"use strict";
2+
3+
let count = 0;
4+
5+
exports.bump = function bump() {
6+
count++;
7+
};
8+
9+
exports.runs = function runs() {
10+
return count;
11+
};

test/configCases/concatenate-modules/commonjs-wrapped-throwing-body/index.js renamed to test/configCases/concatenate-modules/commonjs-wrapped-throwing-body/error-handling.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// strictModuleErrorHandling caches the error and re-throws it on every later
22
// access instead of handing back the half-initialized exports
3+
import { runs } from "./counter";
34
import { get } from "./mid";
45

56
function attempt() {
@@ -14,3 +15,7 @@ it("should re-throw the cached error on every access to a failed member", () =>
1415
expect(attempt()).toEqual({ error: "boom" });
1516
expect(attempt()).toEqual({ error: "boom" });
1617
});
18+
19+
it("should not run a failed member body a second time", () => {
20+
expect(runs()).toBe(1);
21+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// strictModuleExceptionHandling drops the memo when the body throws, so the
2+
// next access runs it again instead of reusing the half-initialized exports
3+
import { runs } from "./counter";
4+
import { get } from "./mid";
5+
6+
function attempt() {
7+
try {
8+
return { ok: get() };
9+
} catch (err) {
10+
return { error: err.message };
11+
}
12+
}
13+
14+
it("should run a failed member body again on every access", () => {
15+
expect(attempt()).toEqual({ error: "boom" });
16+
expect(runs()).toBe(1);
17+
expect(attempt()).toEqual({ error: "boom" });
18+
expect(runs()).toBe(2);
19+
});
20+
21+
it("should keep a member that did not throw memoized", () => {
22+
// counter.js is required by every boom.js run but only evaluates once
23+
expect(runs()).toBe(2);
24+
});
Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,30 @@
11
"use strict";
22

3-
/** @type {import("../../../../").Configuration} */
4-
module.exports = {
3+
/** @typedef {import("../../../../").Configuration} Configuration */
4+
5+
/**
6+
* @param {string} entry entry
7+
* @param {Configuration["output"]} output output options under test
8+
* @returns {Configuration} configuration
9+
*/
10+
const config = (entry, output) => ({
11+
entry,
512
mode: "production",
613
devtool: false,
7-
output: {
8-
strictModuleErrorHandling: true
9-
},
14+
output,
1015
optimization: {
1116
concatenateModules: { commonjs: true },
1217
minimize: false,
1318
usedExports: true,
1419
moduleIds: "named",
1520
chunkIds: "named"
1621
}
17-
};
22+
});
23+
24+
/** @type {Configuration[]} */
25+
module.exports = [
26+
// the error is cached and re-thrown; the body never runs a second time
27+
config("./error-handling.js", { strictModuleErrorHandling: true }),
28+
// the memo is dropped, so the next access runs the body again
29+
config("./exception-handling.js", { strictModuleExceptionHandling: true })
30+
];

0 commit comments

Comments
 (0)