fix(javascript): bind defaulted and destructured Webpack factory roles (#7117)

* fix(javascript): bind defaulted and destructured Webpack factory roles

A Webpack factory whose module parameter was defaulted (`e = {}`) or
destructured (`{exports: x}`) reported an exact empty export list with
complete coverage, because roles were taken only from plain identifiers.

Bind factory roles once, by position, in javascriptBundlerFactoryRoles.
Defaulted module/exports parameters keep their role (the convention always
supplies the argument), `{exports: alias}` binds the alias to
module.exports, and a repeated sloppy parameter name binds its last
argument. Other role patterns (rest, array, nested or computed keys, a
non-identifier loader) receive no role and count as an unknown finding,
so the file's analysis is partial instead of claiming no exports. The
export collector, the factory require name and the standalone bootstrap
externals all use these parsed roles.

Fixes #7113

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(javascript): keep factory receivers through unordered reads

A defaulted role parameter kept the unused default in the binding facts
passed to write ordering, so a receiver read inside a loop, nested block
or closure was unresolved and its export silently dropped while the
module stayed complete.

The role owner now removes defaults the calling convention never runs
before ordering. Separately, an export-shaped write through a role
binding whose read stays unordered now counts as an unknown finding
instead of being dropped, so an incomplete list is never reported as
complete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(javascript): treat never-run factory parameter defaults as dead code

Removing unused defaults from binding facts let writes inside a default
expression reach the export collector: `(e = {}, t = (() => {
e.exports.ghost = 1; })())` reported `ghost` although Webpack supplies
both arguments. Loader calls in such defaults also produced require
references and async chunk keys.

The role owner now records the default of every role parameter, any
binding pattern included, as never run. The export collector, the
async-chunk walk and the static source traversal skip those subtrees,
so they yield no exports, references or chunk keys. Defaults of later,
non-role parameters still run and are still reported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822andClaude Opus 5.5 authored and GitHub committed 2026-10-25 05:23:23 -07:00
1 parent d32d9f2902
commit aa79f59478
10 files changed
+569 -119

No files matched your search

+100 -60
View File
@@ -10,6 +10,10 @@ import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
import {
withoutUnusedFactoryDefaults,
type JavaScriptBundlerFactoryRoles,
} from "./javascriptBundlerFactoryRoles.js";
import {
resolveSemanticBindingState,
type JavaScriptBindingIndex,
@@ -18,6 +22,8 @@ import {
/** Static CommonJS export names. */
export interface StaticExports {
readonly values: readonly string[];
/** Export-shaped writes whose receiver role could not be resolved. */
readonly unknown: number;
}
/** Derive a rename-resistant syntax fingerprint without code execution. */
@@ -32,18 +38,14 @@ export const fingerprintJavaScriptAst = (node: t.Node): string => {
return createHash("sha256").update(JSON.stringify(tokens)).digest("hex");
};
/** Calling-convention roles established by the bundler adapter. */
export interface JavaScriptFactoryExportBindings {
readonly exports: t.Identifier | undefined;
readonly module: t.Identifier | undefined;
readonly loader: t.Identifier | undefined;
}
/** Collect statically declared CommonJS/bundler export names from one factory. */
export const collectJavaScriptExports = (
node: t.Node,
factory?: {
readonly roles: JavaScriptFactoryExportBindings;
readonly roles: Pick<
JavaScriptBundlerFactoryRoles,
"module" | "exports" | "loader" | "unusedDefaults"
>;
readonly index: Pick<
JavaScriptBindingIndex,
"bindings" | "effectsForReferenceWithinActivationAt"
@@ -54,47 +56,61 @@ export const collectJavaScriptExports = (
const index = factory?.index;
const bindings = index?.bindings;
const exports = new Set<string>();
const bindingId = (
reference: t.Node | null | undefined,
): string | undefined =>
bindings !== undefined && t.isIdentifier(reference)
? resolveSemanticBindingState(bindings, reference, reference.name)
?.bindingId
: undefined;
let unknown = 0;
const bindingId = (reference: t.Identifier): string | undefined =>
bindings === undefined
? undefined
: resolveSemanticBindingState(bindings, reference, reference.name)
?.bindingId;
const identity = (
role: keyof JavaScriptFactoryExportBindings,
parameters: readonly (t.Identifier | undefined)[],
fallback: string,
) => {
const id = bindingId(roles?.[role]);
return (reference: t.Node | null): boolean => {
if (!t.isIdentifier(reference)) return false;
if (roles === undefined) return reference.name === fallback;
if (id === undefined || bindings === undefined) return false;
const ids = new Set(
parameters.flatMap((parameter) => {
const id = parameter === undefined ? undefined : bindingId(parameter);
return id === undefined ? [] : [id];
}),
);
return (reference: t.Node | null): ReceiverRole => {
if (!t.isIdentifier(reference)) return undefined;
if (roles === undefined)
return reference.name === fallback ? "role" : undefined;
if (bindings === undefined) return undefined;
const binding = resolveSemanticBindingState(
bindings,
reference,
reference.name,
);
if (binding?.bindingId !== id) return false;
if (binding === undefined || !ids.has(binding.bindingId))
return undefined;
// The calling convention owns the parameter's entry value, not every
// later value assigned to the same lexical binding.
const read = semanticBindingAtRead(
binding,
withoutUnusedFactoryDefaults(binding, roles),
reference,
bindings.parentsByNode,
);
return (
read.status === "ordered" &&
read.binding.initializers.length === 0 &&
if (read.status !== "ordered") return "unresolved";
return read.binding.initializers.length === 0 &&
read.binding.referenceInitializers.length === 0
);
? "role"
: undefined;
};
};
const isExportsAlias = identity("exports", "exports");
const isModuleAlias = identity("module", "module");
const isLoaderAlias = identity("loader", "__webpack_require__");
const receivers = { isExportsAlias, isModuleAlias };
const isExportsAlias = identity(roles?.exports ?? [], "exports");
const isModuleAlias = identity([roles?.module], "module");
const isLoaderAlias = identity([roles?.loader], "__webpack_require__");
const receivers: ExportReceivers = {
isExportsAlias,
isModuleAlias,
unresolved: () => {
unknown += 1;
},
};
traverseJavaScriptAst(node, {
// A default the calling convention never runs declares no exports.
skip: (current) => roles?.unusedDefaults.has(current) === true,
enter: (current) => {
if (t.isAssignmentExpression(current))
collectAssignmentExports(
@@ -111,31 +127,40 @@ export const collectJavaScriptExports = (
"defineProperty",
]);
collectCallExports(current, exports, receivers, intrinsic, (root) => {
if (root === null || !isLoaderAlias(root)) return false;
if (index === undefined) return true;
const loader = isLoaderAlias(root);
if (loader !== "role" || root === null) return loader;
if (index === undefined) return "role";
const facts = index.effectsForReferenceWithinActivationAt(
current,
root,
["d"],
);
return (
facts.memberEffectsIndexed &&
return facts.memberEffectsIndexed &&
!facts.effects.some(
(effect) =>
effect.kind === "member-write" && effect.timing !== "after",
)
);
? "role"
: undefined;
});
}
return undefined;
},
});
return { values: [...exports].sort(compareUnicodeCodePoints) };
return { values: [...exports].sort(compareUnicodeCodePoints), unknown };
};
/**
* `role` holds the parameter's entry value; `unresolved` reads its binding
* where write order is unknown, so the write may or may not be an export.
*/
type ReceiverRole = "role" | "unresolved" | undefined;
interface ExportReceivers {
readonly isExportsAlias: (root: t.Node | null) => boolean;
readonly isModuleAlias: (root: t.Node | null) => boolean;
readonly isExportsAlias: (root: t.Node | null) => ReceiverRole;
readonly isModuleAlias: (root: t.Node | null) => ReceiverRole;
/** Record an export-shaped write whose receiver could not be resolved. */
readonly unresolved: () => void;
}
const semanticTokens = (node: t.Node): string[] => {
@@ -204,19 +229,24 @@ const collectAssignmentExports = (
left: t.LVal | t.OptionalMemberExpression,
right: t.Expression,
output: Set<string>,
{ isExportsAlias, isModuleAlias }: ExportReceivers,
{ isExportsAlias, isModuleAlias, unresolved }: ExportReceivers,
): void => {
const path = memberPath(left);
if (path === null) return;
const root = memberRoot(left);
const exportsAlias = isExportsAlias(root);
// Rebinding the CommonJS alias does not replace module.exports.
if (path.length === 1 && exportsAlias) return;
const exportOffset = exportsAlias
? 1
: isModuleAlias(root) && path[1] === "exports"
? 2
: null;
if (path.length === 1) return;
const exportsAlias = isExportsAlias(root);
const moduleAlias =
exportsAlias === undefined && path[1] === "exports"
? isModuleAlias(root)
: undefined;
if (exportsAlias === "unresolved" || moduleAlias === "unresolved") {
unresolved();
return;
}
const exportOffset =
exportsAlias === "role" ? 1 : moduleAlias === "role" ? 2 : null;
if (exportOffset === null) return;
if (path.length === exportOffset) {
if (t.isObjectExpression(right)) collectObjectKeys(right, output);
@@ -232,27 +262,37 @@ const collectAssignmentExports = (
const collectCallExports = (
call: t.CallExpression,
output: Set<string>,
{ isExportsAlias, isModuleAlias }: ExportReceivers,
{ isExportsAlias, isModuleAlias, unresolved }: ExportReceivers,
intrinsic: boolean,
isLoaderAlias: (root: t.Node | null) => boolean,
isLoaderAlias: (root: t.Node | null) => ReceiverRole,
): void => {
const callee = memberPath(call.callee);
if (callee === null) return;
const definePropertyCall = intrinsic;
const declarationCall =
callee.length === 2 &&
callee[1] === "d" &&
isLoaderAlias(memberRoot(call.callee));
if (!definePropertyCall && !declarationCall) return;
!definePropertyCall && callee.length === 2 && callee[1] === "d"
? isLoaderAlias(memberRoot(call.callee))
: undefined;
if (!definePropertyCall && declarationCall === undefined) return;
const targetNode = call.arguments[0];
const target = memberPath(targetNode);
const exportTarget =
isExportsAlias(targetNode ?? null) ||
(target !== null &&
target.length === 2 &&
isModuleAlias(memberRoot(targetNode)) &&
target[1] === "exports");
if (!exportTarget) return;
const exportsAlias = isExportsAlias(targetNode ?? null);
const moduleAlias =
exportsAlias === undefined &&
target !== null &&
target.length === 2 &&
target[1] === "exports"
? isModuleAlias(memberRoot(targetNode))
: undefined;
if (exportsAlias === undefined && moduleAlias === undefined) return;
if (
exportsAlias === "unresolved" ||
moduleAlias === "unresolved" ||
declarationCall === "unresolved"
) {
unresolved();
return;
}
if (definePropertyCall) {
const name = stringValue(call.arguments[1]);
if (name !== undefined) addExport(output, name);