diff --git a/eslint.config.mjs b/eslint.config.mjs index 192941c02..dc2b4eead 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -350,15 +350,15 @@ export default [ comment: "JsdocBlock:has(JsdocTypeName[value=/^(function|Function)$/])", message: - "Please use provide types for function - `(a: number, b: number) -> number` instead `Function` or use `EXPECTED_FUNCTION` type" + "Please use provide types for function - `(a: number, b: number) -> number` instead `Function`/`function` or use `EXPECTED_FUNCTION` type" + }, + // No `Object` + { + comment: + "JsdocBlock:has(JsdocTag[tag!=/^(typedef|template|param)$/]:has(JsdocTypeName[value=/^(Object|object)$/]))", + message: + "Please use provide types for object - `{ property: number:, result: () => number}` instead `Object`/`object` or use `EXPECTED_OBJECT` type" } - // No `Object` type - // { - // comment: - // "JsdocBlock:has(JsdocTag[tag!=/^(typedef|template)$/]:has(JsdocTypeName[value=/^(object|Object)$/]))", - // message: - // "Please use provide types for object - `{ property: number:, result: () => number}` instead `Object` or use `EXPECTED_OBJECT` type" - // }, ] } ] diff --git a/lib/Compilation.js b/lib/Compilation.js index 15ff50858..e718903fa 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -297,7 +297,7 @@ const { isSourceEqual } = require("./util/source"); * @property {Record=} related object of pointers to other assets, keyed by type of relation (only points from parent to child) */ -/** @typedef {KnownAssetInfo & Record} AssetInfo */ +/** @typedef {KnownAssetInfo & Record} AssetInfo */ /** @typedef {{ path: string, info: AssetInfo }} InterpolatedPathAndAssetInfo */ @@ -650,10 +650,9 @@ class Compilation { * @param {number} stage new stage * @param {() => AsArray} getArgs get old hook function args * @param {string=} code deprecation code (not deprecated when unset) - * @returns {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects + * @returns {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">> | undefined} fake hook which redirects */ const createProcessAssetsHook = (name, stage, getArgs, code) => { - // @ts-expect-error For better compatibility we will avoid the optional type if (!this._backCompat && code) return; /** * @param {string} reason reason @@ -880,36 +879,52 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si beforeChunkAssets: new SyncHook([]), // TODO webpack 6 remove /** @deprecated */ - additionalChunkAssets: createProcessAssetsHook( - "additionalChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" - ), + additionalChunkAssets: + /** @type {FakeHook]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "additionalChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" + ) + ), // TODO webpack 6 deprecate /** @deprecated */ - additionalAssets: createProcessAssetsHook( - "additionalAssets", - Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, - () => [] - ), + additionalAssets: + /** @type {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "additionalAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [] + ) + ), // TODO webpack 6 remove /** @deprecated */ - optimizeChunkAssets: createProcessAssetsHook( - "optimizeChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" - ), + optimizeChunkAssets: + /** @type {FakeHook]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "optimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" + ) + ), // TODO webpack 6 remove /** @deprecated */ - afterOptimizeChunkAssets: createProcessAssetsHook( - "afterOptimizeChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" - ), + afterOptimizeChunkAssets: + /** @type {FakeHook]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "afterOptimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" + ) + ), // TODO webpack 6 deprecate /** @deprecated */ optimizeAssets: processAssetsHook, @@ -2350,7 +2365,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si }; entryData[target].push(entry); this.entries.set( - /** @type {NonNullable} */ (name), + /** @type {NonNullable} */ + (name), entryData ); } else { @@ -2367,7 +2383,10 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si continue; } if (entryData.options[key] === undefined) { - entryData.options[key] = /** @type {TODO} */ (options[key]); + /** @type {TODO} */ + (entryData.options)[key] = + /** @type {NonNullable} */ + (options[key]); } else { return callback( new WebpackError( @@ -4679,7 +4698,7 @@ This prevents using hashes of each other and should be avoided.`); /** * @param {string} file file name * @param {Source | ((source: Source) => Source)} newSourceOrFunction new asset source or function converting old to new - * @param {(AssetInfo | ((assetInfo?: AssetInfo) => AssetInfo)) | undefined} assetInfoUpdateOrFunction new asset info or function converting old to new + * @param {(AssetInfo | ((assetInfo?: AssetInfo) => AssetInfo | undefined)) | undefined} assetInfoUpdateOrFunction new asset info or function converting old to new */ updateAsset( file, diff --git a/lib/DelegatedModuleFactoryPlugin.js b/lib/DelegatedModuleFactoryPlugin.js index ae9b79aae..0c8979784 100644 --- a/lib/DelegatedModuleFactoryPlugin.js +++ b/lib/DelegatedModuleFactoryPlugin.js @@ -13,6 +13,7 @@ const DelegatedModule = require("./DelegatedModule"); /** @typedef {import("./DelegatedModule").SourceRequest} SourceRequest */ /** @typedef {import("./DelegatedModule").Type} Type */ /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ /** * @typedef {object} Options @@ -22,7 +23,7 @@ const DelegatedModule = require("./DelegatedModule"); * @property {DllReferencePluginOptions["type"]} type type * @property {DllReferencePluginOptions["extensions"]} extensions extensions * @property {DllReferencePluginOptions["scope"]} scope scope - * @property {object=} associatedObjectForCache object for caching + * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching */ class DelegatedModuleFactoryPlugin { diff --git a/lib/Dependency.js b/lib/Dependency.js index 33355ab4a..9f8046ed2 100644 --- a/lib/Dependency.js +++ b/lib/Dependency.js @@ -333,11 +333,10 @@ Dependency.NO_EXPORTS_REFERENCED = []; Dependency.EXPORTS_OBJECT_REFERENCED = [[]]; // TODO remove in webpack 6 -// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919 Object.defineProperty(Dependency.prototype, "module", { /** * @deprecated - * @returns {never} throws + * @returns {EXPECTED_ANY} throws */ get() { throw new Error( @@ -357,8 +356,11 @@ Object.defineProperty(Dependency.prototype, "module", { }); // TODO remove in webpack 6 -// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919 Object.defineProperty(Dependency.prototype, "disconnect", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throws + */ get() { throw new Error( "disconnect was removed from Dependency (Dependency no longer carries graph specific information)" diff --git a/lib/DllReferencePlugin.js b/lib/DllReferencePlugin.js index 50b2c5410..808dc099d 100644 --- a/lib/DllReferencePlugin.js +++ b/lib/DllReferencePlugin.js @@ -18,6 +18,7 @@ const makePathsRelative = require("./util/identifier").makePathsRelative; /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ /** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compiler").CompilationParams} CompilationParams */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ const validate = createSchemaValidation( @@ -38,7 +39,7 @@ class DllReferencePlugin { constructor(options) { validate(options); this.options = options; - /** @type {WeakMap} */ + /** @type {WeakMap} */ this._compilationData = new WeakMap(); } diff --git a/lib/FileSystemInfo.js b/lib/FileSystemInfo.js index 82bdf9fae..372f8537e 100644 --- a/lib/FileSystemInfo.js +++ b/lib/FileSystemInfo.js @@ -167,9 +167,8 @@ class SnapshotIterator { } } -/** - * @typedef {(snapshot: Snapshot) => (Map | Set | undefined)[]} GetMapsFunction - */ +/** @typedef {Map | Set | undefined} SnapshotMap */ +/** @typedef {(snapshot: Snapshot) => SnapshotMap[]} GetMapsFunction */ class SnapshotIterable { /** @@ -185,9 +184,9 @@ class SnapshotIterable { let state = 0; /** @type {IterableIterator} */ let it; - /** @type {(snapshot: Snapshot) => (Map | Set | undefined)[]} */ + /** @type {GetMapsFunction} */ let getMaps; - /** @type {(Map | Set | undefined)[]} */ + /** @type {SnapshotMap[]} */ let maps; /** @type {Snapshot} */ let snapshot; @@ -1336,7 +1335,7 @@ class FileSystemInfo { * @private * @param {string} path path * @param {string} reason reason - * @param {any[]} args arguments + * @param {EXPECTED_ANY[]} args arguments */ _log(path, reason, ...args) { const key = path + reason; diff --git a/lib/FlagDependencyUsagePlugin.js b/lib/FlagDependencyUsagePlugin.js index 247dbf905..3d25a2d0f 100644 --- a/lib/FlagDependencyUsagePlugin.js +++ b/lib/FlagDependencyUsagePlugin.js @@ -56,7 +56,7 @@ class FlagDependencyUsagePlugin { /** @type {Map} */ const exportInfoToModuleMap = new Map(); - /** @type {TupleQueue<[Module, RuntimeSpec]>} */ + /** @type {TupleQueue} */ const queue = new TupleQueue(); /** diff --git a/lib/Generator.js b/lib/Generator.js index fdb4a0bdd..7db4028fe 100644 --- a/lib/Generator.js +++ b/lib/Generator.js @@ -32,7 +32,7 @@ * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules * @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) * @property {string} type which kind of code should be generated - * @property {() => Map=} getData get access to the code generation data + * @property {() => Map=} getData get access to the code generation data */ /** diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js index f6a6c5ef1..1ada4992b 100644 --- a/lib/HotModuleReplacementPlugin.js +++ b/lib/HotModuleReplacementPlugin.js @@ -96,13 +96,6 @@ class HotModuleReplacementPlugin { return hooks; } - /** - * @param {object=} options options - */ - constructor(options) { - this.options = options || {}; - } - /** * Apply the plugin * @param {Compiler} compiler the compiler instance diff --git a/lib/Module.js b/lib/Module.js index a2fb52fff..03e7a6c01 100644 --- a/lib/Module.js +++ b/lib/Module.js @@ -45,6 +45,7 @@ const makeSerializable = require("./util/makeSerializable"); /** @template T @typedef {import("./util/LazySet")} LazySet */ /** @template T @typedef {import("./util/SortableSet")} SortableSet */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @@ -93,7 +94,7 @@ const makeSerializable = require("./util/makeSerializable"); /** * @typedef {object} LibIdentOptions * @property {string} context absolute context path to which lib ident is relative to - * @property {object=} associatedObjectForCache object for caching + * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching */ /** @@ -1125,8 +1126,11 @@ class Module extends DependenciesBlock { makeSerializable(Module, "webpack/lib/Module"); // TODO remove in webpack 6 -// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919 Object.defineProperty(Module.prototype, "hasEqualsChunks", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throw an error + */ get() { throw new Error( "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)" @@ -1135,8 +1139,11 @@ Object.defineProperty(Module.prototype, "hasEqualsChunks", { }); // TODO remove in webpack 6 -// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919 Object.defineProperty(Module.prototype, "isUsed", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throw an error + */ get() { throw new Error( "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" @@ -1146,10 +1153,14 @@ Object.defineProperty(Module.prototype, "isUsed", { // TODO remove in webpack 6 Object.defineProperty(Module.prototype, "errors", { + /** + * @deprecated + * @returns {WebpackError[]} errors + */ get: util.deprecate( /** * @this {Module} - * @returns {WebpackError[]} array + * @returns {WebpackError[]} errors */ function () { if (this._errors === undefined) { @@ -1164,10 +1175,14 @@ Object.defineProperty(Module.prototype, "errors", { // TODO remove in webpack 6 Object.defineProperty(Module.prototype, "warnings", { + /** + * @deprecated + * @returns {WebpackError[]} warnings + */ get: util.deprecate( /** * @this {Module} - * @returns {WebpackError[]} array + * @returns {WebpackError[]} warnings */ function () { if (this._warnings === undefined) { @@ -1181,13 +1196,19 @@ Object.defineProperty(Module.prototype, "warnings", { }); // TODO remove in webpack 6 -// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919 Object.defineProperty(Module.prototype, "used", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throw an error + */ get() { throw new Error( "Module.used was refactored (use ModuleGraph.getUsedExports instead)" ); }, + /** + * @param {EXPECTED_ANY} value value + */ set(value) { throw new Error( "Module.used was refactored (use ModuleGraph.setUsedExports instead)" diff --git a/lib/ModuleFilenameHelpers.js b/lib/ModuleFilenameHelpers.js index 1a9653794..826c3dc81 100644 --- a/lib/ModuleFilenameHelpers.js +++ b/lib/ModuleFilenameHelpers.js @@ -16,7 +16,7 @@ const memoize = require("./util/memoize"); /** @typedef {typeof import("./util/Hash")} Hash */ /** @typedef {string | RegExp | (string | RegExp)[]} Matcher */ -/** @typedef {{test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */ +/** @typedef {{ test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */ const ModuleFilenameHelpers = module.exports; diff --git a/lib/ModuleGraph.js b/lib/ModuleGraph.js index 2a19e3101..bcd568b6e 100644 --- a/lib/ModuleGraph.js +++ b/lib/ModuleGraph.js @@ -121,6 +121,9 @@ class ModuleGraphModule { /** @typedef {(moduleGraphConnection: ModuleGraphConnection) => boolean} FilterConnection */ +/** @typedef {EXPECTED_OBJECT} MetaKey */ +/** @typedef {TODO} Meta */ + /** @typedef {Map>} ModuleMemCaches */ class ModuleGraph { @@ -136,7 +139,7 @@ class ModuleGraph { */ this._moduleMap = new Map(); /** - * @type {WeakMap} + * @type {WeakMap} * @private */ this._metaMap = new WeakMap(); @@ -760,21 +763,21 @@ class ModuleGraph { } /** - * @param {TODO} thing any thing - * @returns {object} metadata + * @param {MetaKey} thing any thing + * @returns {Meta} metadata */ getMeta(thing) { let meta = this._metaMap.get(thing); if (meta === undefined) { meta = Object.create(null); - this._metaMap.set(thing, /** @type {object} */ (meta)); + this._metaMap.set(thing, meta); } - return /** @type {object} */ (meta); + return meta; } /** - * @param {TODO} thing any thing - * @returns {object | undefined} metadata + * @param {MetaKey} thing any thing + * @returns {Meta | undefined} metadata */ getMetaIfExisting(thing) { return this._metaMap.get(thing); @@ -794,10 +797,10 @@ class ModuleGraph { } /** - * @template {any[]} T + * @template T * @template V - * @param {(moduleGraph: ModuleGraph, ...args: T) => V} fn computer - * @param {T} args arguments + * @param {(moduleGraph: ModuleGraph, ...args: T[]) => V} fn computer + * @param {...T} args arguments * @returns {V} computed value or cached */ cached(fn, ...args) { diff --git a/lib/MultiCompiler.js b/lib/MultiCompiler.js index 9b43774b0..f1bcc1a70 100644 --- a/lib/MultiCompiler.js +++ b/lib/MultiCompiler.js @@ -70,7 +70,7 @@ module.exports = class MultiCompiler { watchClose: new SyncHook([]), /** @type {MultiHook>} */ watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), - /** @type {MultiHook>} */ + /** @type {MultiHook>} */ infrastructureLog: new MultiHook( compilers.map(c => c.hooks.infrastructureLog) ) diff --git a/lib/NormalModule.js b/lib/NormalModule.js index c0fce2f6f..988f62a81 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -91,6 +91,7 @@ const memoize = require("./util/memoize"); /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./util/createHash").Algorithm} Algorithm */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ /** * @template T * @typedef {import("./util/deprecation").FakeHook} FakeHook @@ -139,7 +140,7 @@ const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/; /** * @param {string} context absolute context path * @param {string} source a source path - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {string} new source path */ const contextifySourceUrl = (context, source, associatedObjectForCache) => { @@ -154,7 +155,7 @@ const contextifySourceUrl = (context, source, associatedObjectForCache) => { /** * @param {string} context absolute context path * @param {SourceMap} sourceMap a source map - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {SourceMap} new source map */ const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { @@ -536,7 +537,7 @@ class NormalModule extends Module { * @param {string} name the asset name * @param {string | Buffer} content the content * @param {(string | SourceMap)=} sourceMap an optional source map - * @param {object=} associatedObjectForCache object for caching + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching * @returns {Source} the created source */ createSourceForAsset( @@ -838,7 +839,7 @@ class NormalModule extends Module { * @param {string} context the compilation context * @param {string | Buffer} content the content * @param {(string | SourceMapSource | null)=} sourceMap an optional source map - * @param {object=} associatedObjectForCache object for caching + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching * @returns {Source} the created source */ createSource(context, content, sourceMap, associatedObjectForCache) { @@ -1017,9 +1018,9 @@ class NormalModule extends Module { loaderContext._compilation = loaderContext._compiler = loaderContext._module = - // @ts-expect-error avoid memory leaking loaderContext.fs = - undefined; + /** @type {EXPECTED_ANY} */ + (undefined); if (!result) { /** @type {BuildInfo} */ diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js index 5c6cf31e7..ff2f4103c 100644 --- a/lib/NormalModuleFactory.js +++ b/lib/NormalModuleFactory.js @@ -53,6 +53,7 @@ const { /** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ /** @typedef {import("./rules/RuleSetCompiler").RuleSetRules} RuleSetRules */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ /** @typedef {Pick} ModuleSettings */ /** @typedef {Partial} CreateData */ @@ -247,7 +248,7 @@ class NormalModuleFactory extends ModuleFactory { * @param {InputFileSystem} param.fs file system * @param {ResolverFactory} param.resolverFactory resolverFactory * @param {ModuleOptions} param.options options - * @param {object} param.associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache} param.associatedObjectForCache an object to which the cache will be attached * @param {boolean=} param.layers enable layers */ constructor({ @@ -310,9 +311,9 @@ class NormalModuleFactory extends ModuleFactory { this.fs = fs; this._globalParserOptions = options.parser; this._globalGeneratorOptions = options.generator; - /** @type {Map>} */ + /** @type {Map>} */ this.parserCache = new Map(); - /** @type {Map>} */ + /** @type {Map>} */ this.generatorCache = new Map(); /** @type {Set} */ this._restoredUnsafeCacheEntries = new Set(); @@ -625,10 +626,12 @@ class NormalModuleFactory extends ModuleFactory { settings[/** @type {keyof ModuleSettings} */ (r.type)] !== null ) { const type = /** @type {keyof ModuleSettings} */ (r.type); - settings[type] = cachedCleverMerge(settings[type], r.value); + /** @type {TODO} */ + (settings)[type] = cachedCleverMerge(settings[type], r.value); } else { const type = /** @type {keyof ModuleSettings} */ (r.type); - settings[type] = r.value; + /** @type {TODO} */ + (settings)[type] = r.value; } } } diff --git a/lib/Parser.js b/lib/Parser.js index 892c5fcd3..7110b6d2f 100644 --- a/lib/Parser.js +++ b/lib/Parser.js @@ -8,7 +8,7 @@ /** @typedef {import("./Compilation")} Compilation */ /** @typedef {import("./NormalModule")} NormalModule */ -/** @typedef {Record} PreparsedAst */ +/** @typedef {Record} PreparsedAst */ /** * @typedef {object} ParserStateBase diff --git a/lib/RecordIdsPlugin.js b/lib/RecordIdsPlugin.js index aaace61c8..25f3115e8 100644 --- a/lib/RecordIdsPlugin.js +++ b/lib/RecordIdsPlugin.js @@ -32,10 +32,14 @@ const identifierUtils = require("./util/identifier"); * @property {RecordsModules=} modules */ +/** + * @typedef {object} RecordIdsPluginOptions + * @property {boolean=} portableIds true, when ids need to be portable + */ + class RecordIdsPlugin { /** - * @param {object} options Options object - * @param {boolean=} options.portableIds true, when ids need to be portable + * @param {RecordIdsPluginOptions} [options] object */ constructor(options) { this.options = options || {}; diff --git a/lib/RequestShortener.js b/lib/RequestShortener.js index 9ef80190f..b39bc2e73 100644 --- a/lib/RequestShortener.js +++ b/lib/RequestShortener.js @@ -7,10 +7,12 @@ const { contextify } = require("./util/identifier"); +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ + class RequestShortener { /** * @param {string} dir the directory - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached */ constructor(dir, associatedObjectForCache) { this.contextify = contextify.bindContextCache( diff --git a/lib/ResolverFactory.js b/lib/ResolverFactory.js index 0403e8706..7ed2143ea 100644 --- a/lib/ResolverFactory.js +++ b/lib/ResolverFactory.js @@ -20,7 +20,7 @@ const { /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ /** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ -/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ +/** @typedef {WebpackResolveOptions & { dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ /** * @typedef {object} WithOptions * @property {(options: Partial) => ResolverWithOptions} withOptions create a resolver with additional/different options @@ -29,6 +29,7 @@ const { /** @typedef {Resolver & WithOptions} ResolverWithOptions */ // need to be hoisted on module level for caching identity +/** @type {ResolveOptionsWithDependencyType} */ const EMPTY_RESOLVE_OPTIONS = {}; /** @@ -69,7 +70,7 @@ const convertToResolveOptions = resolveOptionsWithDepType => { /** * @typedef {object} ResolverCache - * @property {WeakMap} direct + * @property {WeakMap} direct * @property {Map} stringified */ diff --git a/lib/WebpackOptionsApply.js b/lib/WebpackOptionsApply.js index 3928c0438..238a1b7cc 100644 --- a/lib/WebpackOptionsApply.js +++ b/lib/WebpackOptionsApply.js @@ -395,7 +395,7 @@ class WebpackOptionsApply extends OptionsApply { new RequireJsStuffPlugin().apply(compiler); } new CommonJsPlugin().apply(compiler); - new LoaderPlugin({}).apply(compiler); + new LoaderPlugin().apply(compiler); if (options.node !== false) { const NodeStuffPlugin = require("./NodeStuffPlugin"); new NodeStuffPlugin(options.node).apply(compiler); diff --git a/lib/cache/MemoryWithGcCachePlugin.js b/lib/cache/MemoryWithGcCachePlugin.js index ddfb80b15..2597ef505 100644 --- a/lib/cache/MemoryWithGcCachePlugin.js +++ b/lib/cache/MemoryWithGcCachePlugin.js @@ -12,10 +12,14 @@ const Cache = require("../Cache"); /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ +/** + * @typedef {object} MemoryWithGcCachePluginOptions + * @property {number} maxGenerations max generations + */ + class MemoryWithGcCachePlugin { /** - * @param {object} options Options - * @param {number} options.maxGenerations max generations + * @param {MemoryWithGcCachePluginOptions} options options */ constructor({ maxGenerations }) { this._maxGenerations = maxGenerations; diff --git a/lib/cli.js b/lib/cli.js index c7ff52bc3..fce5251f9 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -272,7 +272,7 @@ const getArguments = (schema = webpackSchema) => { /** * @param {Schema} schemaPart the current schema * @param {string} schemaPath the current path in the schema - * @param {{schema: object, path: string}[]} path all previous visited schemaParts + * @param {{ schema: TODO, path: string }[]} path all previous visited schemaParts * @param {string | null} inArray if inside of an array, the path to the array * @returns {number} added arguments */ diff --git a/lib/config/target.js b/lib/config/target.js index de8e06295..d09ee4f2a 100644 --- a/lib/config/target.js +++ b/lib/config/target.js @@ -341,7 +341,7 @@ const mergeTargetProperties = targetProperties => { keys.add(/** @type {keyof TargetProperties} */ (key)); } } - /** @type {object} */ + /** @type {TargetProperties} */ const result = {}; for (const key of keys) { let hasTrue = false; @@ -361,7 +361,7 @@ const mergeTargetProperties = targetProperties => { /** @type {TargetProperties} */ (result)[key] = hasFalse && hasTrue ? null : Boolean(hasTrue); } - return /** @type {TargetProperties} */ (result); + return result; }; /** diff --git a/lib/css/CssParser.js b/lib/css/CssParser.js index 343d22e7a..b6678a78e 100644 --- a/lib/css/CssParser.js +++ b/lib/css/CssParser.js @@ -283,13 +283,17 @@ const eatUntilSemi = walkCssTokens.eatUntil(";"); const eatUntilLeftCurly = walkCssTokens.eatUntil("{"); const eatSemi = walkCssTokens.eatUntil(";"); +/** + * @typedef {object} CssParserOptions + * @property {boolean=} importOption need handle `@import` + * @property {boolean=} url need handle URLs + * @property {("pure" | "global" | "local" | "auto")=} defaultMode default mode + * @property {boolean=} namedExports is named exports + */ + class CssParser extends Parser { /** - * @param {object} options options - * @param {boolean=} options.importOption need handle `@import` - * @param {boolean=} options.url need handle URLs - * @param {("pure" | "global" | "local" | "auto")=} options.defaultMode default mode - * @param {boolean=} options.namedExports is named exports + * @param {CssParserOptions} [options] options */ constructor({ defaultMode = "pure", diff --git a/lib/dependencies/CommonJsExportRequireDependency.js b/lib/dependencies/CommonJsExportRequireDependency.js index d4f7a73c8..fdea9d8c5 100644 --- a/lib/dependencies/CommonJsExportRequireDependency.js +++ b/lib/dependencies/CommonJsExportRequireDependency.js @@ -71,9 +71,7 @@ class CommonJsExportRequireDependency extends ModuleDependency { * @returns {string[]} the imported id */ getIds(moduleGraph) { - return ( - /** @type {TODO} */ (moduleGraph.getMeta(this))[idsSymbol] || this.ids - ); + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; } /** @@ -82,7 +80,7 @@ class CommonJsExportRequireDependency extends ModuleDependency { * @returns {void} */ setIds(moduleGraph, ids) { - /** @type {TODO} */ (moduleGraph.getMeta(this))[idsSymbol] = ids; + moduleGraph.getMeta(this)[idsSymbol] = ids; } /** diff --git a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js index 0e94201b3..68d905166 100644 --- a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +++ b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js @@ -120,8 +120,8 @@ class ExportMode { /** * @param {ModuleGraph} moduleGraph module graph - * @param {TODO} dependencies dependencies - * @param {Dependency=} additionalDependency additional dependency + * @param {HarmonyExportImportedSpecifierDependency[]} dependencies dependencies + * @param {TODO=} additionalDependency additional dependency * @returns {{ names: Names, dependencyIndices: DependencyIndices }} result */ const determineExportAssignments = ( @@ -426,10 +426,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { * @returns {Ids} the imported id */ getIds(moduleGraph) { - return ( - /** @type {TODO} */ - (moduleGraph.getMeta(this))[idsSymbol] || this.ids - ); + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; } /** @@ -438,8 +435,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { * @returns {void} */ setIds(moduleGraph, ids) { - /** @type {TODO} */ - (moduleGraph.getMeta(this))[idsSymbol] = ids; + moduleGraph.getMeta(this)[idsSymbol] = ids; } /** diff --git a/lib/dependencies/HarmonyImportDependency.js b/lib/dependencies/HarmonyImportDependency.js index e9f26fc94..2de2f0131 100644 --- a/lib/dependencies/HarmonyImportDependency.js +++ b/lib/dependencies/HarmonyImportDependency.js @@ -89,7 +89,7 @@ class HarmonyImportDependency extends ModuleDependency { */ getImportVar(moduleGraph) { const module = /** @type {Module} */ (moduleGraph.getParentModule(this)); - const meta = /** @type {TODO} */ (moduleGraph.getMeta(module)); + const meta = moduleGraph.getMeta(module); let importVarMap = meta.importVarMap; if (!importVarMap) meta.importVarMap = importVarMap = new Map(); let importVar = importVarMap.get( diff --git a/lib/dependencies/HarmonyImportSpecifierDependency.js b/lib/dependencies/HarmonyImportSpecifierDependency.js index 3ea38c111..00adb9cf0 100644 --- a/lib/dependencies/HarmonyImportSpecifierDependency.js +++ b/lib/dependencies/HarmonyImportSpecifierDependency.js @@ -104,7 +104,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency { getIds(moduleGraph) { const meta = moduleGraph.getMetaIfExisting(this); if (meta === undefined) return this.ids; - const ids = meta[/** @type {keyof object} */ (idsSymbol)]; + const ids = meta[idsSymbol]; return ids !== undefined ? ids : this.ids; } diff --git a/lib/dependencies/LoaderPlugin.js b/lib/dependencies/LoaderPlugin.js index d39acc9e6..554497ec9 100644 --- a/lib/dependencies/LoaderPlugin.js +++ b/lib/dependencies/LoaderPlugin.js @@ -12,6 +12,7 @@ const LoaderImportDependency = require("./LoaderImportDependency"); /** @typedef {import("../../declarations/LoaderContext").LoaderPluginLoaderContext} LoaderPluginLoaderContext */ /** @typedef {import("../Compilation").DepConstructor} DepConstructor */ +/** @typedef {import("../Compilation").ExecuteModuleExports} ExecuteModuleExports */ /** @typedef {import("../Compilation").ExecuteModuleResult} ExecuteModuleResult */ /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ @@ -20,7 +21,7 @@ const LoaderImportDependency = require("./LoaderImportDependency"); /** * @callback ImportModuleCallback * @param {(Error | null)=} err error object - * @param {any=} exports exports of the evaluated module + * @param {ExecuteModuleExports=} exports exports of the evaluated module */ /** @@ -31,11 +32,6 @@ const LoaderImportDependency = require("./LoaderImportDependency"); */ class LoaderPlugin { - /** - * @param {object} options options - */ - constructor(options = {}) {} - /** * Apply the plugin * @param {Compiler} compiler the compiler instance @@ -150,12 +146,7 @@ class LoaderPlugin { for (const d of buildDependencies) { loaderContext.addBuildDependency(d); } - return callback( - null, - source, - /** @type {object | null} */ (map), - referencedModule - ); + return callback(null, source, map, referencedModule); } ); }; diff --git a/lib/ids/IdHelpers.js b/lib/ids/IdHelpers.js index ddbdd19b6..5a4c9f04b 100644 --- a/lib/ids/IdHelpers.js +++ b/lib/ids/IdHelpers.js @@ -14,6 +14,7 @@ const numberHash = require("../util/numberHash"); /** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../Module")} Module */ /** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ /** * @param {string} str string to hash @@ -75,7 +76,7 @@ const shortenLongString = (string, delimiter, hashFunction) => { /** * @param {Module} module the module * @param {string} context context directory - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {string} short module name */ const getShortModuleName = (module, context, associatedObjectForCache) => { @@ -95,7 +96,7 @@ module.exports.getShortModuleName = getShortModuleName; * @param {Module} module the module * @param {string} context context directory * @param {string | Hash} hashFunction hash function to use - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {string} long module name */ const getLongModuleName = ( @@ -113,7 +114,7 @@ module.exports.getLongModuleName = getLongModuleName; /** * @param {Module} module the module * @param {string} context context directory - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {string} full module name */ const getFullModuleName = (module, context, associatedObjectForCache) => @@ -126,7 +127,7 @@ module.exports.getFullModuleName = getFullModuleName; * @param {string} context context directory * @param {string} delimiter delimiter for names * @param {string | Hash} hashFunction hash function to use - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {string} short chunk name */ const getShortChunkName = ( @@ -156,7 +157,7 @@ module.exports.getShortChunkName = getShortChunkName; * @param {string} context context directory * @param {string} delimiter delimiter for names * @param {string | Hash} hashFunction hash function to use - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {string} short chunk name */ const getLongChunkName = ( @@ -189,7 +190,7 @@ module.exports.getLongChunkName = getLongChunkName; * @param {Chunk} chunk the chunk * @param {ChunkGraph} chunkGraph the chunk graph * @param {string} context context directory - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached * @returns {string} full chunk name */ const getFullChunkName = ( diff --git a/lib/ids/SyncModuleIdsPlugin.js b/lib/ids/SyncModuleIdsPlugin.js index 7154a8bcd..c29c42c0c 100644 --- a/lib/ids/SyncModuleIdsPlugin.js +++ b/lib/ids/SyncModuleIdsPlugin.js @@ -14,13 +14,17 @@ const { getUsedModuleIdsAndModules } = require("./IdHelpers"); const plugin = "SyncModuleIdsPlugin"; +/** + * @typedef {object} SyncModuleIdsPluginOptions + * @property {string} path path to file + * @property {string=} context context for module names + * @property {((module: Module) => boolean)=} test selector for modules + * @property {"read" | "create" | "merge" | "update"=} mode operation mode (defaults to merge) + */ + class SyncModuleIdsPlugin { /** - * @param {object} options options - * @param {string} options.path path to file - * @param {string=} options.context context for module names - * @param {((module: Module) => boolean)=} options.test selector for modules - * @param {"read" | "create" | "merge" | "update"=} options.mode operation mode (defaults to merge) + * @param {SyncModuleIdsPluginOptions} options options */ constructor({ path, context, test, mode }) { this._path = path; diff --git a/lib/index.js b/lib/index.js index 8be984e5f..d82014b2a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -72,7 +72,7 @@ const lazyFunction = factory => { const fac = memoize(factory); const f = /** @type {any} */ ( /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args * @returns {T} result */ (...args) => fac()(...args) diff --git a/lib/javascript/JavascriptParser.js b/lib/javascript/JavascriptParser.js index bb8077f0b..e45d8171e 100644 --- a/lib/javascript/JavascriptParser.js +++ b/lib/javascript/JavascriptParser.js @@ -114,71 +114,68 @@ const ALLOWED_MEMBER_TYPES_ALL = 0b11; const LEGACY_ASSERT_ATTRIBUTES = Symbol("assert"); -/** - * @param {any} Parser parser - * @returns {typeof AcornParser} extender acorn parser - */ +/** @type {(BaseParser: typeof AcornParser) => typeof AcornParser} */ const importAssertions = Parser => - /** @type {typeof AcornParser} */ ( - /** @type {unknown} */ ( - class extends Parser { - parseWithClause() { - /** @type {ImportAttribute[]} */ - const nodes = []; + class extends Parser { + /** + * @this {TODO} + * @returns {ImportAttribute[]} import attributes + */ + parseWithClause() { + /** @type {ImportAttribute[]} */ + const nodes = []; - const isAssertLegacy = this.value === "assert"; - - if (isAssertLegacy) { - if (!this.eat(tokTypes.name)) { - return nodes; - } - } else if (!this.eat(tokTypes._with)) { - return nodes; - } - - this.expect(tokTypes.braceL); - - /** @type {Record} */ - const attributeKeys = {}; - let first = true; - - while (!this.eat(tokTypes.braceR)) { - if (!first) { - this.expect(tokTypes.comma); - if (this.afterTrailingComma(tokTypes.braceR)) { - break; - } - } else { - first = false; - } - - const attr = - /** @type {ImportAttribute} */ - this.parseImportAttribute(); - const keyName = - attr.key.type === "Identifier" ? attr.key.name : attr.key.value; - - if (Object.prototype.hasOwnProperty.call(attributeKeys, keyName)) { - this.raiseRecoverable( - attr.key.start, - `Duplicate attribute key '${keyName}'` - ); - } - - attributeKeys[keyName] = true; - nodes.push(attr); - } - - if (isAssertLegacy) { - /** @type {EXPECTED_ANY} */ - (nodes)[LEGACY_ASSERT_ATTRIBUTES] = true; - } + const isAssertLegacy = this.value === "assert"; + if (isAssertLegacy) { + if (!this.eat(tokTypes.name)) { return nodes; } + } else if (!this.eat(tokTypes._with)) { + return nodes; } - ) - ); + + this.expect(tokTypes.braceL); + + /** @type {Record} */ + const attributeKeys = {}; + let first = true; + + while (!this.eat(tokTypes.braceR)) { + if (!first) { + this.expect(tokTypes.comma); + if (this.afterTrailingComma(tokTypes.braceR)) { + break; + } + } else { + first = false; + } + + const attr = + /** @type {ImportAttribute} */ + this.parseImportAttribute(); + const keyName = + attr.key.type === "Identifier" ? attr.key.name : attr.key.value; + + if (Object.prototype.hasOwnProperty.call(attributeKeys, keyName)) { + this.raiseRecoverable( + attr.key.start, + `Duplicate attribute key '${keyName}'` + ); + } + + attributeKeys[keyName] = true; + nodes.push(attr); + } + + if (isAssertLegacy) { + /** @type {EXPECTED_ANY} */ + (nodes)[LEGACY_ASSERT_ATTRIBUTES] = true; + } + + return nodes; + } + }; // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API const parser = AcornParser.extend(importAssertions); @@ -276,7 +273,7 @@ class VariableInfo { /** @typedef {Omit & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ /** @typedef {symbol} Tag */ -/** @typedef {Record} TagData */ +/** @typedef {Record} TagData */ /** * @typedef {object} TagInfo @@ -1254,7 +1251,8 @@ class JavascriptParser extends Parser { case "MetaProperty": { const res = this.callHooksForName( this.hooks.evaluateTypeof, - /** @type {string} */ (getRootName(expr.argument)), + /** @type {string} */ + (getRootName(expr.argument)), expr ); if (res !== undefined) return res; @@ -1452,7 +1450,8 @@ class JavascriptParser extends Parser { return this.callHooksForName( this.hooks.evaluateIdentifier, - /** @type {string} */ (getRootName(metaProperty)), + /** @type {string} */ + (getRootName(metaProperty)), metaProperty ); }); @@ -2705,9 +2704,8 @@ class JavascriptParser extends Parser { walkExportDefaultDeclaration(statement) { this.hooks.export.call(statement); if ( - /** @type {FunctionDeclaration | ClassDeclaration} */ ( - statement.declaration - ).id && + /** @type {FunctionDeclaration | ClassDeclaration} */ + (statement.declaration).id && statement.declaration.type !== "FunctionExpression" && statement.declaration.type !== "ClassExpression" ) { @@ -3798,11 +3796,12 @@ class JavascriptParser extends Parser { } /** - * @param {TODO} expression member expression + * @template R + * @param {MemberExpression} expression member expression * @param {string} name name * @param {string | VariableInfo} rootInfo root info * @param {string[]} members members - * @param {TODO} onUnhandled on unhandled callback + * @param {() => R | undefined} onUnhandled on unhandled callback */ walkMemberExpressionWithExpressionName( expression, @@ -3815,7 +3814,9 @@ class JavascriptParser extends Parser { // optimize the case where expression.object is a MemberExpression too. // we can keep info here when calling walkMemberExpression directly const property = - expression.property.name || `${expression.property.value}`; + /** @type {Identifier} */ + (expression.property).name || + `${/** @type {TODO} */ (expression.property).value}`; name = name.slice(0, -property.length - 1); members.pop(); const result = this.callHooksForInfo( @@ -3881,8 +3882,8 @@ class JavascriptParser extends Parser { * @template R * @param {HookMap>} hookMap hooks the should be called * @param {Expression | Super} expr expression info - * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => string[]) => any) | undefined} fallback callback when variable in not handled by hooks - * @param {((result?: string) => any) | undefined} defined callback when variable is defined + * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => string[]) => TODO) | undefined} fallback callback when variable in not handled by hooks + * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined * @param {AsArray} args args for the hook * @returns {R | undefined} result of hook */ @@ -3951,8 +3952,8 @@ class JavascriptParser extends Parser { * @template R * @param {HookMap>} hookMap hooks the should be called * @param {ExportedVariableInfo} info variable info - * @param {((name: string) => any) | undefined} fallback callback when variable in not handled by hooks - * @param {((result?: string) => any) | undefined} defined callback when variable is defined + * @param {((name: string) => TODO) | undefined} fallback callback when variable in not handled by hooks + * @param {((result?: string) => TODO) | undefined} defined callback when variable is defined * @param {AsArray} args args for the hook * @returns {R | undefined} result of hook */ @@ -4001,8 +4002,8 @@ class JavascriptParser extends Parser { * @template R * @param {HookMap>} hookMap hooks the should be called * @param {string} name key in map - * @param {((value: string) => any) | undefined} fallback callback when variable in not handled by hooks - * @param {(() => any) | undefined} defined callback when variable is defined + * @param {((value: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks + * @param {(() => R) | undefined} defined callback when variable is defined * @param {AsArray} args args for the hook * @returns {R | undefined} result of hook */ diff --git a/lib/library/AbstractLibraryPlugin.js b/lib/library/AbstractLibraryPlugin.js index fbd88a4bb..3b687c495 100644 --- a/lib/library/AbstractLibraryPlugin.js +++ b/lib/library/AbstractLibraryPlugin.js @@ -32,14 +32,18 @@ const COMMON_LIBRARY_NAME_MESSAGE = * @property {T} options */ +/** + * @typedef {object} AbstractLibraryPluginOptions + * @property {string} pluginName name of the plugin + * @property {LibraryType} type used library type + */ + /** * @template T */ class AbstractLibraryPlugin { /** - * @param {object} options options - * @param {string} options.pluginName name of the plugin - * @param {LibraryType} options.type used library type + * @param {AbstractLibraryPluginOptions} options options */ constructor({ pluginName, type }) { this._pluginName = pluginName; diff --git a/lib/node/NodeEnvironmentPlugin.js b/lib/node/NodeEnvironmentPlugin.js index 221b1af0e..9972dc4cf 100644 --- a/lib/node/NodeEnvironmentPlugin.js +++ b/lib/node/NodeEnvironmentPlugin.js @@ -15,10 +15,14 @@ const nodeConsole = require("./nodeConsole"); /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** + * @typedef {object} NodeEnvironmentPluginOptions + * @property {InfrastructureLogging} infrastructureLogging infrastructure logging options + */ + class NodeEnvironmentPlugin { /** - * @param {object} options options - * @param {InfrastructureLogging} options.infrastructureLogging infrastructure logging options + * @param {NodeEnvironmentPluginOptions} options options */ constructor(options) { this.options = options; diff --git a/lib/optimize/ConcatenatedModule.js b/lib/optimize/ConcatenatedModule.js index b9954851b..a15dd929b 100644 --- a/lib/optimize/ConcatenatedModule.js +++ b/lib/optimize/ConcatenatedModule.js @@ -86,6 +86,7 @@ const { /** @typedef {typeof import("../util/Hash")} HashConstructor */ /** @typedef {import("../util/concatenate").UsedNames} UsedNames */ /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @@ -614,7 +615,7 @@ class ConcatenatedModule extends Module { * @param {Set} modules all modules in the concatenation (including the root module) * @param {RuntimeSpec} runtime the runtime * @param {Compilation} compilation the compilation - * @param {object=} associatedObjectForCache object for caching + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching * @param {string | HashConstructor=} hashFunction hash function to use * @returns {ConcatenatedModule} the module */ @@ -1042,7 +1043,7 @@ class ConcatenatedModule extends Module { /** * @param {Module} rootModule the root module of the concatenation * @param {Set} modules all modules in the concatenation (including the root module) - * @param {object=} associatedObjectForCache object for caching + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching * @param {string | HashConstructor=} hashFunction hash function to use * @returns {string} the identifier */ diff --git a/lib/optimize/RealContentHashPlugin.js b/lib/optimize/RealContentHashPlugin.js index c62e2c07f..13abf66cf 100644 --- a/lib/optimize/RealContentHashPlugin.js +++ b/lib/optimize/RealContentHashPlugin.js @@ -107,6 +107,12 @@ const toCachedSource = source => { /** @type {WeakMap} */ const compilationHooksMap = new WeakMap(); +/** + * @typedef {object} RealContentHashPluginOptions + * @property {string | Hash} hashFunction the hash function to use + * @property {string=} hashDigest the hash digest to use + */ + class RealContentHashPlugin { /** * @param {Compilation} compilation the compilation @@ -129,9 +135,7 @@ class RealContentHashPlugin { } /** - * @param {object} options options object - * @param {string | Hash} options.hashFunction the hash function to use - * @param {string} options.hashDigest the hash digest to use + * @param {RealContentHashPluginOptions} options options */ constructor({ hashFunction, hashDigest }) { this._hashFunction = hashFunction; diff --git a/lib/optimize/SplitChunksPlugin.js b/lib/optimize/SplitChunksPlugin.js index 52a66e08f..4b5f36f17 100644 --- a/lib/optimize/SplitChunksPlugin.js +++ b/lib/optimize/SplitChunksPlugin.js @@ -164,7 +164,7 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); * @property {Set} chunksKeys */ -const defaultGetName = /** @type {GetName} */ (() => {}); +const defaultGetName = /** @type {TODO} */ (() => {}); const deterministicGroupingForModules = /** @type {(options: DeterministicGroupingOptionsForModule) => DeterministicGroupingGroupedItemsForModule[]} */ diff --git a/lib/serialization/ObjectMiddleware.js b/lib/serialization/ObjectMiddleware.js index d4519b040..53ddcc3f6 100644 --- a/lib/serialization/ObjectMiddleware.js +++ b/lib/serialization/ObjectMiddleware.js @@ -67,7 +67,7 @@ Technically any value can be used. * @property {() => ObjectSerializerSnapshot} snapshot * @property {(snapshot: ObjectSerializerSnapshot) => void} rollback * @property {((item: any) => void)=} writeLazy - * @property {((item: any, obj?: object) => (() => Promise | any))=} writeSeparate + * @property {((item: any, obj?: TODO) => (() => Promise | any))=} writeSeparate */ /** diff --git a/lib/stats/DefaultStatsFactoryPlugin.js b/lib/stats/DefaultStatsFactoryPlugin.js index fbb9503fc..d18797aef 100644 --- a/lib/stats/DefaultStatsFactoryPlugin.js +++ b/lib/stats/DefaultStatsFactoryPlugin.js @@ -293,7 +293,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {ChunkId=} chunkId * @property {string|number=} moduleId * @property {StatsModuleTraceItem[]=} moduleTrace - * @property {any=} details + * @property {string=} details * @property {string=} stack */ @@ -1908,7 +1908,9 @@ const errorsSpaceLimit = (errors, max) => { const error = errors[i++]; result.push({ ...error, - details: error.details.split("\n").slice(0, -overLimit).join("\n"), + details: + /** @type {string} */ + (error.details).split("\n").slice(0, -overLimit).join("\n"), filteredDetails: overLimit }); filtered = errors.length - i; diff --git a/lib/stats/DefaultStatsPrinterPlugin.js b/lib/stats/DefaultStatsPrinterPlugin.js index fdd059984..ea624496d 100644 --- a/lib/stats/DefaultStatsPrinterPlugin.js +++ b/lib/stats/DefaultStatsPrinterPlugin.js @@ -726,7 +726,9 @@ const MODULE_TRACE_DEPENDENCY_PRINTERS = { "moduleTraceDependency.loc": loc => loc }; -/** @type {Record string)>} */ +/** + * @type {Record string)>} + */ const ITEM_NAMES = { "compilation.assets[]": "asset", "compilation.modules[]": "module", diff --git a/lib/util/TupleQueue.js b/lib/util/TupleQueue.js index 6cdd7ea9f..b7ec14a22 100644 --- a/lib/util/TupleQueue.js +++ b/lib/util/TupleQueue.js @@ -8,21 +8,22 @@ const TupleSet = require("./TupleSet"); /** - * @template {any[]} T + * @template T + * @template V */ class TupleQueue { /** - * @param {Iterable=} items The initial elements. + * @param {Iterable<[T, V]>=} items The initial elements. */ constructor(items) { /** * @private - * @type {TupleSet} + * @type {TupleSet<[T, V]>} */ this._set = new TupleSet(items); /** * @private - * @type {Iterator} + * @type {Iterator<[T, V]>} */ this._iterator = this._set[Symbol.iterator](); } @@ -37,7 +38,7 @@ class TupleQueue { /** * Appends the specified element to this queue. - * @param {T} item The element to add. + * @param {[T, V]} item The element to add. * @returns {void} */ enqueue(...item) { @@ -46,20 +47,20 @@ class TupleQueue { /** * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + * @returns {[T, V] | undefined} The head of the queue of `undefined` if this queue is empty. */ dequeue() { const result = this._iterator.next(); if (result.done) { if (this._set.size > 0) { this._iterator = this._set[Symbol.iterator](); - const value = this._iterator.next().value; + const value = /** @type {[T, V]} */ (this._iterator.next().value); this._set.delete(...value); return value; } return; } - this._set.delete(...result.value); + this._set.delete(.../** @type {[T, V]} */ (result.value)); return result.value; } } diff --git a/lib/util/WeakTupleMap.js b/lib/util/WeakTupleMap.js index 20790d986..2db609b81 100644 --- a/lib/util/WeakTupleMap.js +++ b/lib/util/WeakTupleMap.js @@ -6,14 +6,14 @@ "use strict"; /** - * @template {any[]} T + * @template T * @template V - * @typedef {Map>} M + * @typedef {Map>} M */ /** - * @template {any[]} T + * @template T * @template V - * @typedef {WeakMap>} W + * @typedef {WeakMap>} W */ /** @@ -32,7 +32,7 @@ class WeakTupleMap { this.f = 0; /** * @private - * @type {any} + * @type {V | undefined} */ this.v = undefined; /** @@ -98,7 +98,7 @@ class WeakTupleMap { for (let i = 0; i < args.length - 1; i++) { node = node._get(args[i]); } - if (node._hasValue()) return node._getValue(); + if (node._hasValue()) return /** @type {V} */ (node._getValue()); const fn = args[args.length - 1]; const newValue = fn(...args.slice(0, -1)); node._setValue(newValue); @@ -138,7 +138,7 @@ class WeakTupleMap { } /** - * @param {any} v value + * @param {V} v value * @private */ _setValue(v) { @@ -152,7 +152,7 @@ class WeakTupleMap { } /** - * @param {any} thing thing + * @param {EXPECTED_ANY} thing thing * @returns {WeakTupleMap | undefined} thing * @private */ @@ -167,7 +167,7 @@ class WeakTupleMap { /** * @private - * @param {any} thing thing + * @param {EXPECTED_ANY} thing thing * @returns {WeakTupleMap} value */ _get(thing) { diff --git a/lib/util/cleverMerge.js b/lib/util/cleverMerge.js index 375a447e0..46873106c 100644 --- a/lib/util/cleverMerge.js +++ b/lib/util/cleverMerge.js @@ -5,9 +5,9 @@ "use strict"; -/** @type {WeakMap>} */ +/** @type {WeakMap>} */ const mergeCache = new WeakMap(); -/** @type {WeakMap>>} */ +/** @type {WeakMap>>} */ const setPropertyCache = new WeakMap(); const DELETE = Symbol("DELETE"); const DYNAMIC_INFO = Symbol("cleverMerge dynamic info"); @@ -44,7 +44,7 @@ const cachedCleverMerge = (first, second) => { if (prevMerge !== undefined) return prevMerge; const newMerge = _cleverMerge(first, second, true); innerCache.set(second, newMerge); - return /** @type {T & O} */ (newMerge); + return newMerge; }; /** @@ -99,11 +99,12 @@ const cachedSetProperty = (obj, property, value) => { * @property {{ byProperty: string, fn: DynamicFunction } | undefined} dynamic dynamic part */ -/** @type {WeakMap} */ +/** @type {WeakMap} */ const parseCache = new WeakMap(); /** - * @param {object} obj the object + * @template {object} T + * @param {T} obj the object * @returns {ParsedObject} parsed object */ const cachedParseObject = obj => { @@ -140,7 +141,7 @@ const parseObject = obj => { for (const key of Object.keys(obj)) { if (key.startsWith("by")) { const byProperty = /** @type {keyof T} */ (key); - const byObj = /** @type {object} */ (obj[byProperty]); + const byObj = /** @type {TODO} */ (obj[byProperty]); if (typeof byObj === "object") { for (const byValue of Object.keys(byObj)) { const obj = byObj[/** @type {keyof (keyof T)} */ (byValue)]; @@ -285,11 +286,13 @@ const cleverMerge = (first, second) => { }; /** + * @template {object} T + * @template {object} O * Merges two objects. Objects are deeply clever merged. - * @param {object} first first object - * @param {object} second second object + * @param {T} first first + * @param {O} second second * @param {boolean} internalCaching should parsing of objects and nested merges be cached - * @returns {object} merged object of first and second object + * @returns {T & O} merged object of first and second object */ const _cleverMerge = (first, second, internalCaching = false) => { const firstObject = internalCaching @@ -302,9 +305,13 @@ const _cleverMerge = (first, second, internalCaching = false) => { let { byProperty, fn } = firstDynamicInfo; const fnInfo = fn[DYNAMIC_INFO]; if (fnInfo) { - second = internalCaching - ? cachedCleverMerge(fnInfo[1], second) - : cleverMerge(fnInfo[1], second); + second = + /** @type {TODO} */ + ( + internalCaching + ? cachedCleverMerge(fnInfo[1], second) + : cleverMerge(fnInfo[1], second) + ); fn = fnInfo[0]; } /** @type {DynamicFunction} */ @@ -315,7 +322,9 @@ const _cleverMerge = (first, second, internalCaching = false) => { : cleverMerge(fnResult, second); }; newFn[DYNAMIC_INFO] = [fn, second]; - return serializeObject(firstObject.static, { byProperty, fn: newFn }); + return /** @type {T & O} */ ( + serializeObject(firstObject.static, { byProperty, fn: newFn }) + ); } // If the first part is static only, we merge the static parts and keep the dynamic part of the second argument @@ -338,7 +347,7 @@ const _cleverMerge = (first, second, internalCaching = false) => { resultInfo.set(key, secondEntry); } } - return serializeObject(resultInfo, secondDynamicInfo); + return /** @type {T & O} */ (serializeObject(resultInfo, secondDynamicInfo)); }; /** diff --git a/lib/util/comparators.js b/lib/util/comparators.js index bdfea56d7..7b3fbd98d 100644 --- a/lib/util/comparators.js +++ b/lib/util/comparators.js @@ -21,26 +21,27 @@ const { compareRuntime } = require("./runtime"); * @typedef {(a: T, b: T) => -1 | 0 | 1} Comparator */ /** - * @template TArg + * @template {object} TArg * @template T * @typedef {(tArg: TArg, a: T, b: T) => -1 | 0 | 1} RawParameterizedComparator */ /** - * @template TArg + * @template {object} TArg * @template T * @typedef {(tArg: TArg) => Comparator} ParameterizedComparator */ /** - * @template T - * @param {RawParameterizedComparator} fn comparator with argument - * @returns {ParameterizedComparator} comparator + * @template {object} TArg + * @template {object} T + * @param {RawParameterizedComparator} fn comparator with argument + * @returns {ParameterizedComparator} comparator */ const createCachedParameterizedComparator = fn => { - /** @type {WeakMap>} */ + /** @type {WeakMap>} */ const map = new WeakMap(); return arg => { - const cachedResult = map.get(arg); + const cachedResult = map.get(/** @type {EXPECTED_OBJECT} */ (arg)); if (cachedResult !== undefined) return cachedResult; /** * @param {T} a first item @@ -48,7 +49,7 @@ const createCachedParameterizedComparator = fn => { * @returns {-1|0|1} compare result */ const result = fn.bind(null, arg); - map.set(arg, result); + map.set(/** @type {EXPECTED_OBJECT} */ (arg), result); return result; }; }; @@ -233,7 +234,7 @@ module.exports.compareModulesByIdOrIdentifier = * @param {ChunkGraph} chunkGraph the chunk graph * @param {Chunk} a chunk * @param {Chunk} b chunk - * @returns {-1|0|1} compare result + * @returns {-1 | 0 | 1} compare result */ const compareChunks = (chunkGraph, a, b) => chunkGraph.compareChunks(a, b); /** @type {ParameterizedComparator} */ @@ -241,9 +242,9 @@ module.exports.compareChunks = createCachedParameterizedComparator(compareChunks); /** - * @param {string|number} a first id - * @param {string|number} b second id - * @returns {-1|0|1} compare result + * @param {string | number} a first id + * @param {string | number} b second id + * @returns {-1 | 0 | 1} compare result */ const compareIds = (a, b) => { if (typeof a !== typeof b) { @@ -272,15 +273,15 @@ module.exports.compareStrings = compareStrings; /** * @param {ChunkGroup} a first chunk group * @param {ChunkGroup} b second chunk group - * @returns {-1|0|1} compare result + * @returns {-1 | 0 | 1} compare result */ const compareChunkGroupsByIndex = (a, b) => /** @type {number} */ (a.index) < /** @type {number} */ (b.index) ? -1 : 1; module.exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex; /** - * @template {object} K1 - * @template {object} K2 + * @template {EXPECTED_OBJECT} K1 + * @template {EXPECTED_OBJECT} K2 * @template T */ class TwoKeyWeakMap { diff --git a/lib/util/create-schema-validation.js b/lib/util/create-schema-validation.js index f7b5f1ceb..27a0ab0be 100644 --- a/lib/util/create-schema-validation.js +++ b/lib/util/create-schema-validation.js @@ -23,7 +23,12 @@ const createSchemaValidation = (check, getSchema, options) => { getSchema = memoize(getSchema); return value => { if (check && value && !check(value)) { - getValidate()(getSchema(), value, options); + getValidate()( + getSchema(), + /** @type {EXPECTED_OBJECT | EXPECTED_OBJECT[]} */ + (value), + options + ); require("util").deprecate( () => {}, "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", diff --git a/lib/util/deprecation.js b/lib/util/deprecation.js index 7e947709c..79dc4ae12 100644 --- a/lib/util/deprecation.js +++ b/lib/util/deprecation.js @@ -227,17 +227,17 @@ module.exports.createArrayToSetDeprecationSet = name => { * @param {string} name property name * @param {string} code deprecation code * @param {string} note additional note - * @returns {Proxy} frozen object with deprecation when modifying + * @returns {T} frozen object with deprecation when modifying */ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { const message = `${name} will be frozen in future, all modifications are deprecated.${ note && `\n${note}` }`; - return /** @type {Proxy} */ ( - new Proxy(/** @type {T} */ (obj), { + return /** @type {T} */ ( + new Proxy(obj, { set: util.deprecate( /** - * @param {T} target target + * @param {object} target target * @param {string | symbol} property property * @param {EXPECTED_ANY} value value * @param {EXPECTED_ANY} receiver receiver @@ -250,7 +250,7 @@ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { ), defineProperty: util.deprecate( /** - * @param {T} target target + * @param {object} target target * @param {string | symbol} property property * @param {PropertyDescriptor} descriptor descriptor * @returns {boolean} result @@ -262,7 +262,7 @@ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { ), deleteProperty: util.deprecate( /** - * @param {T} target target + * @param {object} target target * @param {string | symbol} property property * @returns {boolean} result */ @@ -272,7 +272,7 @@ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { ), setPrototypeOf: util.deprecate( /** - * @param {T} target target + * @param {object} target target * @param {EXPECTED_OBJECT | null} proto proto * @returns {boolean} result */ diff --git a/lib/util/makeSerializable.js b/lib/util/makeSerializable.js index 90b60fb3e..39d28fe59 100644 --- a/lib/util/makeSerializable.js +++ b/lib/util/makeSerializable.js @@ -13,7 +13,7 @@ const { register } = require("./serialization"); /** @typedef {{ serialize: (context: ObjectSerializerContext) => void, deserialize: (context: ObjectDeserializerContext) => void }} SerializableClass */ /** * @template {SerializableClass} T - * @typedef {(new (...params: any[]) => T) & { deserialize?: (context: ObjectDeserializerContext) => T }} SerializableClassConstructor + * @typedef {(new (...params: EXPECTED_ANY[]) => T) & { deserialize?: (context: ObjectDeserializerContext) => T }} SerializableClassConstructor */ /** diff --git a/test/cases/errors/import-module-cycle-multiple/loader.js b/test/cases/errors/import-module-cycle-multiple/loader.js index 3d13b9953..b5391becf 100644 --- a/test/cases/errors/import-module-cycle-multiple/loader.js +++ b/test/cases/errors/import-module-cycle-multiple/loader.js @@ -10,7 +10,8 @@ exports.default = function (source) { try { const source = await this.importModule("../loader!" + ref); loadedRefs.push([ref, source]); - } catch(err) { + } catch (_err) { + const err = /** @type {Error} */ (_err); loadedRefs.push([ref, `err: ${err && err.message}`]); } } diff --git a/test/cases/errors/load-module-cycle-multiple/loader.js b/test/cases/errors/load-module-cycle-multiple/loader.js index e91f9dc4b..65389f59e 100644 --- a/test/cases/errors/load-module-cycle-multiple/loader.js +++ b/test/cases/errors/load-module-cycle-multiple/loader.js @@ -17,7 +17,8 @@ exports.default = function (source) { try { const source = await loadModulePromise("../loader!" + ref); loadedRefs.push([ref, JSON.parse(source)]); - } catch(err) { + } catch(_err) { + const err = /** @type {Error} */ (_err); loadedRefs.push([ref, `err: ${err && err.message}`]); } } diff --git a/test/configCases/css/runtime-data-webpack/webpack.config.js b/test/configCases/css/runtime-data-webpack/webpack.config.js index 1bf5d64a3..336fd9f9f 100644 --- a/test/configCases/css/runtime-data-webpack/webpack.config.js +++ b/test/configCases/css/runtime-data-webpack/webpack.config.js @@ -17,7 +17,7 @@ module.exports = { }, assets => { const name = "bundle0.css"; - const code = assets[name].source(); + const code = /** @type {string} */ (assets[name].source()); compilation.updateAsset( name, diff --git a/test/configCases/custom-source-type/localization/webpack.config.js b/test/configCases/custom-source-type/localization/webpack.config.js index 9fdbe5ab1..6b6592d74 100644 --- a/test/configCases/custom-source-type/localization/webpack.config.js +++ b/test/configCases/custom-source-type/localization/webpack.config.js @@ -7,10 +7,11 @@ const webpack = require("../../../../"); /** @typedef {import("../../../../").Compiler} Compiler */ /** @typedef {import("../../../../").ParserState} ParserState */ +/** @typedef {import("../../../../lib/Parser").PreparsedAst} PreparsedAst */ class LocalizationParser extends Parser { /** - * @param {string | Buffer | Record} source input source + * @param {string | Buffer | PreparsedAst} source input source * @param {ParserState} state state * @returns {ParserState} state */ diff --git a/test/configCases/process-assets/update-info/file.svg b/test/configCases/process-assets/update-info/file.svg new file mode 100644 index 000000000..d7b7e40b4 --- /dev/null +++ b/test/configCases/process-assets/update-info/file.svg @@ -0,0 +1 @@ +icon-square-small diff --git a/test/configCases/process-assets/update-info/file1.svg b/test/configCases/process-assets/update-info/file1.svg new file mode 100644 index 000000000..d7b7e40b4 --- /dev/null +++ b/test/configCases/process-assets/update-info/file1.svg @@ -0,0 +1 @@ +icon-square-small diff --git a/test/configCases/process-assets/update-info/index.js b/test/configCases/process-assets/update-info/index.js new file mode 100644 index 000000000..61420f560 --- /dev/null +++ b/test/configCases/process-assets/update-info/index.js @@ -0,0 +1,13 @@ +it("should update info", () => { + const file = new URL("./file.svg", import.meta.url); + expect(/file\.svg$/.test(file)).toBe(true); + const { info } = __STATS__.assets.find(item => item.name === "images/file.svg"); + expect(info.custom).toBe(true); + expect(info.related).toEqual({"first": ["first"], "second": ["second"]}); + expect(info.customFn).toBe(true); + + const file1 = new URL("./file1.svg", import.meta.url); + expect(/file1\.svg$/.test(file1)).toBe(true); + const { info: info1 } = __STATS__.assets.find(item => item.name === "images/file1.svg"); + expect(info1.custom).toBeUndefined(); +}); diff --git a/test/configCases/process-assets/update-info/webpack.config.js b/test/configCases/process-assets/update-info/webpack.config.js new file mode 100644 index 000000000..310bff0d9 --- /dev/null +++ b/test/configCases/process-assets/update-info/webpack.config.js @@ -0,0 +1,49 @@ +/** @type {import("../../../../").Configuration} */ +module.exports = { + output: { + assetModuleFilename: "images/[name][ext]" + }, + plugins: [ + { + apply: compiler => { + compiler.hooks.compilation.tap("TestPlugin", compilation => { + compilation.hooks.processAssets.tap( + { + name: "TestPlugin", + additionalAssets: true + }, + assets => { + for (const asset of Object.keys(assets)) { + switch (asset) { + case "images/file.svg": { + compilation.updateAsset(asset, assets[asset], { + custom: true, + related: { first: ["first"] } + }); + compilation.updateAsset(asset, assets[asset], info => ({ + ...info, + related: { ...info.related, second: ["second"] }, + customFn: true + })); + break; + } + case "images/file1.svg": { + compilation.updateAsset(asset, assets[asset], { + custom: true + }); + compilation.updateAsset( + asset, + assets[asset], + () => undefined + ); + break; + } + } + } + } + ); + }); + } + } + ] +}; diff --git a/test/configCases/rebuild/finishModules/webpack.config.js b/test/configCases/rebuild/finishModules/webpack.config.js index 488d955be..476555d9b 100644 --- a/test/configCases/rebuild/finishModules/webpack.config.js +++ b/test/configCases/rebuild/finishModules/webpack.config.js @@ -1,6 +1,10 @@ const { resolve, join } = require("path"); const { NormalModule } = require("../../../../"); +/** + * @typedef {TODO} Module + */ + /** * @param {import("../../../../").Compiler} compiler the compiler */ @@ -10,7 +14,8 @@ var testPlugin = compiler => { NormalModule.getCompilationHooks(compilation).loader.tap( "TestPlugin", loaderContext => { - /** @type {any} */ (loaderContext).shouldReplace = shouldReplace; + /** @type {any} */ + (loaderContext).shouldReplace = shouldReplace; } ); compilation.hooks.finishModules.tapAsync( @@ -19,7 +24,7 @@ var testPlugin = compiler => { const src = resolve(join(__dirname, "other-file.js")); /** - * @param {any} m test + * @param {Module} m test * @returns {boolean} test */ function matcher(m) { diff --git a/test/configCases/rebuild/rebuildWithNewDependencies/webpack.config.js b/test/configCases/rebuild/rebuildWithNewDependencies/webpack.config.js index e415874aa..d19d05b1f 100644 --- a/test/configCases/rebuild/rebuildWithNewDependencies/webpack.config.js +++ b/test/configCases/rebuild/rebuildWithNewDependencies/webpack.config.js @@ -1,6 +1,10 @@ const { resolve, join } = require("path"); const { NormalModule } = require("../../../../"); +/** + * @typedef {TODO} Module + */ + /** * @param {import("../../../../").Compiler} compiler the compiler */ @@ -10,7 +14,8 @@ var testPlugin = compiler => { NormalModule.getCompilationHooks(compilation).loader.tap( "TestPlugin", loaderContext => { - /** @type {any} */ (loaderContext).shouldReplace = shouldReplace; + /** @type {any} */ + (loaderContext).shouldReplace = shouldReplace; } ); compilation.hooks.finishModules.tapAsync( @@ -19,7 +24,7 @@ var testPlugin = compiler => { const src = resolve(join(__dirname, "a.js")); /** - * @param {any} m test + * @param {Module} m test * @returns {boolean} test */ function matcher(m) { diff --git a/test/configCases/source-map/no-source-map/webpack.config.js b/test/configCases/source-map/no-source-map/webpack.config.js index 23d83012d..385b3de29 100644 --- a/test/configCases/source-map/no-source-map/webpack.config.js +++ b/test/configCases/source-map/no-source-map/webpack.config.js @@ -5,7 +5,8 @@ const plugins = [ const result = asset.source.sourceAndMap(); try { expect(result.map).toBe(null); - } catch (err) { + } catch (_err) { + const err = /** @type {Error} */ (_err); err.message += `\nfor asset ${asset.name}`; throw err; } diff --git a/test/helpers/infrastructureLogErrors.js b/test/helpers/infrastructureLogErrors.js index 58e778b00..d19cb7e33 100644 --- a/test/helpers/infrastructureLogErrors.js +++ b/test/helpers/infrastructureLogErrors.js @@ -14,7 +14,7 @@ const errorsFilter = [PERSISTENCE_CACHE_INVALIDATE_ERROR]; /** * @param {string[]} logs logs - * @param {object} config config + * @param {TODO} config config * @returns {string[]} errors */ module.exports = function filterInfraStructureErrors(logs, config) { diff --git a/test/watchCases/cache/add-defines/webpack.config.js b/test/watchCases/cache/add-defines/webpack.config.js index 6ba676888..02cb9e23c 100644 --- a/test/watchCases/cache/add-defines/webpack.config.js +++ b/test/watchCases/cache/add-defines/webpack.config.js @@ -47,7 +47,8 @@ module.exports = { defines[Number(currentWatchStep.step || 0)] ); plugin.apply( - /** @type {any} */ ({ + /** @type {any} */ + ({ hooks: { compilation: { tap: (name, fn) => { diff --git a/tsconfig.json b/tsconfig.json index 48e5022d9..b6ca80d0a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,7 +7,6 @@ "checkJs": true, "noEmit": true, "strict": true, - "alwaysStrict": true, "types": ["node"], "esModuleInterop": true }, diff --git a/tsconfig.types.json b/tsconfig.types.json index ebdd79075..72cdfefca 100644 --- a/tsconfig.types.json +++ b/tsconfig.types.json @@ -7,7 +7,6 @@ "checkJs": true, "noEmit": true, "strict": true, - "alwaysStrict": true, "types": ["node"], "esModuleInterop": true }, diff --git a/tsconfig.types.test.json b/tsconfig.types.test.json index e6e76890a..a757b01d8 100644 --- a/tsconfig.types.test.json +++ b/tsconfig.types.test.json @@ -6,13 +6,15 @@ "allowJs": true, "checkJs": true, "noEmit": true, - "strict": false, - "noImplicitThis": true, - "alwaysStrict": true, + "strict": true, + "noImplicitAny": false, + "strictNullChecks": false, "types": ["node", "jest"], "esModuleInterop": true }, "include": [ + "declarations.d.ts", + "declarations/*.d.ts", "test/**/webpack.config.js", "test/cases/**/*loader*.js", "test/watchCases/**/*loader*.js", diff --git a/types.d.ts b/types.d.ts index 2b624c452..72446f01e 100644 --- a/types.d.ts +++ b/types.d.ts @@ -115,16 +115,7 @@ declare interface Abortable { signal?: AbortSignal; } declare class AbstractLibraryPlugin { - constructor(__0: { - /** - * name of the plugin - */ - pluginName: string; - /** - * used library type - */ - type: string; - }); + constructor(__0: AbstractLibraryPluginOptions); /** * Apply the plugin @@ -169,6 +160,17 @@ declare class AbstractLibraryPlugin { ): void; static COMMON_LIBRARY_NAME_MESSAGE: string; } +declare interface AbstractLibraryPluginOptions { + /** + * name of the plugin + */ + pluginName: string; + + /** + * used library type + */ + type: string; +} declare interface AdditionalData { [index: string]: any; webpackAST: object; @@ -2187,7 +2189,7 @@ declare class Compilation { newSourceOrFunction: Source | ((source: Source) => Source), assetInfoUpdateOrFunction?: | AssetInfo - | ((assetInfo?: AssetInfo) => AssetInfo) + | ((assetInfo?: AssetInfo) => undefined | AssetInfo) ): void; renameAsset(file: string, newFile: string): void; deleteAsset(file: string): void; @@ -5555,8 +5557,7 @@ declare interface HashedModuleIdsPluginOptions { } declare abstract class HelperRuntimeModule extends RuntimeModule {} declare class HotModuleReplacementPlugin { - constructor(options?: object); - options: object; + constructor(); /** * Apply the plugin @@ -6800,12 +6801,12 @@ declare class JavascriptParser extends Parser { walkImportExpression(expression: ImportExpressionJavascriptParser): void; walkCallExpression(expression: CallExpression): void; walkMemberExpression(expression: MemberExpression): void; - walkMemberExpressionWithExpressionName( - expression: any, + walkMemberExpressionWithExpressionName( + expression: MemberExpression, name: string, rootInfo: string | VariableInfo, members: string[], - onUnhandled?: any + onUnhandled: () => undefined | R ): void; walkThisExpression(expression: ThisExpression): void; walkIdentifier(expression: Identifier): void; @@ -6881,7 +6882,7 @@ declare class JavascriptParser extends Parser { rootInfo: string | VariableInfo | ScopeInfo, getMembers: () => string[] ) => any), - defined: undefined | ((result?: string) => any), + defined: undefined | ((result?: string) => undefined | R), ...args: AsArray ): undefined | R; callHooksForName( @@ -6904,8 +6905,8 @@ declare class JavascriptParser extends Parser { callHooksForNameWithFallback( hookMap: HookMap>, name: string, - fallback: undefined | ((value: string) => any), - defined: undefined | (() => any), + fallback: undefined | ((value: string) => undefined | R), + defined: undefined | (() => R), ...args: AsArray ): undefined | R; inScope( @@ -7756,7 +7757,7 @@ declare interface KnownStatsError { chunkId?: string | number; moduleId?: string | number; moduleTrace?: StatsModuleTraceItem[]; - details?: any; + details?: string; stack?: string; } declare interface KnownStatsFactoryContext { @@ -8383,7 +8384,7 @@ declare interface LoaderPluginLoaderContext { importModule( request: string, options: undefined | ImportModuleOptions, - callback: (err?: null | Error, exports?: any) => any + callback: (err?: null | Error, exports?: ExecuteModuleExports) => any ): void; importModule(request: string, options?: ImportModuleOptions): Promise; } @@ -9210,13 +9211,13 @@ declare class ModuleGraph { setDepthIfLower(module: Module, depth: number): boolean; isAsync(module: Module): boolean; setAsync(module: Module): void; - getMeta(thing?: any): object; - getMetaIfExisting(thing?: any): undefined | object; + getMeta(thing: object): any; + getMetaIfExisting(thing: object): any; freeze(cacheStage?: string): void; unfreeze(): void; - cached( - fn: (moduleGraph: ModuleGraph, ...args: T) => V, - ...args: T + cached( + fn: (moduleGraph: ModuleGraph, ...args: T[]) => V, + ...args: T[] ): V; setModuleMemCaches( moduleMemCaches: Map> @@ -9608,7 +9609,9 @@ declare class MultiCompiler { run: MultiHook>; watchClose: SyncHook<[]>; watchRun: MultiHook>; - infrastructureLog: MultiHook>; + infrastructureLog: MultiHook< + SyncBailHook<[string, string, undefined | any[]], true | void> + >; }>; compilers: Compiler[]; dependencies: WeakMap; @@ -9719,24 +9722,20 @@ declare class NoEmitOnErrorsPlugin { } type Node = false | NodeOptions; declare class NodeEnvironmentPlugin { - constructor(options: { - /** - * infrastructure logging options - */ - infrastructureLogging: InfrastructureLogging; - }); - options: { - /** - * infrastructure logging options - */ - infrastructureLogging: InfrastructureLogging; - }; + constructor(options: NodeEnvironmentPluginOptions); + options: NodeEnvironmentPluginOptions; /** * Apply the plugin */ apply(compiler: Compiler): void; } +declare interface NodeEnvironmentPluginOptions { + /** + * infrastructure logging options + */ + infrastructureLogging: InfrastructureLogging; +} /** * Options object for node compatibility features. @@ -9972,8 +9971,8 @@ declare abstract class NormalModuleFactory extends ModuleFactory { ruleSet: RuleSet; context: string; fs: InputFileSystem; - parserCache: Map>; - generatorCache: Map>; + parserCache: Map>; + generatorCache: Map>; cleanupForCache(): void; resolveResource( contextInfo: ModuleFactoryCreateDataContextInfo, @@ -10163,7 +10162,7 @@ declare interface ObjectSerializerContext { snapshot: () => ObjectSerializerSnapshot; rollback: (snapshot: ObjectSerializerSnapshot) => void; writeLazy?: (item?: any) => void; - writeSeparate?: (item?: any, obj?: object) => () => any; + writeSeparate?: (item?: any, obj?: any) => () => any; } declare interface ObjectSerializerSnapshot { length: number; @@ -11247,7 +11246,7 @@ declare interface OutputNormalized { */ workerWasmLoading?: string | false; } -declare interface ParameterizedComparator { +declare interface ParameterizedComparator { (tArg: TArg): Comparator; } declare interface ParsedIdentifier { @@ -12238,16 +12237,7 @@ declare interface ReadlinkTypes { ): void; } declare class RealContentHashPlugin { - constructor(__0: { - /** - * the hash function to use - */ - hashFunction: string | typeof Hash; - /** - * the hash digest to use - */ - hashDigest: string; - }); + constructor(__0: RealContentHashPluginOptions); /** * Apply the plugin @@ -12257,6 +12247,17 @@ declare class RealContentHashPlugin { compilation: Compilation ): CompilationHooksRealContentHashPlugin; } +declare interface RealContentHashPluginOptions { + /** + * the hash function to use + */ + hashFunction: string | typeof Hash; + + /** + * the hash digest to use + */ + hashDigest?: string; +} declare interface RealDependencyLocation { start: SourcePosition; end?: SourcePosition; @@ -13057,7 +13058,7 @@ declare abstract class Resolver { normalize(path: string): string; } declare interface ResolverCache { - direct: WeakMap; + direct: WeakMap; stringified: Map; } declare abstract class ResolverFactory { @@ -15250,30 +15251,34 @@ type StatsValue = | "detailed"; type Supports = undefined | string; declare class SyncModuleIdsPlugin { - constructor(__0: { - /** - * path to file - */ - path: string; - /** - * context for module names - */ - context?: string; - /** - * selector for modules - */ - test?: (module: Module) => boolean; - /** - * operation mode (defaults to merge) - */ - mode?: "read" | "create" | "merge" | "update"; - }); + constructor(__0: SyncModuleIdsPluginOptions); /** * Apply the plugin */ apply(compiler: Compiler): void; } +declare interface SyncModuleIdsPluginOptions { + /** + * path to file + */ + path: string; + + /** + * context for module names + */ + context?: string; + + /** + * selector for modules + */ + test?: (module: Module) => boolean; + + /** + * operation mode (defaults to merge) + */ + mode?: "read" | "create" | "merge" | "update"; +} declare interface SyntheticDependencyLocation { name: string; index?: number;