GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — perf(SourceMapDevToolPlugin): emit .map asset as Buffer to reduce V8 heap by alexander-akait · Pull Request #20963 · webpack/webpack

perf(SourceMapDevToolPlugin): emit .map asset as Buffer to reduce V8 heap #20963

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
alexander-akait merged 6 commits into main from claude/fix-issue-20961-PaNv3
May 22, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

perf(SourceMapDevToolPlugin): emit .map asset as Buffer to reduce V8 heap #20963

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
6 commits
Select commit Hold shift + click to select a range
fee309a
perf(SourceMapDevToolPlugin): emit .map asset as Buffer to reduce V8 …
alexander-akait May 22, 2026
a7327f4
perf(SourceMapDevToolPlugin): release CachedSource map caches via cle…
alexander-akait May 22, 2026
1b0e58b
perf(cache): release LazyHashedEtag's captured object after hash is m…
alexander-akait May 22, 2026
278696d
fix(SourceMapDevToolPlugin): feature-detect clearCache, clarify Buffe…
alexander-akait May 22, 2026
d1f49e3
fix(SourceMapDevToolPlugin): clear cache on the Source that owns it; …
alexander-akait May 22, 2026
7eff261
fix(SourceMapDevToolPlugin): precompute base64 once for inline data-URL
alexander-akait May 22, 2026
File filter
Filter by extension


Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

5 changes: 5 additions & 0 deletions 5 .changeset/source-map-dev-tool-memory.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"webpack": patch
---

Reduce peak memory of `SourceMapDevToolPlugin` on large builds (closes #20961).
127 changes: 102 additions & 25 deletions 127 lib/SourceMapDevToolPlugin.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ const { makePathsAbsolute } = require("./util/identifier");
/**
* Defines the source map task type used by this module.
* @typedef {object} SourceMapTask
* @property {Source} asset
* @property {AssetInfo} assetInfo
* @property {(string | Module)[]} modules
* @property {string} source
* @property {string} file
* @property {RawSourceMap} sourceMap
* @property {Source} mapSource the Source instance whose `sourceAndMap` we called (the current asset or, when its map was already stripped, the pinned original from `originalSources`) — what `clearCache` should target
* @property {ItemCacheFacade} cacheItem cache item
*/

Expand Down Expand Up @@ -111,12 +111,14 @@ const getOriginalSourceRegistry = (compilation) => {
* The returned source is read from the asset as it currently stands — that way
* any `sourceMappingURL` comments appended by earlier plugin instances survive
* — while the map is taken from the pinned original Source when the current
* one no longer carries it.
* one no longer carries it. `mapSource` identifies which Source instance was
* actually queried for the map (the current asset, or the pinned original);
* that's the one whose internal caches the caller should release.
* @param {string} file file name
* @param {Source} asset source object as currently held by the compilation
* @param {MapOptions} options map extraction options
* @param {Map<string, Source>} registry compilation-scoped original-source registry
* @returns {{ source: string, sourceMap: RawSourceMap } | undefined} extracted pair or `undefined` when no map is recoverable
* @returns {{ source: string, sourceMap: RawSourceMap, mapSource: Source } | undefined} extracted pair or `undefined` when no map is recoverable
*/
const extractSourceAndMap = (file, asset, options, registry) => {
/** @type {string | Buffer} */
Expand All @@ -139,20 +141,20 @@ const extractSourceAndMap = (file, asset, options, registry) => {
// that a later plugin instance (which will see a rewrapped asset
// without a map) can recover it on demand.
if (!registry.has(file)) registry.set(file, asset);
} else {
// The current asset (typically a `RawSource` left by an earlier
// SourceMapDevToolPlugin instance) has no internal map. Re-extract
// the map from the original Source we pinned earlier. We keep using
// `source` from the current asset so that any prior wrappers (e.g.
// appended sourceMappingURL comments) are preserved.
const original = registry.get(file);
if (!original) return;
sourceMap = original.sourceAndMap
? original.sourceAndMap(options).map
: original.map(options);
if (!sourceMap) return;
return { source, sourceMap, mapSource: asset };
}
return { source, sourceMap };
// The current asset (typically a `RawSource` left by an earlier
// SourceMapDevToolPlugin instance) has no internal map. Re-extract
// the map from the original Source we pinned earlier. We keep using
// `source` from the current asset so that any prior wrappers (e.g.
// appended sourceMappingURL comments) are preserved.
const original = registry.get(file);
if (!original) return;
sourceMap = original.sourceAndMap
? original.sourceAndMap(options).map
: original.map(options);
if (!sourceMap) return;
return { source, sourceMap, mapSource: original };
};

/**
Expand All @@ -177,7 +179,7 @@ const getTaskForFile = (
) => {
const extracted = extractSourceAndMap(file, asset, options, registry);
if (!extracted) return;
const { source, sourceMap } = extracted;
const { source, sourceMap, mapSource } = extracted;
const context = compilation.options.context;
const root = compilation.compiler.root;
const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root);
Expand All @@ -190,10 +192,10 @@ const getTaskForFile = (

return {
file,
asset,
source: /** @type {string} */ (source),
assetInfo,
sourceMap,
mapSource,
modules,
cacheItem
};
Expand Down Expand Up @@ -360,6 +362,25 @@ class SourceMapDevToolPlugin {
const tasks = [];
let fileIndex = 0;

// Shared deduplication set for `Source#clearCache` calls below.
// Webpack chunks routinely share module-level `CachedSource`
// instances. A per-call WeakSet would re-walk those shared
// subtrees once per chunk — 50 chunks × thousands of shared
// modules in dev/non-minified setups — and worse, every
// chunk's `sourceAndMap` would have to recompute the cleared
// caches, churning allocations (measured: +700 MB peak RSS,
// +6 s wall time on a 50×1000 synthetic build).
//
// Sharing one set lets each shared subtree be walked exactly
// once. The trade-off is that subsequent chunks' `sourceAndMap`
// calls can repopulate a shared module's `_cachedMaps` after
// its own clear was skipped (because the module is already in
// the visited set), leaving at most one populated cache entry
// per shared module at the end of the run — bounded to a few
// MB even at the scale of #20961. That's strictly preferable
// to the alternative's hundreds of MB of transient peak RSS.
const clearCacheVisited = new WeakSet();

asyncLib.each(
files,
(file, callback) => {
Expand Down Expand Up @@ -458,6 +479,44 @@ class SourceMapDevToolPlugin {
originalSources
);

// Release the per-instance caches that `sourceAndMap`
// just populated. The composed map (and, for
// `SourceMapSource`, the parsed `_sourceMapAsObject` /
// `_innerSourceMapAsObject`) otherwise sit on the
// CachedSource — and every shared child — until phase
// 2 replaces the asset, which is what causes the OOM
// spike on builds with thousands of chunks
// (webpack#20961). Keep `source` since downstream
// consumers reading the original asset still need it;
// `hash`/`size` default to retained because they're
// cheap to keep but expensive to rebuild.
// `clearCacheVisited` is shared across every call (see
// its declaration above for the rationale).
//
// Target `task.mapSource` (not `asset.source`): when
// `extractSourceAndMap` falls back to the pinned
// original (the current asset is a `RawSource` left
// by an earlier plugin instance), the `sourceAndMap`
// call populated the original's caches, not the
// current asset's.
//
// Feature-detected: `clearCache` landed in
// `webpack-sources` 3.5, but `compilation.assets` may
// hold `Source`-like instances from a third-party
// plugin built against an older copy of
// `webpack-sources` (or a hand-rolled implementation).
// Calling it unconditionally would throw on those.
if (task && typeof task.mapSource.clearCache === "function") {
task.mapSource.clearCache(
{
maps: true,
source: false,
parsedMap: true
},
clearCacheVisited
);
}

if (task) {
const modules = task.modules;

Expand Down Expand Up @@ -698,12 +757,23 @@ class SourceMapDevToolPlugin {
outputSourceMap.debugId = debugIdValue;
}

const sourceMapString = JSON.stringify(outputSourceMap);
if (sourceMapFilename) {
// External `.map` file: hold the serialized map as a
// `Buffer` instead of a V8 string. `RawSource` accepts
// a buffer directly, and the emitted asset stays in
// `compilation.assets` until the build finishes — so
// storing the bytes off the V8 heap (where Buffers
// live, accounted as `external` memory) avoids keeping
// a large V8 string alive for the rest of the build
// and reduces heap pressure on `--max-old-space-size`.
const sourceMapBuffer = Buffer.from(
JSON.stringify(outputSourceMap),
"utf8"
);
Comment thread
Comment on lines +761 to +772

@alexander-akait alexander-akait May 22, 2026

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Reworded in 278696d — same point as #discussion_r3287251359, addressed there.


Generated by Claude Code

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
const filename = file;
const sourceMapContentHash = usesContentHash
? createHash(compilation.outputOptions.hashFunction)
.update(sourceMapString)
.update(sourceMapBuffer)
.digest("hex")
: undefined;

Expand Down Expand Up @@ -775,7 +845,7 @@ class SourceMapDevToolPlugin {
assetsInfo[file] = assetInfo;
compilation.updateAsset(file, asset, assetInfo);
// Add source map file to compilation assets and chunk files
const sourceMapAsset = new RawSource(sourceMapString);
const sourceMapAsset = new RawSource(sourceMapBuffer);
const sourceMapAssetInfo = {
...sourceMapInfo,
development: true
Expand All @@ -801,6 +871,16 @@ class SourceMapDevToolPlugin {
`${PLUGIN_NAME}: append can't be a function when no filename is provided`
);
}
// Inline data-URL form: `[map]` gets the raw JSON, `[url]`
// gets the same JSON base64-encoded. `URL_COMMENT_REGEXP`
// is a `/g` regex, so a user `append` template with more
// than one `[url]` placeholder would otherwise re-encode
// the same JSON per match. Pre-compute both once.
const sourceMapString = JSON.stringify(outputSourceMap);
const sourceMapBase64 = Buffer.from(
sourceMapString,
"utf8"
).toString("base64");
/**
* Add source map as data url to asset
*/
Expand All @@ -811,10 +891,7 @@ class SourceMapDevToolPlugin {
.replace(
URL_COMMENT_REGEXP,
() =>
`data:application/json;charset=utf-8;base64,${Buffer.from(
sourceMapString,
"utf8"
).toString("base64")}`
`data:application/json;charset=utf-8;base64,${sourceMapBase64}`
)
);
assets[file] = asset;
Expand Down
11 changes: 9 additions & 2 deletions 11 lib/cache/getLazyHashedEtag.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class LazyHashedEtag {
* @param {HashFunction} hashFunction the hash function to use
*/
constructor(obj, hashFunction = DEFAULTS.HASH_FUNCTION) {
/** @type {HashableObject} */
/** @type {HashableObject | undefined} */
this._obj = obj;
/** @type {undefined | string} */
this._hash = undefined;
Expand All @@ -40,8 +40,15 @@ class LazyHashedEtag {
toString() {
if (this._hash === undefined) {
const hash = createHash(this._hashFunction);
this._obj.updateHash(hash);
/** @type {HashableObject} */
(this._obj).updateHash(hash);
this._hash = hash.digest("base64");
// Drop the captured object once the hash is memoized. The hash is
// never reset, so we never need `_obj` again — and many callers
// (e.g. `SourceMapDevToolPlugin`, `RealContentHashPlugin`) capture
// a heavy `CachedSource` here that would otherwise stay reachable
// through this etag for the lifetime of the compilation cache.
this._obj = undefined;
}
return this._hash;
}
Expand Down
2 changes: 1 addition & 1 deletion 2 package.json
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
"tapable": "^2.3.0",
"terser-webpack-plugin": "^5.5.0",
"watchpack": "^2.5.1",
"webpack-sources": "^3.4.1"
"webpack-sources": "^3.5.0"
},
"devDependencies": {
"@babel/core": "^7.27.1",
Expand Down
34 changes: 34 additions & 0 deletions 34 types.d.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2886,6 +2886,22 @@ declare interface CleanPluginCompilationHooks {
*/
keep: SyncBailHook<[string], boolean | void>;
}
declare interface ClearCacheOptions {
/**
* drop cached source maps (default `true`)
*/
maps?: boolean;

/**
* drop cached source/buffer copies (default `true`)
*/
source?: boolean;

/**
* drop the parsed object form of cached source maps on `SourceMapSource` instances (default `false` — re-parsing JSON is significantly more expensive than `toString`). Only takes effect when a serialized form (buffer or string) is also retained, so the data remains recoverable.
*/
parsedMap?: boolean;
}
declare interface CodeGenMapOverloads {
get: <K extends string>(key: K) => undefined | CodeGenValue<K>;
set: <K extends string>(
Expand Down Expand Up @@ -22470,6 +22486,19 @@ declare class Source {
map(options?: MapOptions): null | RawSourceMap;
sourceAndMap(options?: MapOptions): SourceAndMap;
updateHash(hash: HashLike): void;

/**
* Release cached data held by this source. clearCache is a memory
* hint: it never affects correctness or output, only how expensive
* the next read is. Subclasses override; the base is a no-op so
* every Source supports the call. Composite sources always recurse
* into wrapped sources. When the same child is reachable via several
* parents (e.g. modules shared across webpack chunks), pass a shared
* `visited` WeakSet so each subtree is walked at most once.
* Not safe to call concurrently with source/map/sourceAndMap/
* streamChunks/updateHash on the same instance.
*/
clearCache(options?: ClearCacheOptions, visited?: WeakSet<Source>): void;
}
declare interface SourceAndMap {
/**
Expand Down Expand Up @@ -22517,6 +22546,11 @@ declare interface SourceLike {
* hash updater
*/
updateHash?: (hash: HashLike) => void;

/**
* clear cache
*/
clearCache?: (options?: ClearCacheOptions, visited?: WeakSet<Source>) => void;
}
declare class SourceMapDevToolPlugin {
/**
Expand Down
8 changes: 4 additions & 4 deletions 8 yarn.lock
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -9527,10 +9527,10 @@ webpack-merge@^6.0.1:
flat "^5.0.2"
wildcard "^2.0.1"

webpack-sources@^3.4.1:
version "3.4.1"
resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.4.1.tgz#009d110999ebd9fb3a6fa8d32eec6f84d940e65d"
integrity sha512-eACpxRN02yaawnt+uUNIF7Qje6A9zArxBbcAJjK1PK3S9Ycg5jIuJ8pW4q8EMnwNZCEGltcjkRx1QzOxOkKD8A==
webpack-sources@^3.5.0:
version "3.5.0"
resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.5.0.tgz#87bf7f5801a4e985b1f1c92b64b9620a02f76d08"
integrity sha512-HPuy+uuoTCaaoEoI1LQ3JN9+vrPBvEesnnX1jADHy728cHSMlq4wUc4afYqahq2B1mhQVZxCXOkNTnXltr+2vQ==

whatwg-url@^5.0.0:
version "5.0.0"
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.