Skip to content

Commit b999d26

Browse files
refactor(types): type serializer contexts, runtime module queue and validated values (#23059)
* refactor(types): type serializer contexts, runtime module queue and cache tokens Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh * refactor(types): type the exhausted entry in ConcatenatedModule's switch Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh * refactor(types): name the value schema-utils validates Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh * refactor(types): type the minifiers' input source map Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh * chore: add changeset for serializer context types Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh * fix: create queued runtime modules in queue order once all have loaded Each pending runtime module's load resolves to what creates it, so the creators run as they did before: in queue order, after every load, each right before its module is attached. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh * refactor(types): infer the exports-keys map in SideEffectsFlagPlugin Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 5767d94 commit b999d26

20 files changed

Lines changed: 77 additions & 49 deletions
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+
Type the serializer contexts and the minifiers' input source maps.

‎lib/Compilation.js‎

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,10 @@ const unsafeCacheDependencies = new WeakMap();
665665
/** @type {WeakMap<ModuleWithRestoreFromUnsafeCache, UnsafeCacheData>} */
666666
const unsafeCacheData = new WeakMap();
667667

668-
/** @typedef {EXPECTED_OBJECT} DependencyReportCacheToken */
668+
/**
669+
* Stands for one round of dependency reporting, and is compared by identity only.
670+
*/
671+
class DependencyReportCacheToken {}
669672

670673
/**
671674
* Renewed when the module or a transitively referenced module is rebuilt.
@@ -725,9 +728,9 @@ const moduleRuntimeRequirementsKey = (runtime) =>
725728
*/
726729
const moduleHashKey = (runtime) => `moduleHash-${getRuntimeKey(runtime)}`;
727730
/**
728-
* A queued lazy runtime module; `create` takes exactly what its own `load`
729-
* resolves, which differs per entry.
730-
* @typedef {{ chunk: Chunk, load: () => Promise<EXPECTED_OBJECT>, create: (loaded: never) => RuntimeModule, chunkGraph: ChunkGraph }} PendingRuntimeModule
731+
* A queued lazy runtime module: `load` resolves to what creates it, which runs
732+
* in queue order once every load has finished.
733+
* @typedef {{ chunk: Chunk, load: () => Promise<() => RuntimeModule>, chunkGraph: ChunkGraph }} PendingRuntimeModule
731734
*/
732735

733736
class Compilation {
@@ -3477,8 +3480,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
34773480
* @returns {void}
34783481
*/
34793482
_flagModulesForDependencyReporting(modules) {
3480-
/** @type {DependencyReportCacheToken} */
3481-
const token = {};
3483+
const token = new DependencyReportCacheToken();
34823484
const { moduleGraph, builtModules } = this;
34833485
/** @type {Set<Module>} */
34843486
const updatedModules = new Set();
@@ -4887,7 +4889,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
48874889
* is over. `runtimeRequirementInTree` is a sync hook, so a tap cannot await
48884890
* the load itself; anything the tap reads off the requirement set must be
48894891
* captured before queueing, since `create` runs later.
4890-
* @template {object} T
4892+
* @template T
48914893
* @param {Chunk} chunk target chunk
48924894
* @param {() => Promise<T>} load resolves the runtime module implementation
48934895
* @param {(loaded: T) => RuntimeModule} create builds the runtime module from it
@@ -4898,7 +4900,11 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
48984900
if (this._pendingRuntimeModules === undefined) {
48994901
this._pendingRuntimeModules = [];
49004902
}
4901-
this._pendingRuntimeModules.push({ chunk, load, create, chunkGraph });
4903+
this._pendingRuntimeModules.push({
4904+
chunk,
4905+
load: () => load().then((loaded) => () => create(loaded)),
4906+
chunkGraph
4907+
});
49024908
}
49034909

49044910
/**
@@ -4912,14 +4918,10 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
49124918
if (pending === undefined) return callback(null);
49134919
this._pendingRuntimeModules = undefined;
49144920
Promise.all(pending.map(({ load }) => load()))
4915-
.then((loaded) => {
4921+
.then((creates) => {
49164922
for (let i = 0; i < pending.length; i++) {
4917-
const { chunk, create, chunkGraph } = pending[i];
4918-
this.addRuntimeModule(
4919-
chunk,
4920-
create(/** @type {never} */ (loaded[i])),
4921-
chunkGraph
4922-
);
4923+
const { chunk, chunkGraph } = pending[i];
4924+
this.addRuntimeModule(chunk, creates[i](), chunkGraph);
49234925
}
49244926
})
49254927
// a `runtimeModule` tap may have queued more

‎lib/Compiler.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ const getConcurrentCompilationError = memoize(() =>
8888
* } from "./fs/fs"
8989
*/
9090
/** @import { Schema, ValidationErrorConfiguration } from "schema-utils" */
91-
/** @import { PrecompiledCheck } from "./util/validateSchema" */
91+
/** @import { PrecompiledCheck, ValidatedValue } from "./util/validateSchema" */
9292

9393
/**
9494
* Defines the compilation params type used by this module.
@@ -1717,7 +1717,7 @@ ${other}`);
17171717

17181718
/**
17191719
* Validates a value against a schema, skipping the schema when the precompiled check passes
1720-
* @template {object | object[]} T
1720+
* @template {ValidatedValue} T
17211721
* @param {Schema | (() => Schema)} schema schema, or a function returning it so a valid value never reads it
17221722
* @param {T} value value
17231723
* @param {(ValidationErrorConfiguration | PrecompiledCheck<T>)=} options name and data path of the errors, read from a schema titled `"<name> <baseDataPath>"` when not given; the check can take its place

‎lib/css/cssMinify.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
* Minifies source a stylesheet embeds; may answer asynchronously.
1818
* @typedef {(source: string, info: { type: string, hostType: string }) => Promise<string | EmbeddedSourceResult | undefined> | string | EmbeddedSourceResult | undefined} AsyncEmbeddedSourceRenderer
1919
*/
20+
/** @import { RawSourceMap } from "webpack-sources" */
2021
/** @import { SourceMap } from "../util/SourceProcessor" */
2122
/** @import { DeferredEmbeddedSource } from "../util/dataURL" */
2223
/** @typedef {import("../util/extractComments").PluginExtractComments} ExtractCommentsOption */
@@ -35,7 +36,7 @@
3536
* worker pool as source (a top-level import wouldn't survive), and `require("webpack")`
3637
* re-resolves in the worker — via the installed package, or the dev self-link.
3738
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
38-
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
39+
* @param {Partial<RawSourceMap>=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
3940
* @param {{ as?: "stylesheet" | "block-contents", environment?: CssEnvironment, charset?: "auto" | false, convertLengthUnits?: boolean, convertApproximateColors?: boolean, dropOverriddenDeclarations?: boolean, extractComments?: MinimizeExtractComments, mergeDistantRules?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string }, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer, svg?: boolean } & CssTransformOptions=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`, and the per-transform switches). `renderEmbeddedSource` minifies source this stylesheet embeds, and may be asynchronous: one parse serves both it and the output; `svg` minifies an SVG `data:` URL it declines as the `.svg` assets are. Its `extractComments` decides which comments move into a separate file, over the plugin's
4041
* @param {ExtractCommentsOption=} extractComments the plugin's `extractComments`, read where `minimize.css.extractComments` is not set
4142
* @returns {Promise<{ code: string, map?: SourceMap, extractedComments?: string[], warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified CSS, its input->output source map (one anchor for the whole of a `block-contents` print, which is emitted as one piece), the comments taken out of it, and what a renderer reported over what this embeds

‎lib/hmr/JavascriptHotModuleReplacement.runtime.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ var $moduleCache$;
8989
var $moduleFactories$;
9090
/** @type {Record<string, EnsureChunkHandler>} */
9191
var $ensureChunkHandlers$;
92-
/** @type {(obj: object, key: ModuleId) => boolean} */
92+
/** @type {<T>(obj: Record<ModuleId, T>, key: ModuleId) => boolean} */
9393
var $hasOwnProperty$;
9494
/** @type {Record<ModuleId, HotData>} */
9595
var $hmrModuleData$;

‎lib/javascript/jsMinify.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"use strict";
77

88
/** @typedef {import("./syntax-printer").MinifyOptions} MinifyOptions */
9+
/** @import { RawSourceMap } from "webpack-sources" */
910
/** @typedef {import("../util/SourceProcessor").SourceMap} SourceMap */
1011

1112
/** @typedef {import("./syntax-parser").JavascriptSourceType} JavascriptSourceType */
@@ -30,7 +31,7 @@
3031
* `minimizer-webpack-plugin` ships this function to its worker pool as source,
3132
* where this module's own scope is gone.
3233
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
33-
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
34+
* @param {Partial<RawSourceMap>=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
3435
* @param {(MinifyOptions & { as?: JavascriptSourceType })=} minimizerOptions `optimization.minimize.javascript`; `as` names the production the source is written in, which is the source's own rather than the configuration's
3536
* @param {ExtractCommentsOption=} extractComments which comments to move into a separate file
3637
* @returns {Promise<{ code: string, map?: SourceMap, extractedComments?: string[] }>} the minified code, its input->output source map, and the comments taken out of it

‎lib/javascript/syntax-printer.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,12 @@ const {
220220

221221
/**
222222
* terser's `DefaultsError`, what `defaults` throws for an option it does not know.
223+
* @template {object} T
223224
*/
224225
class DefaultsError extends Error {
225226
/**
226227
* @param {string} message what went wrong
227-
* @param {object} defs the options known
228+
* @param {T} defs the options known
228229
*/
229230
constructor(message, defs) {
230231
super();
@@ -235,7 +236,8 @@ class DefaultsError extends Error {
235236
}
236237

237238
/**
238-
* @param {EXPECTED_OBJECT} object an object
239+
* @template {object} O
240+
* @param {O} object an object
239241
* @param {PropertyKey} property a key
240242
* @returns {boolean} whether the object has it as its own
241243
*/

‎lib/module/NormalModule.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ const DEPRECATED_PARSER_STATE_ALIASES = {
236236

237237
/** @typedef {Parameters<Resolver["resolve"]>[4]} ResolveCallback */
238238
/** @typedef {Parameters<typeof import("schema-utils").validate>[0]} Schema */
239-
/** @import { PrecompiledCheck } from "../util/validateSchema" */
239+
/** @import { PrecompiledCheck, ValidatedValue } from "../util/validateSchema" */
240240
/** @import { ValidationErrorConfiguration } from "schema-utils" */
241241

242242
/**
@@ -1217,7 +1217,7 @@ class NormalModule extends Module {
12171217
if (schema && compilation.options.validate) {
12181218
getValidateSchema()(
12191219
schema,
1220-
/** @type {T} */ (options),
1220+
/** @type {T & ValidatedValue} */ (options),
12211221
configuration,
12221222
check,
12231223
{

‎lib/optimize/ConcatenatedModule.js‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3041,8 +3041,12 @@ ${defineGetters}`
30413041
break;
30423042
}
30433043
default:
3044-
// @ts-expect-error never is expected here
3045-
throw new Error(`Unsupported concatenation entry type ${info.type}`);
3044+
// Every entry type is handled above, so `info` is `never` here.
3045+
throw new Error(
3046+
`Unsupported concatenation entry type ${
3047+
/** @type {{ type: string }} */ (info).type
3048+
}`
3049+
);
30463050
}
30473051
// Building a wrapped module's interop object here would evaluate its body
30483052
// at the top level and break require() cycles, so it is deferred behind a

‎lib/optimize/SideEffectsFlagPlugin.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,11 @@ const KEY_FIXED = 16;
186186
* @param {number} flags the `KEY_*` flags of this write or definition
187187
*/
188188
const recordKey = (writes, key, flags) => {
189-
const keys = writes.keys || (writes.keys = new Map());
189+
let { keys } = writes;
190+
if (keys === undefined) {
191+
keys = new Map();
192+
writes.keys = keys;
193+
}
190194
const previous = keys.get(key) || 0;
191195
let next = previous | flags;
192196
if (previous & flags & KEY_DEFINED) next |= KEY_REDEFINED;

0 commit comments

Comments
 (0)