Skip to content

Commit 7c83d25

Browse files
refactor(types): type memo cache keys, stats filters and hook instances
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HArJAXZagrHVVNLZZk9soh
1 parent 04947bc commit 7c83d25

10 files changed

Lines changed: 60 additions & 48 deletions

File tree

‎lib/Compiler.js‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,12 +178,13 @@ const getConcurrentCompilationError = memoize(() =>
178178

179179
/**
180180
* A module's memo cache: reads and writes under a `MemCacheKey<V>` are typed `V`, `provide` by what its function returns.
181-
* Plain keys stay untyped for plugins.
181+
* Plain keys stay untyped for plugins. `provide` reads the key's type from the key given, not from its function:
182+
* `[R][R extends R ? 0 : never]` is `R` where TypeScript does not infer `R`, as `NoInfer` does in TypeScript 5.4 and later.
182183
* @typedef {{
183184
* get<K extends TupleElement>(key: K, ...rest: TupleElement[]): MemCacheValue<K> | undefined,
184185
* set<K extends TupleElement>(key: K, ...restAndValue: [...TupleElement[], MemCacheValue<K>]): void,
185-
* provide<K extends TupleElement, V>(key: K, ...restAndCompute: [...TupleElement[], (...key: EXPECTED_ANY[]) => MemCacheProvided<K, V>]): MemCacheProvided<K, V>,
186-
* cachedProvide<This, V>(compute: (thisArg: This, ...key: EXPECTED_ANY[]) => V, thisArg: This, args: TupleElement[]): V,
186+
* provide<K extends TupleElement, V, R extends TupleElement[]>(key: K, ...restAndCompute: [...R, (key: K, ...rest: [R][R extends R ? 0 : never]) => MemCacheProvided<K, V>]): MemCacheProvided<K, V>,
187+
* cachedProvide<This, V, A extends TupleElement[]>(compute: (thisArg: This, ...key: [A][A extends A ? 0 : never]) => V, thisArg: This, args: A): V,
187188
* } & Omit<import("./util/WeakTupleMap")<TupleElement[], unknown>, "get" | "set" | "provide" | "cachedProvide">} MemCache
188189
*/
189190
/** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, lazyRequests: string | undefined, memCache: MemCache }} ModuleMemCachesItem */
@@ -1716,7 +1717,7 @@ ${other}`);
17161717

17171718
/**
17181719
* Validates a value against a schema, skipping the schema when the precompiled check passes
1719-
* @template {EXPECTED_OBJECT | EXPECTED_OBJECT[]} [T=EXPECTED_OBJECT]
1720+
* @template {object | object[]} T
17201721
* @param {Schema | (() => Schema)} schema schema, or a function returning it so a valid value never reads it
17211722
* @param {T} value value
17221723
* @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/debug/ProfilingPlugin.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ const { fileUrlToPath } = require("../util/identifier");
1818
/** @import { FullTap } from "tapable" */
1919
/** @import Compilation from "../Compilation" */
2020
/** @import Compiler from "../Compiler" */
21+
/** @import Generator from "../module/Generator" */
2122
/** @import NormalModuleFactory from "../module/NormalModuleFactory" */
23+
/** @import Parser from "../module/Parser" */
2224
/** @import ResolverFactory from "../resolve/ResolverFactory" */
2325
/** @import { IntermediateFileSystem } from "../fs/fs" */
2426

@@ -441,12 +443,12 @@ const interceptTaps = (hook, interceptor) => {
441443

442444
/**
443445
* Intercept all hooks for.
444-
* @param {EXPECTED_OBJECT & { hooks?: Hooks }} instance instance
446+
* @param {{ hooks?: Hooks } | Parser | Generator} instance instance, its hooks read where it has them
445447
* @param {Trace} tracer tracer
446448
* @param {string} logLabel log label
447449
*/
448450
const interceptAllHooksFor = (instance, tracer, logLabel) => {
449-
if (Reflect.has(instance, "hooks")) {
451+
if ("hooks" in instance) {
450452
const hooks = /** @type {Hooks} */ (instance.hooks);
451453
for (const hookName of Object.keys(hooks)) {
452454
const hook = hooks[hookName];

‎lib/graph/ModuleGraph.js‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const ModuleGraphConnection = require("./ModuleGraphConnection");
1515
const isDependencyKind = require("./isDependencyKind");
1616

1717
/** @import { ModuleMemCaches } from "../Compilation" */
18+
/** @import { MemCache } from "../Compiler" */
1819
/** @import { TupleElement } from "../util/WeakTupleMap" */
1920
/** @import DependenciesBlock from "./DependenciesBlock" */
2021
/** @import Dependency, { ExportInfoName } from "./Dependency" */
@@ -180,7 +181,7 @@ class ModuleGraph {
180181
*/
181182
this._metaMap = new WeakMap();
182183
/**
183-
* @type {WeakTupleMap<EXPECTED_ANY[], EXPECTED_ANY> | undefined}
184+
* @type {MemCache | undefined}
184185
* @private
185186
*/
186187
this._cache = undefined;
@@ -1189,8 +1190,10 @@ class ModuleGraph {
11891190
*/
11901191
dependencyCacheProvide(dependency, ...args) {
11911192
const fn =
1192-
/** @type {(moduleGraph: ModuleGraph, dependency: D, ...args: TupleElement[]) => R} */
1193+
/** @type {(moduleGraph: ModuleGraph, dependency: D, ...args: ARGS) => R} */
11931194
(args.pop());
1195+
// What is left once the function is popped is the key.
1196+
const keys = /** @type {ARGS} */ (/** @type {TupleElement[]} */ (args));
11941197
if (this._moduleMemCaches && this._cacheStage) {
11951198
const memCache = this._moduleMemCaches.get(
11961199
/** @type {Module} */
@@ -1201,14 +1204,16 @@ class ModuleGraph {
12011204
return memCache.provide(
12021205
/** @type {Dependency} */ (dependency),
12031206
this._cacheStage,
1204-
...args,
1205-
() => fn(this, dependency, ...args)
1207+
...keys,
1208+
() => fn(this, dependency, ...keys)
12061209
);
12071210
}
12081211
}
1209-
if (this._cache === undefined) return fn(this, dependency, ...args);
1210-
return this._cache.provide(dependency, ...args, () =>
1211-
fn(this, dependency, ...args)
1212+
if (this._cache === undefined) return fn(this, dependency, ...keys);
1213+
return this._cache.provide(
1214+
/** @type {Dependency} */ (dependency),
1215+
...keys,
1216+
() => fn(this, dependency, ...keys)
12121217
);
12131218
}
12141219

‎lib/resolve/getResolveOptionsKey.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
/** @import { ResolveOptionsWithDependencyType } from "./ResolverFactory" */
99

10-
/** @type {WeakMap<EXPECTED_OBJECT | EXPECTED_FUNCTION, number>} */
10+
/** @type {WeakMap<EXPECTED_OBJECT, number>} */
1111
const identities = new WeakMap();
1212
let nextIdentity = 0;
1313

‎lib/serialization/ObjectMiddleware.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ const SetObjectSerializer = require("./SetObjectSerializer");
104104
/**
105105
* Defines the object serializer type used by this module.
106106
* Methods, so a serializer may narrow `value` to the class it is registered for.
107-
* @template {EXPECTED_OBJECT} [T=EXPECTED_OBJECT]
107+
* @template {object} [T=object]
108108
* @typedef {{ serialize(value: T, context: ObjectSerializerContext): void, deserialize(context: ObjectDeserializerContext): EXPECTED_OBJECT }} ObjectSerializer
109109
*/
110110

‎lib/stats/DefaultStatsPresetPlugin.js‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -302,32 +302,34 @@ const DEFAULTS = {
302302
};
303303

304304
/**
305-
* Defines the normalize function type used by this module.
306-
* @template T
307-
* @typedef {(value: T, ...args: EXPECTED_ANY[]) => boolean} NormalizeFunction
305+
* The function a configured filter of type `I` normalizes to: its own function type.
306+
* @template {string | { test: (value: string) => boolean } | boolean | ((value: string, ...rest: never[]) => boolean)} I
307+
* @typedef {Exclude<I, string | { test: (value: string) => boolean } | boolean>} FilterFunction
308308
*/
309309

310310
/**
311-
* Returns normalize fn.
312-
* @template {string} T
313-
* @param {string | ({ test: (value: T) => boolean }) | NormalizeFunction<T> | boolean} item item to normalize
314-
* @returns {NormalizeFunction<T>} normalize fn
311+
* Turns a filter as configured into the function the stats factory calls: a
312+
* string matches a path segment, a `{ test }` (a RegExp) tests the value, a
313+
* boolean answers for every value, and a function is kept as given.
314+
* @template {string | { test: (value: string) => boolean } | boolean | ((value: string, ...rest: never[]) => boolean)} I
315+
* @param {I} item item to normalize
316+
* @returns {FilterFunction<I>} normalize fn, called with the value first and the option's other arguments after it
315317
*/
316318
const normalizeFilter = (item) => {
317319
if (typeof item === "string") {
318320
const regExp = new RegExp(
319321
`[\\\\/]${item.replace(/[-[\]{}()*+?.\\^$|]/g, "\\$&")}([\\\\/]|$|!|\\?)`
320322
);
321-
return (ident) => regExp.test(ident);
323+
return /** @type {FilterFunction<I>} */ ((ident) => regExp.test(ident));
322324
}
323325
if (item && typeof item === "object" && typeof item.test === "function") {
324-
return (ident) => item.test(ident);
326+
return /** @type {FilterFunction<I>} */ ((ident) => item.test(ident));
325327
}
326328
if (typeof item === "boolean") {
327-
return () => item;
329+
return /** @type {FilterFunction<I>} */ ((_ident) => item);
328330
}
329331

330-
return /** @type {NormalizeFunction<T>} */ (item);
332+
return /** @type {FilterFunction<I>} */ (item);
331333
};
332334

333335
/** @typedef {keyof (KnownNormalizedStatsOptions | StatsOptions)} NormalizerKeys */
@@ -349,13 +351,13 @@ const NORMALIZER = {
349351
? /** @type {KnownNormalizedStatsOptions["excludeModules"]} */ ([value])
350352
: [];
351353
}
352-
return value.map(normalizeFilter);
354+
return value.map((item) => normalizeFilter(item));
353355
},
354356
excludeAssets: (value) => {
355357
if (!Array.isArray(value)) {
356358
value = value ? [value] : [];
357359
}
358-
return value.map(normalizeFilter);
360+
return value.map((item) => normalizeFilter(item));
359361
},
360362
warningsFilter: (value) => {
361363
if (!Array.isArray(value)) {
@@ -393,7 +395,7 @@ const NORMALIZER = {
393395
? /** @type {KnownNormalizedStatsOptions["loggingDebug"]} */ ([value])
394396
: [];
395397
}
396-
return value.map(normalizeFilter);
398+
return value.map((item) => normalizeFilter(item));
397399
}
398400
};
399401

‎lib/util/WeakTupleMap.js‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,8 @@ class WeakTupleMap {
121121
/**
122122
* Returns an existing value for the tuple or computes, stores, and returns a
123123
* new one when the tuple is missing.
124-
* @param {[...K, (...args: K) => V]} args tuple
124+
* @template {K} A
125+
* @param {[...A, (...args: A) => V]} args tuple
125126
* @returns {V} the value
126127
*/
127128
provide(...args) {
@@ -131,8 +132,8 @@ class WeakTupleMap {
131132
node = node._get(/** @type {ArrayElement<K>} */ (args[i]));
132133
}
133134
if (node._hasValue()) return /** @type {V} */ (node._getValue());
134-
const fn = /** @type {(...args: K) => V} */ (args[args.length - 1]);
135-
const newValue = fn(.../** @type {K} */ (args.slice(0, -1)));
135+
const fn = /** @type {(...args: A) => V} */ (args[args.length - 1]);
136+
const newValue = fn(.../** @type {A} */ (args.slice(0, -1)));
136137
node._setValue(newValue);
137138
return newValue;
138139
}
@@ -144,9 +145,10 @@ class WeakTupleMap {
144145
* extra rest array) on every call — `ModuleGraph#cached` runs this on hot
145146
* paths where most calls hit the cache and the closure would be pure waste.
146147
* @template This
147-
* @param {(thisArg: This, ...args: K) => V} compute computer, also the first key element
148+
* @template {K} A
149+
* @param {(thisArg: This, ...args: [A][A extends A ? 0 : never]) => V} compute computer, also the first key element; `A` is read from `args`, not from it
148150
* @param {This} thisArg first argument passed to `compute`
149-
* @param {K} args remaining key elements, also passed to `compute`
151+
* @param {A} args remaining key elements, also passed to `compute`
150152
* @returns {V} the value
151153
*/
152154
cachedProvide(compute, thisArg, args) {

‎lib/util/comparators.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,8 @@ const compareChunkGroupsByIndex = (a, b) =>
378378

379379
/**
380380
* Represents TwoKeyWeakMap.
381-
* @template {EXPECTED_OBJECT} K1
382-
* @template {EXPECTED_OBJECT} K2
381+
* @template {object} K1
382+
* @template {object} K2
383383
* @template T
384384
*/
385385
class TwoKeyWeakMap {

‎lib/util/deprecation.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => {
369369
/**
370370
* Updates prototype of using the provided target.
371371
* @param {T} target target
372-
* @param {EXPECTED_OBJECT | null} proto proto
372+
* @param {Parameters<typeof Reflect.setPrototypeOf>[1]} proto proto
373373
* @returns {boolean} result
374374
*/
375375
(target, proto) => Reflect.setPrototypeOf(target, proto),

‎types.d.ts‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4655,7 +4655,7 @@ declare class Compiler {
46554655
/**
46564656
* Validates a value against a schema, skipping the schema when the precompiled check passes
46574657
*/
4658-
validate<T extends Parameters<typeof validateFunction>[1] = object>(
4658+
validate<T extends Parameters<typeof validateFunction>[1]>(
46594659
schema:
46604660
| (JSONSchema4 & ExtendedSchema)
46614661
| (JSONSchema6 & ExtendedSchema)
@@ -19843,17 +19843,17 @@ type MemCache = {
1984319843
key: K,
1984419844
...restAndValue: [...TupleElement[], MemCacheValue<K>]
1984519845
): void;
19846-
provide<K extends TupleElement, V>(
19846+
provide<K extends TupleElement, V, R extends TupleElement[]>(
1984719847
key: K,
1984819848
...restAndCompute: [
19849-
...TupleElement[],
19850-
(...key: any[]) => MemCacheProvided<K, V>
19849+
...R,
19850+
(key: K, ...rest: [R][R extends R ? 0 : never]) => MemCacheProvided<K, V>
1985119851
]
1985219852
): MemCacheProvided<K, V>;
19853-
cachedProvide<This, V>(
19854-
compute: (thisArg: This, ...key: any[]) => V,
19853+
cachedProvide<This, V, A extends TupleElement[]>(
19854+
compute: (thisArg: This, ...key: [A][A extends A ? 0 : never]) => V,
1985519855
thisArg: This,
19856-
args: TupleElement[]
19856+
args: A
1985719857
): V;
1985819858
} & Omit<
1985919859
WeakTupleMap<TupleElement[], unknown>,
@@ -35287,7 +35287,7 @@ declare abstract class WeakTupleMap<K extends TupleElement[], V> {
3528735287
* Returns an existing value for the tuple or computes, stores, and returns a
3528835288
* new one when the tuple is missing.
3528935289
*/
35290-
provide(...args: [...K, (...args: K) => V]): V;
35290+
provide<A extends TupleElement[]>(...args: [...A, (...args: A) => V]): V;
3529135291

3529235292
/**
3529335293
* Memoizes `compute(thisArg, ...args)` under the tuple key `[compute,
@@ -35296,10 +35296,10 @@ declare abstract class WeakTupleMap<K extends TupleElement[], V> {
3529635296
* extra rest array) on every call — `ModuleGraph#cached` runs this on hot
3529735297
* paths where most calls hit the cache and the closure would be pure waste.
3529835298
*/
35299-
cachedProvide<This>(
35300-
compute: (thisArg: This, ...args: K) => V,
35299+
cachedProvide<This, A extends TupleElement[]>(
35300+
compute: (thisArg: This, ...args: [A][A extends A ? 0 : never]) => V,
3530135301
thisArg: This,
35302-
args: K
35302+
args: A
3530335303
): V;
3530435304

3530535305
/**

0 commit comments

Comments
 (0)