Skip to content

feat(lexer): detect Webpack entry exports in extended mode - #139

Draft
BridgeAR wants to merge 5 commits into
mainfrom
BridgeAR/2026-10-27-webpack-exports
Draft

BridgeAR wants to merge 5 commits into
mainfrom
BridgeAR/2026-10-27-webpack-exports

Conversation

@BridgeAR

Copy link
Copy Markdown
Member

Scanning every factory in a Webpack bundle reports internal names alongside the published entry's exports. Extended mode now follows recognized Webpack startup and reexport patterns to exclude unrelated factory exports.

Refs: #88

@guybedford guybedford left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, it's a really nice piece of work. Following the startup expression to the entry factory, and falling back to full candidate detection whenever the shape isn't recognised, is the right structure for extended mode. The test against the published jest-watcher bundle is a great anchor. It's also good to see the JS and C implementations kept in step, and the committed Wasm rebuilds byte-for-byte from source with the local toolchain.

I tested the branch against real webpack 5.112 output and benchmarked it against main. The inline comments have the details. There are three main themes:

  1. Unrecognised re-exports drop names silently. Only the re-export forms the lexer recognises are followed. Other ways of re-exporting an internal module, such as TypeScript's __exportStar or Object.assign(exports, ...), currently drop names without triggering the fallback. Anything that can't be accounted for should fall back, so that extended mode still reports at least what main does.
  2. Current webpack output shapes. Webpack emits method-shorthand factories ("id"(module, exports, __webpack_require__) {) for target: 'node', and these always hit the fallback today. There is also an array form of __webpack_require__.d.
  3. Perf. A one-line prefilter recovers most of the extended-mode overhead on non-webpack code.

Benchmarks use the Wasm build, the median of 60 interleaved runs per file in test/samples, on x86_64:

default vs main extended vs main
this PR +1–5% +13–42%
with the prefilter suggested inline +1–5% +4–12%

Comment thread src/lexer.c Outdated
continue;

if (openTokenDepth == 0) {
if (extendedMode && keywordStart(pos) && readWebpackToken(ch))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In extended mode, this runs keywordStart and readWebpackToken for every non-whitespace token, including punctuators and every identifier, even in sources with no webpack markers. Every branch of readWebpackToken either needs a current factory binding or starts with _, so that check can go first:

if (extendedMode && (ch == '_' || webpackCurrent) && keywordStart(pos) && readWebpackToken(ch))

The same applies to lexer.js with (ch === 95 || webpack?.current). On test/samples, this brings extended mode from +13–42% down to +4–12% vs main, and the suite still passes. Inside a factory, the webpackCurrent branch could be narrowed further to tokens whose first character matches the first character of the target or module binding.

Comment thread src/lexer.c Outdated
if (!str_eq18(pos + 1, '_', 'w', 'e', 'b', 'p', 'a', 'c', 'k', '_', 'r', 'e', 'q', 'u', 'i', 'r', 'e', '_', '_') ||
isIdentifierChar(webpackCharAt(pos + 19))) return false;
if ((webpackCurrent ? openTokenDepth == webpackCurrent->depth : webpackInline) &&
readWebpackCall(&starExportBinding_.specifier_start, &starExportBinding_.specifier_end)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A __webpack_require__(id) call becomes a dependency only in two cases: it is at the factory's own depth and then consumed by the Object.keys(...).forEach star pattern, or it is assigned directly to module.exports. Any other way of re-exporting an internal module drops that module's names, and the result is not marked invalid. For example, with a literal entry:

"./entry.js": (function (module, exports, __webpack_require__) {
  exports.own = 1;
  __exportStar(__webpack_require__("./dep.js"), exports); // TypeScript `export *`
}),
entry body runtime main (extended) this PR
__exportStar(__webpack_require__("./dep.js"), exports) own, depA depA, own own
Object.assign(exports, __webpack_require__("./dep.js")) own, depA depA, own own
var d = __webpack_require__("./dep.js"); for (var k in d) exports[k] = d[k]; own, depA depA, own own
module.exports = { ...__webpack_require__("./dep.js") } depA depA, own own

The Object.assign case also appears in real webpack output, for a CJS entry that does Object.assign(exports, require('./dep')).

Excluding names is exactly what this feature adds, so it seems safest to fall back to candidate detection whenever a reachable factory's exports binding escapes in a form the lexer doesn't recognise. That covers the binding being passed as a call argument, written through a computed member, or an internal __webpack_require__ being spread into the export object. The Babel star pattern in the jest-watcher fixture is recognised first, so it would still take the precise path.

Comment thread src/lexer.c
uint16_t* revert = pos;
const uint16_t *id, *idEnd, *module = NULL, *moduleEnd = NULL, *target = NULL, *targetEnd = NULL, *ignored, *ignoredEnd;
pos++;
bool found = readWebpackId(&id, &idEnd);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current webpack emits factories in method-shorthand form when the target supports it, which includes target: 'node' on webpack 5.112:

var __webpack_modules__ = ({
"./src/dep.js"
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  ...
},

The id here is expected to be followed by :, so every factory in such a bundle invalidates the table and detection falls back. I built bundles with target: 'node', library.type: 'commonjs2', in development mode and in production with minimize: false. None of them got the entry-only result. With output.environment.methodShorthand: false, the ESM entries did. Supporting id(params) { alongside id: (params) => { and id: function (params) { would cover the common Node case.

Comment thread src/lexer.c Outdated
pos++;
if (readExportsOrModuleDotExports(commentWhitespace()) && commentWhitespace() == ',') {
pos++;
if (commentWhitespace() == '{') exportObjectPos = pos;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Webpack 5.112 also emits an array form of the getter map in some production builds:

__webpack_require__.d(__webpack_exports__, [
  "own", 0, /* binding */ own
]);

Each entry is a key followed by either 0 and a value, or a getter. This form is skipped at the moment, so own is missed. It's fine as a follow-up, but a test would be good either way.

Comment thread src/lexer.c

// Note: parsing is based on the _assumption_ that the source is already valid
uint32_t parseCJSWithOptions (uint16_t* _source, uint32_t _sourceLen, void (*_addExport)(const uint16_t*, const uint16_t*), void (*_addReexport)(const uint16_t*, const uint16_t*), void (*_addUnsafeGetter)(const uint16_t*, const uint16_t*), void (*_clearReexports)(), uint32_t options) {
static __attribute__((always_inline)) uint32_t parseCJSMode (uint16_t* _source, uint32_t _sourceLen, void (*_addExport)(const uint16_t*, const uint16_t*), void (*_addReexport)(const uint16_t*, const uint16_t*), void (*_addUnsafeGetter)(const uint16_t*, const uint16_t*), void (*_clearReexports)(), uint32_t options, bool extendedMode) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked whether this specialisation is worth its size. Without it, using a single call with (options & 2) != 0, the Wasm is 36.5 KB instead of 40.1 KB, but default mode goes from +1–5% to +3–7% vs main. So it pays for itself 👍

Comment thread lexer.js Outdated
const revertPos = pos;
if (ch === 109/*m*/ && source.startsWith('odule', pos + 1)) {
pos += 6;
const target = extended && (webpack?.current?.target ?? '__webpack_exports__');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small JS/C mismatch: when the current factory has no exports parameter, target falls back to '__webpack_exports__' here. The C version only matches __webpack_exports__ outside a factory (!webpackCurrent). For example:

"e": ((m) => { __webpack_require__.d(__webpack_exports__, { x: () => 1 }); }),

With entry "e", this gives ['x'] from lexer.js and [] from the Wasm build.

Comment thread lexer.js Outdated
@@ -959,8 +1214,12 @@ function tryParseModuleExportsDotAssign () {
}

/** @param {boolean} assign */

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the old /** @param {boolean} assign */ is still here above the new JSDoc block.

Comment thread build/Makefile Outdated

optimize: lib/lexer.wasm
${WASM_OPT} -Oz lib/lexer.wasm -o lib/lexer.wasm
${WASM_OPT} -Oz --enable-bulk-memory --strip-debug lib/lexer.wasm -o lib/lexer.wasm

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new binary contains a memory.fill, presumably from the struct zero-initialisation; main's has none. I assume that's why --enable-bulk-memory is needed here. That's fine for Node >= 18, but it changes the Wasm feature set, so it's worth noting in the commit message. Is --strip-debug still needed, given --strip-all at link time?

Comment thread test/webpack.js
const options = { mode: 'extended' };

/** @param {string} modules */
function bundle (modules) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bundle() helper is a great way to cover edge cases. It would be good to add one or two fixtures generated by current webpack as well, for example target: 'node' in development mode and in production with minimize: false. These should include method-shorthand factories, harmony re-exports and a TS __exportStar entry, so that regressions against real output show up here.

@guybedford guybedford left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround. Everything from the previous round is addressed, and this now works well on real bundles. On the new head:

  • I ran extended mode over the 30 webpack-bundled jest@30 packages and compared with the runtime keys. All 30 match (ignoring __esModule), where main reports extra internal names for 27 of them.
  • The four unrecognised re-export cases from last time all fall back correctly now.
  • The Wasm rebuilds byte-for-byte, and the JS and Wasm builds give identical output on everything I ran (those bundles, my own webpack 5.112 builds, test/samples and the fixtures).
  • Perf, Wasm build, median of 60 interleaved runs per file in test/samples, x86_64:
default vs main extended vs main
previous head +1–5% +13–42%
this head up to +5% +3–9%

There is one gap left. The unsupported-use fallback is tracked for the exports and module bindings of table factories, but not for the root __webpack_exports__. That leaves two shapes emitted by webpack 5.112 that lose names without falling back. The details are inline.

Comment thread src/lexer.c Outdated
}
}
pos = start;
tryParseExportsDotAssign(false, 19);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The result of this call is ignored, so a use of the root __webpack_exports__ that isn't recognised never triggers the fallback. Webpack's direct-call startup hits this, which it emits when the entry can't be inlined and no module cache is needed:

(() => {
  var __webpack_modules__ = ({
    43(__unused_webpack_module, exports) {
      exports.helper = () => 1;
      exports.own = (0, exports.helper)();
    }
  });
  let __webpack_exports__ = {};
  __webpack_modules__[43](0, __webpack_exports__);
  module.exports = __webpack_exports__;
})();
runtime main (extended) this PR
helper, own helper, own none

__webpack_exports__ = {} followed by the publish is read as an inlined entry with no exports, so the precise path returns an empty list. This was there in the previous round too, but the method-shorthand fallback hid it.

It comes from real output. This TypeScript entry, compiled with tsc --module commonjs and bundled with webpack 5.112 using mode: 'production', minimize: false, target: 'node' and library.type: 'commonjs2', gives exactly that startup:

export const helper = () => 1;
export const own = helper();

The self-reference (0, exports.helper)() appears to be what stops webpack from inlining the entry.

I think the same rule as for factories applies here: if the root __webpack_exports__ is used in a form that isn't the declaration, a recognised write, or the final publish, fall back to candidate detection. Recognising __webpack_modules__[id](…, __webpack_exports__) as an entry call would keep the precise path for this shape, but that could be a follow-up. A production-mode TypeScript fixture next to the development one would cover it.

Comment thread src/lexer.c
uint16_t* argEnd = pos;
uint16_t next = commentWhitespace();
if (method == 'r' && next == ')') trustWebpackExports(argEnd);
if (method == 'd' && next == ',') {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the definition is neither an object nor an array literal, a table factory falls back, because the exports argument isn't trusted. At the root nothing is flagged. Webpack emits this for an export * whose target it can't analyse statically, inside an inlined entry:

let __webpack_exports__ = {};
(() => {
  __webpack_require__.d(__webpack_exports__, { mine: () => mine });
  var _barrel = __webpack_require__("./barrel.js");
  var __WEBPACK_REEXPORT_OBJECT__ = {};
  for (const key in _barrel) if (["mine", "default"].indexOf(key) < 0)
    __WEBPACK_REEXPORT_OBJECT__[key] = () => _barrel[key];
  __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__);
  const mine = 1;
})();
module.exports = __webpack_exports__;

With "./barrel.js" exporting depA:

runtime main (extended) this PR
mine, depA depA mine

I got this from an ESM entry doing export * from './barrel.js', where the barrel is tsc CommonJS output that itself uses __exportStar. It happens in both development and production mode. The same code inside a table factory falls back as expected, so this is the same root-level gap as the direct-call case. The spread and unrecognised-property checks in readExportProperty are also only applied when there is a current factory.

Comment thread src/lexer.c
uint16_t* start = pos;
if (webpackCurrent) {
if (matchesWebpackBinding(webpackCurrent->target, webpackCurrent->targetLength)) {
if (!tryParseExportsDotAssign(false, webpackCurrent->targetLength) && start >= webpackTrustedEnd)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not blocking: a plain member read of the binding also lands here. tsc rewrites every reference to an exported const as exports.name, for example exports.own = (0, exports.helper)();, so a reachable module that uses one of its own exports always falls back. With one more module in the bundle, a development build of the TypeScript entry from my other comment reports that module's internal names for this reason, where main is exact.

A read of exports.name or module.exports.name can't hand out the exports object itself, so it could be treated as benign. That would keep tsc-compiled bundles on the precise path.

Scanning every factory in a Webpack bundle reports internal names alongside the published entry's exports.
Extended mode now follows recognized Webpack startup and reexport patterns to exclude unrelated factory exports.

Refs: #88
Signed-off-by: Ruben Bridgewater <ruben.bridgewater@datadoghq.com>
1. Unknown uses of factory exports can hide internal reexports.
   Retain the full candidate set when a reachable factory has an
   unsupported export use. Preserve surrounding star bindings
   across factory scans.
2. Read shorthand factories and both getter map forms in Webpack
   5.112. Keep the delimiter after a literal require call so the
   scanner can close a factory without a trailing semicolon.
3. Skip Webpack keyword checks for unrelated tokens. Eight passes
   over test/samples in extended Wasm mode take 78.74 ms before and
   67.41 ms after on Node.js 22.23.4 (trimmed mean of seven trials).

The Wasm binary uses memory.fill and needs bulk memory. Enable the
feature explicitly for WABT versions that require the flag.

Drive-by fix:
* Remove the duplicate parameter annotation.

Signed-off-by: Ruben Bridgewater <ruben.bridgewater@datadoghq.com>
Most tokens inside a factory cannot refer to either factory parameter.
Check the first character before matching the entire identifier.

On Node 22.23.4 (V8 12.4, macOS arm64), parsing three Webpack fixtures
went from 625.36 ms to 495.60 ms in JS (4,500 passes) and from 518.14 ms
to 407.71 ms in Wasm (9,000 passes). These are trimmed means of seven
interleaved trials.

A recognized star loop without a known binding could hide the write
that would trigger fallback. Keep all candidates when the binding is
unknown. Use the latest recorded binding in both Webpack backends.
A direct factory call or a dynamic getter map can add names without a
recognized write to the startup exports binding. Retain factory candidates
instead of returning an incomplete export list.

A direct assignment can also make a recorded star reexport uncertain.
A closed call identifies the write without proving a new binding.

Signed-off-by: Ruben Bridgewater <ruben.bridgewater@datadoghq.com>
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-10-27-webpack-exports branch from 4ae5acd to 538a138 Compare November 23, 2026 14:10
The scanner checks the factory boundary even for tokens that are not Webpack declarations. Keeping the depth with the active parameter initials removes the factory object lookup from those checks.

Five Webpack bundles took a median of 28.8 us/parse before and 25.6 us/parse after in extended mode (Node 22.23.4, V8 12.4, macOS arm64, nine warmed trials). Default-only runs in separate processes stayed within 0.2% for tiny, small, and larger CommonJS files on this runtime.

Signed-off-by: Ruben Bridgewater <ruben.bridgewater@datadoghq.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants