fix: no `object` types and less `any` types
Github Actions / lint (push) Has been cancelled Details
Github Actions / basic (push) Has been cancelled Details
Github Actions / validate-legacy-node (push) Has been cancelled Details
Github Actions / unit (push) Has been cancelled Details
Github Actions / integration (10.x, macos-latest, a) (push) Has been cancelled Details
Github Actions / integration (10.x, macos-latest, b) (push) Has been cancelled Details
Github Actions / integration (10.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (10.x, ubuntu-latest, b) (push) Has been cancelled Details
Github Actions / integration (10.x, windows-latest, a) (push) Has been cancelled Details
Github Actions / integration (10.x, windows-latest, b) (push) Has been cancelled Details
Github Actions / integration (12.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (14.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (16.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (18.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (18.x, ubuntu-latest, b) (push) Has been cancelled Details
Github Actions / integration (20.x, macos-latest, a) (push) Has been cancelled Details
Github Actions / integration (20.x, macos-latest, b) (push) Has been cancelled Details
Github Actions / integration (20.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (20.x, ubuntu-latest, b) (push) Has been cancelled Details
Github Actions / integration (20.x, windows-latest, a) (push) Has been cancelled Details
Github Actions / integration (20.x, windows-latest, b) (push) Has been cancelled Details
Github Actions / integration (22.x, macos-latest, a) (push) Has been cancelled Details
Github Actions / integration (22.x, macos-latest, b) (push) Has been cancelled Details
Github Actions / integration (22.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (22.x, ubuntu-latest, b) (push) Has been cancelled Details
Github Actions / integration (22.x, windows-latest, a) (push) Has been cancelled Details
Github Actions / integration (22.x, windows-latest, b) (push) Has been cancelled Details
Github Actions / integration (23.x, ubuntu-latest, a) (push) Has been cancelled Details
Github Actions / integration (23.x, ubuntu-latest, b) (push) Has been cancelled Details
Github Actions / integration (lts/*, ubuntu-latest, a, 1) (push) Has been cancelled Details
Github Actions / integration (lts/*, ubuntu-latest, b, 1) (push) Has been cancelled Details

This commit is contained in:
Alexander Akait 2025-04-02 19:02:22 +03:00 committed by GitHub
parent d3809aee24
commit e911f5296d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
65 changed files with 539 additions and 373 deletions

View File

@ -350,15 +350,15 @@ export default [
comment: comment:
"JsdocBlock:has(JsdocTypeName[value=/^(function|Function)$/])", "JsdocBlock:has(JsdocTypeName[value=/^(function|Function)$/])",
message: 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"
// },
] ]
} }
] ]

View File

@ -297,7 +297,7 @@ const { isSourceEqual } = require("./util/source");
* @property {Record<string, string | string[]>=} related object of pointers to other assets, keyed by type of relation (only points from parent to child) * @property {Record<string, string | string[]>=} related object of pointers to other assets, keyed by type of relation (only points from parent to child)
*/ */
/** @typedef {KnownAssetInfo & Record<string, any>} AssetInfo */ /** @typedef {KnownAssetInfo & Record<string, EXPECTED_ANY>} AssetInfo */
/** @typedef {{ path: string, info: AssetInfo }} InterpolatedPathAndAssetInfo */ /** @typedef {{ path: string, info: AssetInfo }} InterpolatedPathAndAssetInfo */
@ -650,10 +650,9 @@ class Compilation {
* @param {number} stage new stage * @param {number} stage new stage
* @param {() => AsArray<T>} getArgs get old hook function args * @param {() => AsArray<T>} getArgs get old hook function args
* @param {string=} code deprecation code (not deprecated when unset) * @param {string=} code deprecation code (not deprecated when unset)
* @returns {FakeHook<Pick<AsyncSeriesHook<T>, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects * @returns {FakeHook<Pick<AsyncSeriesHook<T>, "tap" | "tapAsync" | "tapPromise" | "name">> | undefined} fake hook which redirects
*/ */
const createProcessAssetsHook = (name, stage, getArgs, code) => { const createProcessAssetsHook = (name, stage, getArgs, code) => {
// @ts-expect-error For better compatibility we will avoid the optional type
if (!this._backCompat && code) return; if (!this._backCompat && code) return;
/** /**
* @param {string} reason reason * @param {string} reason reason
@ -880,36 +879,52 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
beforeChunkAssets: new SyncHook([]), beforeChunkAssets: new SyncHook([]),
// TODO webpack 6 remove // TODO webpack 6 remove
/** @deprecated */ /** @deprecated */
additionalChunkAssets: createProcessAssetsHook( additionalChunkAssets:
"additionalChunkAssets", /** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, (
() => [this.chunks], createProcessAssetsHook(
"DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" "additionalChunkAssets",
), Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
() => [this.chunks],
"DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS"
)
),
// TODO webpack 6 deprecate // TODO webpack 6 deprecate
/** @deprecated */ /** @deprecated */
additionalAssets: createProcessAssetsHook( additionalAssets:
"additionalAssets", /** @type {FakeHook<Pick<AsyncSeriesHook<[]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, (
() => [] createProcessAssetsHook(
), "additionalAssets",
Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
() => []
)
),
// TODO webpack 6 remove // TODO webpack 6 remove
/** @deprecated */ /** @deprecated */
optimizeChunkAssets: createProcessAssetsHook( optimizeChunkAssets:
"optimizeChunkAssets", /** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, (
() => [this.chunks], createProcessAssetsHook(
"DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" "optimizeChunkAssets",
), Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE,
() => [this.chunks],
"DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS"
)
),
// TODO webpack 6 remove // TODO webpack 6 remove
/** @deprecated */ /** @deprecated */
afterOptimizeChunkAssets: createProcessAssetsHook( afterOptimizeChunkAssets:
"afterOptimizeChunkAssets", /** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, (
() => [this.chunks], createProcessAssetsHook(
"DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" "afterOptimizeChunkAssets",
), Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1,
() => [this.chunks],
"DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS"
)
),
// TODO webpack 6 deprecate // TODO webpack 6 deprecate
/** @deprecated */ /** @deprecated */
optimizeAssets: processAssetsHook, optimizeAssets: processAssetsHook,
@ -2350,7 +2365,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
}; };
entryData[target].push(entry); entryData[target].push(entry);
this.entries.set( this.entries.set(
/** @type {NonNullable<EntryOptions["name"]>} */ (name), /** @type {NonNullable<EntryOptions["name"]>} */
(name),
entryData entryData
); );
} else { } else {
@ -2367,7 +2383,10 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
continue; continue;
} }
if (entryData.options[key] === undefined) { if (entryData.options[key] === undefined) {
entryData.options[key] = /** @type {TODO} */ (options[key]); /** @type {TODO} */
(entryData.options)[key] =
/** @type {NonNullable<EntryOptions[keyof EntryOptions]>} */
(options[key]);
} else { } else {
return callback( return callback(
new WebpackError( new WebpackError(
@ -4679,7 +4698,7 @@ This prevents using hashes of each other and should be avoided.`);
/** /**
* @param {string} file file name * @param {string} file file name
* @param {Source | ((source: Source) => Source)} newSourceOrFunction new asset source or function converting old to new * @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( updateAsset(
file, file,

View File

@ -13,6 +13,7 @@ const DelegatedModule = require("./DelegatedModule");
/** @typedef {import("./DelegatedModule").SourceRequest} SourceRequest */ /** @typedef {import("./DelegatedModule").SourceRequest} SourceRequest */
/** @typedef {import("./DelegatedModule").Type} Type */ /** @typedef {import("./DelegatedModule").Type} Type */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** /**
* @typedef {object} Options * @typedef {object} Options
@ -22,7 +23,7 @@ const DelegatedModule = require("./DelegatedModule");
* @property {DllReferencePluginOptions["type"]} type type * @property {DllReferencePluginOptions["type"]} type type
* @property {DllReferencePluginOptions["extensions"]} extensions extensions * @property {DllReferencePluginOptions["extensions"]} extensions extensions
* @property {DllReferencePluginOptions["scope"]} scope scope * @property {DllReferencePluginOptions["scope"]} scope scope
* @property {object=} associatedObjectForCache object for caching * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching
*/ */
class DelegatedModuleFactoryPlugin { class DelegatedModuleFactoryPlugin {

View File

@ -333,11 +333,10 @@ Dependency.NO_EXPORTS_REFERENCED = [];
Dependency.EXPORTS_OBJECT_REFERENCED = [[]]; Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
// TODO remove in webpack 6 // TODO remove in webpack 6
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Dependency.prototype, "module", { Object.defineProperty(Dependency.prototype, "module", {
/** /**
* @deprecated * @deprecated
* @returns {never} throws * @returns {EXPECTED_ANY} throws
*/ */
get() { get() {
throw new Error( throw new Error(
@ -357,8 +356,11 @@ Object.defineProperty(Dependency.prototype, "module", {
}); });
// TODO remove in webpack 6 // TODO remove in webpack 6
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Dependency.prototype, "disconnect", { Object.defineProperty(Dependency.prototype, "disconnect", {
/**
* @deprecated
* @returns {EXPECTED_ANY} throws
*/
get() { get() {
throw new Error( throw new Error(
"disconnect was removed from Dependency (Dependency no longer carries graph specific information)" "disconnect was removed from Dependency (Dependency no longer carries graph specific information)"

View File

@ -18,6 +18,7 @@ const makePathsRelative = require("./util/identifier").makePathsRelative;
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */
/** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Compiler").CompilationParams} CompilationParams */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const validate = createSchemaValidation( const validate = createSchemaValidation(
@ -38,7 +39,7 @@ class DllReferencePlugin {
constructor(options) { constructor(options) {
validate(options); validate(options);
this.options = options; this.options = options;
/** @type {WeakMap<object, CompilationDataItem>} */ /** @type {WeakMap<CompilationParams, CompilationDataItem>} */
this._compilationData = new WeakMap(); this._compilationData = new WeakMap();
} }

View File

@ -167,9 +167,8 @@ class SnapshotIterator {
} }
} }
/** /** @typedef {Map<string, TODO> | Set<string> | undefined} SnapshotMap */
* @typedef {(snapshot: Snapshot) => (Map<string, any> | Set<string> | undefined)[]} GetMapsFunction /** @typedef {(snapshot: Snapshot) => SnapshotMap[]} GetMapsFunction */
*/
class SnapshotIterable { class SnapshotIterable {
/** /**
@ -185,9 +184,9 @@ class SnapshotIterable {
let state = 0; let state = 0;
/** @type {IterableIterator<string>} */ /** @type {IterableIterator<string>} */
let it; let it;
/** @type {(snapshot: Snapshot) => (Map<string, any> | Set<string> | undefined)[]} */ /** @type {GetMapsFunction} */
let getMaps; let getMaps;
/** @type {(Map<string, any> | Set<string> | undefined)[]} */ /** @type {SnapshotMap[]} */
let maps; let maps;
/** @type {Snapshot} */ /** @type {Snapshot} */
let snapshot; let snapshot;
@ -1336,7 +1335,7 @@ class FileSystemInfo {
* @private * @private
* @param {string} path path * @param {string} path path
* @param {string} reason reason * @param {string} reason reason
* @param {any[]} args arguments * @param {EXPECTED_ANY[]} args arguments
*/ */
_log(path, reason, ...args) { _log(path, reason, ...args) {
const key = path + reason; const key = path + reason;

View File

@ -56,7 +56,7 @@ class FlagDependencyUsagePlugin {
/** @type {Map<ExportsInfo, Module>} */ /** @type {Map<ExportsInfo, Module>} */
const exportInfoToModuleMap = new Map(); const exportInfoToModuleMap = new Map();
/** @type {TupleQueue<[Module, RuntimeSpec]>} */ /** @type {TupleQueue<Module, RuntimeSpec>} */
const queue = new TupleQueue(); const queue = new TupleQueue();
/** /**

View File

@ -32,7 +32,7 @@
* @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules * @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 {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 {string} type which kind of code should be generated
* @property {() => Map<string, any>=} getData get access to the code generation data * @property {() => Map<string, TODO>=} getData get access to the code generation data
*/ */
/** /**

View File

@ -96,13 +96,6 @@ class HotModuleReplacementPlugin {
return hooks; return hooks;
} }
/**
* @param {object=} options options
*/
constructor(options) {
this.options = options || {};
}
/** /**
* Apply the plugin * Apply the plugin
* @param {Compiler} compiler the compiler instance * @param {Compiler} compiler the compiler instance

View File

@ -45,6 +45,7 @@ const makeSerializable = require("./util/makeSerializable");
/** @template T @typedef {import("./util/LazySet")<T>} LazySet<T> */ /** @template T @typedef {import("./util/LazySet")<T>} LazySet<T> */
/** @template T @typedef {import("./util/SortableSet")<T>} SortableSet<T> */ /** @template T @typedef {import("./util/SortableSet")<T>} SortableSet<T> */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** /**
@ -93,7 +94,7 @@ const makeSerializable = require("./util/makeSerializable");
/** /**
* @typedef {object} LibIdentOptions * @typedef {object} LibIdentOptions
* @property {string} context absolute context path to which lib ident is relative to * @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"); makeSerializable(Module, "webpack/lib/Module");
// TODO remove in webpack 6 // TODO remove in webpack 6
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Module.prototype, "hasEqualsChunks", { Object.defineProperty(Module.prototype, "hasEqualsChunks", {
/**
* @deprecated
* @returns {EXPECTED_ANY} throw an error
*/
get() { get() {
throw new Error( throw new Error(
"Module.hasEqualsChunks was renamed (use hasEqualChunks instead)" "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)"
@ -1135,8 +1139,11 @@ Object.defineProperty(Module.prototype, "hasEqualsChunks", {
}); });
// TODO remove in webpack 6 // TODO remove in webpack 6
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Module.prototype, "isUsed", { Object.defineProperty(Module.prototype, "isUsed", {
/**
* @deprecated
* @returns {EXPECTED_ANY} throw an error
*/
get() { get() {
throw new Error( throw new Error(
"Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)"
@ -1146,10 +1153,14 @@ Object.defineProperty(Module.prototype, "isUsed", {
// TODO remove in webpack 6 // TODO remove in webpack 6
Object.defineProperty(Module.prototype, "errors", { Object.defineProperty(Module.prototype, "errors", {
/**
* @deprecated
* @returns {WebpackError[]} errors
*/
get: util.deprecate( get: util.deprecate(
/** /**
* @this {Module} * @this {Module}
* @returns {WebpackError[]} array * @returns {WebpackError[]} errors
*/ */
function () { function () {
if (this._errors === undefined) { if (this._errors === undefined) {
@ -1164,10 +1175,14 @@ Object.defineProperty(Module.prototype, "errors", {
// TODO remove in webpack 6 // TODO remove in webpack 6
Object.defineProperty(Module.prototype, "warnings", { Object.defineProperty(Module.prototype, "warnings", {
/**
* @deprecated
* @returns {WebpackError[]} warnings
*/
get: util.deprecate( get: util.deprecate(
/** /**
* @this {Module} * @this {Module}
* @returns {WebpackError[]} array * @returns {WebpackError[]} warnings
*/ */
function () { function () {
if (this._warnings === undefined) { if (this._warnings === undefined) {
@ -1181,13 +1196,19 @@ Object.defineProperty(Module.prototype, "warnings", {
}); });
// TODO remove in webpack 6 // TODO remove in webpack 6
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Module.prototype, "used", { Object.defineProperty(Module.prototype, "used", {
/**
* @deprecated
* @returns {EXPECTED_ANY} throw an error
*/
get() { get() {
throw new Error( throw new Error(
"Module.used was refactored (use ModuleGraph.getUsedExports instead)" "Module.used was refactored (use ModuleGraph.getUsedExports instead)"
); );
}, },
/**
* @param {EXPECTED_ANY} value value
*/
set(value) { set(value) {
throw new Error( throw new Error(
"Module.used was refactored (use ModuleGraph.setUsedExports instead)" "Module.used was refactored (use ModuleGraph.setUsedExports instead)"

View File

@ -16,7 +16,7 @@ const memoize = require("./util/memoize");
/** @typedef {typeof import("./util/Hash")} Hash */ /** @typedef {typeof import("./util/Hash")} Hash */
/** @typedef {string | RegExp | (string | RegExp)[]} Matcher */ /** @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; const ModuleFilenameHelpers = module.exports;

View File

@ -121,6 +121,9 @@ class ModuleGraphModule {
/** @typedef {(moduleGraphConnection: ModuleGraphConnection) => boolean} FilterConnection */ /** @typedef {(moduleGraphConnection: ModuleGraphConnection) => boolean} FilterConnection */
/** @typedef {EXPECTED_OBJECT} MetaKey */
/** @typedef {TODO} Meta */
/** @typedef {Map<Module, WeakTupleMap<any, any>>} ModuleMemCaches */ /** @typedef {Map<Module, WeakTupleMap<any, any>>} ModuleMemCaches */
class ModuleGraph { class ModuleGraph {
@ -136,7 +139,7 @@ class ModuleGraph {
*/ */
this._moduleMap = new Map(); this._moduleMap = new Map();
/** /**
* @type {WeakMap<TODO, object>} * @type {WeakMap<MetaKey, Meta>}
* @private * @private
*/ */
this._metaMap = new WeakMap(); this._metaMap = new WeakMap();
@ -760,21 +763,21 @@ class ModuleGraph {
} }
/** /**
* @param {TODO} thing any thing * @param {MetaKey} thing any thing
* @returns {object} metadata * @returns {Meta} metadata
*/ */
getMeta(thing) { getMeta(thing) {
let meta = this._metaMap.get(thing); let meta = this._metaMap.get(thing);
if (meta === undefined) { if (meta === undefined) {
meta = Object.create(null); 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 * @param {MetaKey} thing any thing
* @returns {object | undefined} metadata * @returns {Meta | undefined} metadata
*/ */
getMetaIfExisting(thing) { getMetaIfExisting(thing) {
return this._metaMap.get(thing); return this._metaMap.get(thing);
@ -794,10 +797,10 @@ class ModuleGraph {
} }
/** /**
* @template {any[]} T * @template T
* @template V * @template V
* @param {(moduleGraph: ModuleGraph, ...args: T) => V} fn computer * @param {(moduleGraph: ModuleGraph, ...args: T[]) => V} fn computer
* @param {T} args arguments * @param {...T} args arguments
* @returns {V} computed value or cached * @returns {V} computed value or cached
*/ */
cached(fn, ...args) { cached(fn, ...args) {

View File

@ -70,7 +70,7 @@ module.exports = class MultiCompiler {
watchClose: new SyncHook([]), watchClose: new SyncHook([]),
/** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */ /** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)),
/** @type {MultiHook<SyncBailHook<[string, string, any[]], true>>} */ /** @type {MultiHook<SyncBailHook<[string, string, EXPECTED_ANY[] | undefined], true | void>>} */
infrastructureLog: new MultiHook( infrastructureLog: new MultiHook(
compilers.map(c => c.hooks.infrastructureLog) compilers.map(c => c.hooks.infrastructureLog)
) )

View File

@ -91,6 +91,7 @@ const memoize = require("./util/memoize");
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./util/createHash").Algorithm} Algorithm */ /** @typedef {import("./util/createHash").Algorithm} Algorithm */
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** /**
* @template T * @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook * @typedef {import("./util/deprecation").FakeHook<T>} FakeHook
@ -139,7 +140,7 @@ const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
/** /**
* @param {string} context absolute context path * @param {string} context absolute context path
* @param {string} source a source 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 * @returns {string} new source path
*/ */
const contextifySourceUrl = (context, source, associatedObjectForCache) => { const contextifySourceUrl = (context, source, associatedObjectForCache) => {
@ -154,7 +155,7 @@ const contextifySourceUrl = (context, source, associatedObjectForCache) => {
/** /**
* @param {string} context absolute context path * @param {string} context absolute context path
* @param {SourceMap} sourceMap a source map * @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 * @returns {SourceMap} new source map
*/ */
const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
@ -536,7 +537,7 @@ class NormalModule extends Module {
* @param {string} name the asset name * @param {string} name the asset name
* @param {string | Buffer} content the content * @param {string | Buffer} content the content
* @param {(string | SourceMap)=} sourceMap an optional source map * @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 * @returns {Source} the created source
*/ */
createSourceForAsset( createSourceForAsset(
@ -838,7 +839,7 @@ class NormalModule extends Module {
* @param {string} context the compilation context * @param {string} context the compilation context
* @param {string | Buffer} content the content * @param {string | Buffer} content the content
* @param {(string | SourceMapSource | null)=} sourceMap an optional source map * @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 * @returns {Source} the created source
*/ */
createSource(context, content, sourceMap, associatedObjectForCache) { createSource(context, content, sourceMap, associatedObjectForCache) {
@ -1017,9 +1018,9 @@ class NormalModule extends Module {
loaderContext._compilation = loaderContext._compilation =
loaderContext._compiler = loaderContext._compiler =
loaderContext._module = loaderContext._module =
// @ts-expect-error avoid memory leaking
loaderContext.fs = loaderContext.fs =
undefined; /** @type {EXPECTED_ANY} */
(undefined);
if (!result) { if (!result) {
/** @type {BuildInfo} */ /** @type {BuildInfo} */

View File

@ -53,6 +53,7 @@ const {
/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ /** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */
/** @typedef {import("./rules/RuleSetCompiler").RuleSetRules} RuleSetRules */ /** @typedef {import("./rules/RuleSetCompiler").RuleSetRules} RuleSetRules */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** @typedef {Pick<RuleSetRule, 'type' | 'sideEffects' | 'parser' | 'generator' | 'resolve' | 'layer'>} ModuleSettings */ /** @typedef {Pick<RuleSetRule, 'type' | 'sideEffects' | 'parser' | 'generator' | 'resolve' | 'layer'>} ModuleSettings */
/** @typedef {Partial<NormalModuleCreateData & { settings: ModuleSettings }>} CreateData */ /** @typedef {Partial<NormalModuleCreateData & { settings: ModuleSettings }>} CreateData */
@ -247,7 +248,7 @@ class NormalModuleFactory extends ModuleFactory {
* @param {InputFileSystem} param.fs file system * @param {InputFileSystem} param.fs file system
* @param {ResolverFactory} param.resolverFactory resolverFactory * @param {ResolverFactory} param.resolverFactory resolverFactory
* @param {ModuleOptions} param.options options * @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 * @param {boolean=} param.layers enable layers
*/ */
constructor({ constructor({
@ -310,9 +311,9 @@ class NormalModuleFactory extends ModuleFactory {
this.fs = fs; this.fs = fs;
this._globalParserOptions = options.parser; this._globalParserOptions = options.parser;
this._globalGeneratorOptions = options.generator; this._globalGeneratorOptions = options.generator;
/** @type {Map<string, WeakMap<object, Parser>>} */ /** @type {Map<string, WeakMap<ParserOptions, Parser>>} */
this.parserCache = new Map(); this.parserCache = new Map();
/** @type {Map<string, WeakMap<object, Generator>>} */ /** @type {Map<string, WeakMap<GeneratorOptions, Generator>>} */
this.generatorCache = new Map(); this.generatorCache = new Map();
/** @type {Set<Module>} */ /** @type {Set<Module>} */
this._restoredUnsafeCacheEntries = new Set(); this._restoredUnsafeCacheEntries = new Set();
@ -625,10 +626,12 @@ class NormalModuleFactory extends ModuleFactory {
settings[/** @type {keyof ModuleSettings} */ (r.type)] !== null settings[/** @type {keyof ModuleSettings} */ (r.type)] !== null
) { ) {
const type = /** @type {keyof ModuleSettings} */ (r.type); const type = /** @type {keyof ModuleSettings} */ (r.type);
settings[type] = cachedCleverMerge(settings[type], r.value); /** @type {TODO} */
(settings)[type] = cachedCleverMerge(settings[type], r.value);
} else { } else {
const type = /** @type {keyof ModuleSettings} */ (r.type); const type = /** @type {keyof ModuleSettings} */ (r.type);
settings[type] = r.value; /** @type {TODO} */
(settings)[type] = r.value;
} }
} }
} }

View File

@ -8,7 +8,7 @@
/** @typedef {import("./Compilation")} Compilation */ /** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./NormalModule")} NormalModule */ /** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {Record<string, any>} PreparsedAst */ /** @typedef {Record<string, EXPECTED_ANY>} PreparsedAst */
/** /**
* @typedef {object} ParserStateBase * @typedef {object} ParserStateBase

View File

@ -32,10 +32,14 @@ const identifierUtils = require("./util/identifier");
* @property {RecordsModules=} modules * @property {RecordsModules=} modules
*/ */
/**
* @typedef {object} RecordIdsPluginOptions
* @property {boolean=} portableIds true, when ids need to be portable
*/
class RecordIdsPlugin { class RecordIdsPlugin {
/** /**
* @param {object} options Options object * @param {RecordIdsPluginOptions} [options] object
* @param {boolean=} options.portableIds true, when ids need to be portable
*/ */
constructor(options) { constructor(options) {
this.options = options || {}; this.options = options || {};

View File

@ -7,10 +7,12 @@
const { contextify } = require("./util/identifier"); const { contextify } = require("./util/identifier");
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
class RequestShortener { class RequestShortener {
/** /**
* @param {string} dir the directory * @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) { constructor(dir, associatedObjectForCache) {
this.contextify = contextify.bindContextCache( this.contextify = contextify.bindContextCache(

View File

@ -20,7 +20,7 @@ const {
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ /** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */
/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ /** @typedef {WebpackResolveOptions & { dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */
/** /**
* @typedef {object} WithOptions * @typedef {object} WithOptions
* @property {(options: Partial<ResolveOptionsWithDependencyType>) => ResolverWithOptions} withOptions create a resolver with additional/different options * @property {(options: Partial<ResolveOptionsWithDependencyType>) => ResolverWithOptions} withOptions create a resolver with additional/different options
@ -29,6 +29,7 @@ const {
/** @typedef {Resolver & WithOptions} ResolverWithOptions */ /** @typedef {Resolver & WithOptions} ResolverWithOptions */
// need to be hoisted on module level for caching identity // need to be hoisted on module level for caching identity
/** @type {ResolveOptionsWithDependencyType} */
const EMPTY_RESOLVE_OPTIONS = {}; const EMPTY_RESOLVE_OPTIONS = {};
/** /**
@ -69,7 +70,7 @@ const convertToResolveOptions = resolveOptionsWithDepType => {
/** /**
* @typedef {object} ResolverCache * @typedef {object} ResolverCache
* @property {WeakMap<object, ResolverWithOptions>} direct * @property {WeakMap<ResolveOptionsWithDependencyType, ResolverWithOptions>} direct
* @property {Map<string, ResolverWithOptions>} stringified * @property {Map<string, ResolverWithOptions>} stringified
*/ */

View File

@ -395,7 +395,7 @@ class WebpackOptionsApply extends OptionsApply {
new RequireJsStuffPlugin().apply(compiler); new RequireJsStuffPlugin().apply(compiler);
} }
new CommonJsPlugin().apply(compiler); new CommonJsPlugin().apply(compiler);
new LoaderPlugin({}).apply(compiler); new LoaderPlugin().apply(compiler);
if (options.node !== false) { if (options.node !== false) {
const NodeStuffPlugin = require("./NodeStuffPlugin"); const NodeStuffPlugin = require("./NodeStuffPlugin");
new NodeStuffPlugin(options.node).apply(compiler); new NodeStuffPlugin(options.node).apply(compiler);

View File

@ -12,10 +12,14 @@ const Cache = require("../Cache");
/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/**
* @typedef {object} MemoryWithGcCachePluginOptions
* @property {number} maxGenerations max generations
*/
class MemoryWithGcCachePlugin { class MemoryWithGcCachePlugin {
/** /**
* @param {object} options Options * @param {MemoryWithGcCachePluginOptions} options options
* @param {number} options.maxGenerations max generations
*/ */
constructor({ maxGenerations }) { constructor({ maxGenerations }) {
this._maxGenerations = maxGenerations; this._maxGenerations = maxGenerations;

View File

@ -272,7 +272,7 @@ const getArguments = (schema = webpackSchema) => {
/** /**
* @param {Schema} schemaPart the current schema * @param {Schema} schemaPart the current schema
* @param {string} schemaPath the current path in the 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 * @param {string | null} inArray if inside of an array, the path to the array
* @returns {number} added arguments * @returns {number} added arguments
*/ */

View File

@ -341,7 +341,7 @@ const mergeTargetProperties = targetProperties => {
keys.add(/** @type {keyof TargetProperties} */ (key)); keys.add(/** @type {keyof TargetProperties} */ (key));
} }
} }
/** @type {object} */ /** @type {TargetProperties} */
const result = {}; const result = {};
for (const key of keys) { for (const key of keys) {
let hasTrue = false; let hasTrue = false;
@ -361,7 +361,7 @@ const mergeTargetProperties = targetProperties => {
/** @type {TargetProperties} */ /** @type {TargetProperties} */
(result)[key] = hasFalse && hasTrue ? null : Boolean(hasTrue); (result)[key] = hasFalse && hasTrue ? null : Boolean(hasTrue);
} }
return /** @type {TargetProperties} */ (result); return result;
}; };
/** /**

View File

@ -283,13 +283,17 @@ const eatUntilSemi = walkCssTokens.eatUntil(";");
const eatUntilLeftCurly = walkCssTokens.eatUntil("{"); const eatUntilLeftCurly = walkCssTokens.eatUntil("{");
const eatSemi = 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 { class CssParser extends Parser {
/** /**
* @param {object} options options * @param {CssParserOptions} [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
*/ */
constructor({ constructor({
defaultMode = "pure", defaultMode = "pure",

View File

@ -71,9 +71,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
* @returns {string[]} the imported id * @returns {string[]} the imported id
*/ */
getIds(moduleGraph) { getIds(moduleGraph) {
return ( return moduleGraph.getMeta(this)[idsSymbol] || this.ids;
/** @type {TODO} */ (moduleGraph.getMeta(this))[idsSymbol] || this.ids
);
} }
/** /**
@ -82,7 +80,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
* @returns {void} * @returns {void}
*/ */
setIds(moduleGraph, ids) { setIds(moduleGraph, ids) {
/** @type {TODO} */ (moduleGraph.getMeta(this))[idsSymbol] = ids; moduleGraph.getMeta(this)[idsSymbol] = ids;
} }
/** /**

View File

@ -120,8 +120,8 @@ class ExportMode {
/** /**
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {TODO} dependencies dependencies * @param {HarmonyExportImportedSpecifierDependency[]} dependencies dependencies
* @param {Dependency=} additionalDependency additional dependency * @param {TODO=} additionalDependency additional dependency
* @returns {{ names: Names, dependencyIndices: DependencyIndices }} result * @returns {{ names: Names, dependencyIndices: DependencyIndices }} result
*/ */
const determineExportAssignments = ( const determineExportAssignments = (
@ -426,10 +426,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
* @returns {Ids} the imported id * @returns {Ids} the imported id
*/ */
getIds(moduleGraph) { getIds(moduleGraph) {
return ( return moduleGraph.getMeta(this)[idsSymbol] || this.ids;
/** @type {TODO} */
(moduleGraph.getMeta(this))[idsSymbol] || this.ids
);
} }
/** /**
@ -438,8 +435,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
* @returns {void} * @returns {void}
*/ */
setIds(moduleGraph, ids) { setIds(moduleGraph, ids) {
/** @type {TODO} */ moduleGraph.getMeta(this)[idsSymbol] = ids;
(moduleGraph.getMeta(this))[idsSymbol] = ids;
} }
/** /**

View File

@ -89,7 +89,7 @@ class HarmonyImportDependency extends ModuleDependency {
*/ */
getImportVar(moduleGraph) { getImportVar(moduleGraph) {
const module = /** @type {Module} */ (moduleGraph.getParentModule(this)); const module = /** @type {Module} */ (moduleGraph.getParentModule(this));
const meta = /** @type {TODO} */ (moduleGraph.getMeta(module)); const meta = moduleGraph.getMeta(module);
let importVarMap = meta.importVarMap; let importVarMap = meta.importVarMap;
if (!importVarMap) meta.importVarMap = importVarMap = new Map(); if (!importVarMap) meta.importVarMap = importVarMap = new Map();
let importVar = importVarMap.get( let importVar = importVarMap.get(

View File

@ -104,7 +104,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
getIds(moduleGraph) { getIds(moduleGraph) {
const meta = moduleGraph.getMetaIfExisting(this); const meta = moduleGraph.getMetaIfExisting(this);
if (meta === undefined) return this.ids; if (meta === undefined) return this.ids;
const ids = meta[/** @type {keyof object} */ (idsSymbol)]; const ids = meta[idsSymbol];
return ids !== undefined ? ids : this.ids; return ids !== undefined ? ids : this.ids;
} }

View File

@ -12,6 +12,7 @@ const LoaderImportDependency = require("./LoaderImportDependency");
/** @typedef {import("../../declarations/LoaderContext").LoaderPluginLoaderContext} LoaderPluginLoaderContext */ /** @typedef {import("../../declarations/LoaderContext").LoaderPluginLoaderContext} LoaderPluginLoaderContext */
/** @typedef {import("../Compilation").DepConstructor} DepConstructor */ /** @typedef {import("../Compilation").DepConstructor} DepConstructor */
/** @typedef {import("../Compilation").ExecuteModuleExports} ExecuteModuleExports */
/** @typedef {import("../Compilation").ExecuteModuleResult} ExecuteModuleResult */ /** @typedef {import("../Compilation").ExecuteModuleResult} ExecuteModuleResult */
/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
@ -20,7 +21,7 @@ const LoaderImportDependency = require("./LoaderImportDependency");
/** /**
* @callback ImportModuleCallback * @callback ImportModuleCallback
* @param {(Error | null)=} err error object * @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 { class LoaderPlugin {
/**
* @param {object} options options
*/
constructor(options = {}) {}
/** /**
* Apply the plugin * Apply the plugin
* @param {Compiler} compiler the compiler instance * @param {Compiler} compiler the compiler instance
@ -150,12 +146,7 @@ class LoaderPlugin {
for (const d of buildDependencies) { for (const d of buildDependencies) {
loaderContext.addBuildDependency(d); loaderContext.addBuildDependency(d);
} }
return callback( return callback(null, source, map, referencedModule);
null,
source,
/** @type {object | null} */ (map),
referencedModule
);
} }
); );
}; };

View File

@ -14,6 +14,7 @@ const numberHash = require("../util/numberHash");
/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {typeof import("../util/Hash")} Hash */ /** @typedef {typeof import("../util/Hash")} Hash */
/** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** /**
* @param {string} str string to hash * @param {string} str string to hash
@ -75,7 +76,7 @@ const shortenLongString = (string, delimiter, hashFunction) => {
/** /**
* @param {Module} module the module * @param {Module} module the module
* @param {string} context context directory * @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 * @returns {string} short module name
*/ */
const getShortModuleName = (module, context, associatedObjectForCache) => { const getShortModuleName = (module, context, associatedObjectForCache) => {
@ -95,7 +96,7 @@ module.exports.getShortModuleName = getShortModuleName;
* @param {Module} module the module * @param {Module} module the module
* @param {string} context context directory * @param {string} context context directory
* @param {string | Hash} hashFunction hash function to use * @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 * @returns {string} long module name
*/ */
const getLongModuleName = ( const getLongModuleName = (
@ -113,7 +114,7 @@ module.exports.getLongModuleName = getLongModuleName;
/** /**
* @param {Module} module the module * @param {Module} module the module
* @param {string} context context directory * @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 * @returns {string} full module name
*/ */
const getFullModuleName = (module, context, associatedObjectForCache) => const getFullModuleName = (module, context, associatedObjectForCache) =>
@ -126,7 +127,7 @@ module.exports.getFullModuleName = getFullModuleName;
* @param {string} context context directory * @param {string} context context directory
* @param {string} delimiter delimiter for names * @param {string} delimiter delimiter for names
* @param {string | Hash} hashFunction hash function to use * @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 * @returns {string} short chunk name
*/ */
const getShortChunkName = ( const getShortChunkName = (
@ -156,7 +157,7 @@ module.exports.getShortChunkName = getShortChunkName;
* @param {string} context context directory * @param {string} context context directory
* @param {string} delimiter delimiter for names * @param {string} delimiter delimiter for names
* @param {string | Hash} hashFunction hash function to use * @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 * @returns {string} short chunk name
*/ */
const getLongChunkName = ( const getLongChunkName = (
@ -189,7 +190,7 @@ module.exports.getLongChunkName = getLongChunkName;
* @param {Chunk} chunk the chunk * @param {Chunk} chunk the chunk
* @param {ChunkGraph} chunkGraph the chunk graph * @param {ChunkGraph} chunkGraph the chunk graph
* @param {string} context context directory * @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 * @returns {string} full chunk name
*/ */
const getFullChunkName = ( const getFullChunkName = (

View File

@ -14,13 +14,17 @@ const { getUsedModuleIdsAndModules } = require("./IdHelpers");
const plugin = "SyncModuleIdsPlugin"; 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 { class SyncModuleIdsPlugin {
/** /**
* @param {object} options options * @param {SyncModuleIdsPluginOptions} 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)
*/ */
constructor({ path, context, test, mode }) { constructor({ path, context, test, mode }) {
this._path = path; this._path = path;

View File

@ -72,7 +72,7 @@ const lazyFunction = factory => {
const fac = memoize(factory); const fac = memoize(factory);
const f = /** @type {any} */ ( const f = /** @type {any} */ (
/** /**
* @param {...any} args args * @param {...EXPECTED_ANY} args args
* @returns {T} result * @returns {T} result
*/ */
(...args) => fac()(...args) (...args) => fac()(...args)

View File

@ -114,71 +114,68 @@ const ALLOWED_MEMBER_TYPES_ALL = 0b11;
const LEGACY_ASSERT_ATTRIBUTES = Symbol("assert"); const LEGACY_ASSERT_ATTRIBUTES = Symbol("assert");
/** /** @type {(BaseParser: typeof AcornParser) => typeof AcornParser} */
* @param {any} Parser parser
* @returns {typeof AcornParser} extender acorn parser
*/
const importAssertions = Parser => const importAssertions = Parser =>
/** @type {typeof AcornParser} */ ( class extends Parser {
/** @type {unknown} */ ( /**
class extends Parser { * @this {TODO}
parseWithClause() { * @returns {ImportAttribute[]} import attributes
/** @type {ImportAttribute[]} */ */
const nodes = []; parseWithClause() {
/** @type {ImportAttribute[]} */
const nodes = [];
const isAssertLegacy = this.value === "assert"; 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<string, boolean>} */
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;
}
if (isAssertLegacy) {
if (!this.eat(tokTypes.name)) {
return nodes; return nodes;
} }
} else if (!this.eat(tokTypes._with)) {
return nodes;
} }
)
); this.expect(tokTypes.braceL);
/** @type {Record<string, boolean>} */
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 // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
const parser = AcornParser.extend(importAssertions); const parser = AcornParser.extend(importAssertions);
@ -276,7 +273,7 @@ class VariableInfo {
/** @typedef {Omit<AcornOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ /** @typedef {Omit<AcornOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */
/** @typedef {symbol} Tag */ /** @typedef {symbol} Tag */
/** @typedef {Record<string, any>} TagData */ /** @typedef {Record<string, TODO>} TagData */
/** /**
* @typedef {object} TagInfo * @typedef {object} TagInfo
@ -1254,7 +1251,8 @@ class JavascriptParser extends Parser {
case "MetaProperty": { case "MetaProperty": {
const res = this.callHooksForName( const res = this.callHooksForName(
this.hooks.evaluateTypeof, this.hooks.evaluateTypeof,
/** @type {string} */ (getRootName(expr.argument)), /** @type {string} */
(getRootName(expr.argument)),
expr expr
); );
if (res !== undefined) return res; if (res !== undefined) return res;
@ -1452,7 +1450,8 @@ class JavascriptParser extends Parser {
return this.callHooksForName( return this.callHooksForName(
this.hooks.evaluateIdentifier, this.hooks.evaluateIdentifier,
/** @type {string} */ (getRootName(metaProperty)), /** @type {string} */
(getRootName(metaProperty)),
metaProperty metaProperty
); );
}); });
@ -2705,9 +2704,8 @@ class JavascriptParser extends Parser {
walkExportDefaultDeclaration(statement) { walkExportDefaultDeclaration(statement) {
this.hooks.export.call(statement); this.hooks.export.call(statement);
if ( if (
/** @type {FunctionDeclaration | ClassDeclaration} */ ( /** @type {FunctionDeclaration | ClassDeclaration} */
statement.declaration (statement.declaration).id &&
).id &&
statement.declaration.type !== "FunctionExpression" && statement.declaration.type !== "FunctionExpression" &&
statement.declaration.type !== "ClassExpression" 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} name name
* @param {string | VariableInfo} rootInfo root info * @param {string | VariableInfo} rootInfo root info
* @param {string[]} members members * @param {string[]} members members
* @param {TODO} onUnhandled on unhandled callback * @param {() => R | undefined} onUnhandled on unhandled callback
*/ */
walkMemberExpressionWithExpressionName( walkMemberExpressionWithExpressionName(
expression, expression,
@ -3815,7 +3814,9 @@ class JavascriptParser extends Parser {
// optimize the case where expression.object is a MemberExpression too. // optimize the case where expression.object is a MemberExpression too.
// we can keep info here when calling walkMemberExpression directly // we can keep info here when calling walkMemberExpression directly
const property = 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); name = name.slice(0, -property.length - 1);
members.pop(); members.pop();
const result = this.callHooksForInfo( const result = this.callHooksForInfo(
@ -3881,8 +3882,8 @@ class JavascriptParser extends Parser {
* @template R * @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {Expression | Super} expr expression info * @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 {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => string[]) => TODO) | undefined} fallback callback when variable in not handled by hooks
* @param {((result?: string) => any) | undefined} defined callback when variable is defined * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
* @param {AsArray<T>} args args for the hook * @param {AsArray<T>} args args for the hook
* @returns {R | undefined} result of hook * @returns {R | undefined} result of hook
*/ */
@ -3951,8 +3952,8 @@ class JavascriptParser extends Parser {
* @template R * @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {ExportedVariableInfo} info variable info * @param {ExportedVariableInfo} info variable info
* @param {((name: string) => any) | undefined} fallback callback when variable in not handled by hooks * @param {((name: string) => TODO) | undefined} fallback callback when variable in not handled by hooks
* @param {((result?: string) => any) | undefined} defined callback when variable is defined * @param {((result?: string) => TODO) | undefined} defined callback when variable is defined
* @param {AsArray<T>} args args for the hook * @param {AsArray<T>} args args for the hook
* @returns {R | undefined} result of hook * @returns {R | undefined} result of hook
*/ */
@ -4001,8 +4002,8 @@ class JavascriptParser extends Parser {
* @template R * @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {string} name key in map * @param {string} name key in map
* @param {((value: string) => any) | undefined} fallback callback when variable in not handled by hooks * @param {((value: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks
* @param {(() => any) | undefined} defined callback when variable is defined * @param {(() => R) | undefined} defined callback when variable is defined
* @param {AsArray<T>} args args for the hook * @param {AsArray<T>} args args for the hook
* @returns {R | undefined} result of hook * @returns {R | undefined} result of hook
*/ */

View File

@ -32,14 +32,18 @@ const COMMON_LIBRARY_NAME_MESSAGE =
* @property {T} options * @property {T} options
*/ */
/**
* @typedef {object} AbstractLibraryPluginOptions
* @property {string} pluginName name of the plugin
* @property {LibraryType} type used library type
*/
/** /**
* @template T * @template T
*/ */
class AbstractLibraryPlugin { class AbstractLibraryPlugin {
/** /**
* @param {object} options options * @param {AbstractLibraryPluginOptions} options options
* @param {string} options.pluginName name of the plugin
* @param {LibraryType} options.type used library type
*/ */
constructor({ pluginName, type }) { constructor({ pluginName, type }) {
this._pluginName = pluginName; this._pluginName = pluginName;

View File

@ -15,10 +15,14 @@ const nodeConsole = require("./nodeConsole");
/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
/**
* @typedef {object} NodeEnvironmentPluginOptions
* @property {InfrastructureLogging} infrastructureLogging infrastructure logging options
*/
class NodeEnvironmentPlugin { class NodeEnvironmentPlugin {
/** /**
* @param {object} options options * @param {NodeEnvironmentPluginOptions} options options
* @param {InfrastructureLogging} options.infrastructureLogging infrastructure logging options
*/ */
constructor(options) { constructor(options) {
this.options = options; this.options = options;

View File

@ -86,6 +86,7 @@ const {
/** @typedef {typeof import("../util/Hash")} HashConstructor */ /** @typedef {typeof import("../util/Hash")} HashConstructor */
/** @typedef {import("../util/concatenate").UsedNames} UsedNames */ /** @typedef {import("../util/concatenate").UsedNames} UsedNames */
/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** /**
@ -614,7 +615,7 @@ class ConcatenatedModule extends Module {
* @param {Set<Module>} modules all modules in the concatenation (including the root module) * @param {Set<Module>} modules all modules in the concatenation (including the root module)
* @param {RuntimeSpec} runtime the runtime * @param {RuntimeSpec} runtime the runtime
* @param {Compilation} compilation the compilation * @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 * @param {string | HashConstructor=} hashFunction hash function to use
* @returns {ConcatenatedModule} the module * @returns {ConcatenatedModule} the module
*/ */
@ -1042,7 +1043,7 @@ class ConcatenatedModule extends Module {
/** /**
* @param {Module} rootModule the root module of the concatenation * @param {Module} rootModule the root module of the concatenation
* @param {Set<Module>} modules all modules in the concatenation (including the root module) * @param {Set<Module>} 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 * @param {string | HashConstructor=} hashFunction hash function to use
* @returns {string} the identifier * @returns {string} the identifier
*/ */

View File

@ -107,6 +107,12 @@ const toCachedSource = source => {
/** @type {WeakMap<Compilation, CompilationHooks>} */ /** @type {WeakMap<Compilation, CompilationHooks>} */
const compilationHooksMap = new 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 { class RealContentHashPlugin {
/** /**
* @param {Compilation} compilation the compilation * @param {Compilation} compilation the compilation
@ -129,9 +135,7 @@ class RealContentHashPlugin {
} }
/** /**
* @param {object} options options object * @param {RealContentHashPluginOptions} options options
* @param {string | Hash} options.hashFunction the hash function to use
* @param {string} options.hashDigest the hash digest to use
*/ */
constructor({ hashFunction, hashDigest }) { constructor({ hashFunction, hashDigest }) {
this._hashFunction = hashFunction; this._hashFunction = hashFunction;

View File

@ -164,7 +164,7 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
* @property {Set<bigint | Chunk>} chunksKeys * @property {Set<bigint | Chunk>} chunksKeys
*/ */
const defaultGetName = /** @type {GetName} */ (() => {}); const defaultGetName = /** @type {TODO} */ (() => {});
const deterministicGroupingForModules = const deterministicGroupingForModules =
/** @type {(options: DeterministicGroupingOptionsForModule) => DeterministicGroupingGroupedItemsForModule[]} */ /** @type {(options: DeterministicGroupingOptionsForModule) => DeterministicGroupingGroupedItemsForModule[]} */

View File

@ -67,7 +67,7 @@ Technically any value can be used.
* @property {() => ObjectSerializerSnapshot} snapshot * @property {() => ObjectSerializerSnapshot} snapshot
* @property {(snapshot: ObjectSerializerSnapshot) => void} rollback * @property {(snapshot: ObjectSerializerSnapshot) => void} rollback
* @property {((item: any) => void)=} writeLazy * @property {((item: any) => void)=} writeLazy
* @property {((item: any, obj?: object) => (() => Promise<any> | any))=} writeSeparate * @property {((item: any, obj?: TODO) => (() => Promise<any> | any))=} writeSeparate
*/ */
/** /**

View File

@ -293,7 +293,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {ChunkId=} chunkId * @property {ChunkId=} chunkId
* @property {string|number=} moduleId * @property {string|number=} moduleId
* @property {StatsModuleTraceItem[]=} moduleTrace * @property {StatsModuleTraceItem[]=} moduleTrace
* @property {any=} details * @property {string=} details
* @property {string=} stack * @property {string=} stack
*/ */
@ -1908,7 +1908,9 @@ const errorsSpaceLimit = (errors, max) => {
const error = errors[i++]; const error = errors[i++];
result.push({ result.push({
...error, ...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 filteredDetails: overLimit
}); });
filtered = errors.length - i; filtered = errors.length - i;

View File

@ -726,7 +726,9 @@ const MODULE_TRACE_DEPENDENCY_PRINTERS = {
"moduleTraceDependency.loc": loc => loc "moduleTraceDependency.loc": loc => loc
}; };
/** @type {Record<string, string | ((item: any) => string)>} */ /**
* @type {Record<string, string | ((item: any) => string)>}
*/
const ITEM_NAMES = { const ITEM_NAMES = {
"compilation.assets[]": "asset", "compilation.assets[]": "asset",
"compilation.modules[]": "module", "compilation.modules[]": "module",

View File

@ -8,21 +8,22 @@
const TupleSet = require("./TupleSet"); const TupleSet = require("./TupleSet");
/** /**
* @template {any[]} T * @template T
* @template V
*/ */
class TupleQueue { class TupleQueue {
/** /**
* @param {Iterable<T>=} items The initial elements. * @param {Iterable<[T, V]>=} items The initial elements.
*/ */
constructor(items) { constructor(items) {
/** /**
* @private * @private
* @type {TupleSet<T>} * @type {TupleSet<[T, V]>}
*/ */
this._set = new TupleSet(items); this._set = new TupleSet(items);
/** /**
* @private * @private
* @type {Iterator<T>} * @type {Iterator<[T, V]>}
*/ */
this._iterator = this._set[Symbol.iterator](); this._iterator = this._set[Symbol.iterator]();
} }
@ -37,7 +38,7 @@ class TupleQueue {
/** /**
* Appends the specified element to this queue. * Appends the specified element to this queue.
* @param {T} item The element to add. * @param {[T, V]} item The element to add.
* @returns {void} * @returns {void}
*/ */
enqueue(...item) { enqueue(...item) {
@ -46,20 +47,20 @@ class TupleQueue {
/** /**
* Retrieves and removes the head of this queue. * 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() { dequeue() {
const result = this._iterator.next(); const result = this._iterator.next();
if (result.done) { if (result.done) {
if (this._set.size > 0) { if (this._set.size > 0) {
this._iterator = this._set[Symbol.iterator](); 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); this._set.delete(...value);
return value; return value;
} }
return; return;
} }
this._set.delete(...result.value); this._set.delete(.../** @type {[T, V]} */ (result.value));
return result.value; return result.value;
} }
} }

View File

@ -6,14 +6,14 @@
"use strict"; "use strict";
/** /**
* @template {any[]} T * @template T
* @template V * @template V
* @typedef {Map<object, WeakTupleMap<T, V>>} M * @typedef {Map<object, WeakTupleMap<T[], V>>} M
*/ */
/** /**
* @template {any[]} T * @template T
* @template V * @template V
* @typedef {WeakMap<object, WeakTupleMap<T, V>>} W * @typedef {WeakMap<object, WeakTupleMap<T[], V>>} W
*/ */
/** /**
@ -32,7 +32,7 @@ class WeakTupleMap {
this.f = 0; this.f = 0;
/** /**
* @private * @private
* @type {any} * @type {V | undefined}
*/ */
this.v = undefined; this.v = undefined;
/** /**
@ -98,7 +98,7 @@ class WeakTupleMap {
for (let i = 0; i < args.length - 1; i++) { for (let i = 0; i < args.length - 1; i++) {
node = node._get(args[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 fn = args[args.length - 1];
const newValue = fn(...args.slice(0, -1)); const newValue = fn(...args.slice(0, -1));
node._setValue(newValue); node._setValue(newValue);
@ -138,7 +138,7 @@ class WeakTupleMap {
} }
/** /**
* @param {any} v value * @param {V} v value
* @private * @private
*/ */
_setValue(v) { _setValue(v) {
@ -152,7 +152,7 @@ class WeakTupleMap {
} }
/** /**
* @param {any} thing thing * @param {EXPECTED_ANY} thing thing
* @returns {WeakTupleMap<T, V> | undefined} thing * @returns {WeakTupleMap<T, V> | undefined} thing
* @private * @private
*/ */
@ -167,7 +167,7 @@ class WeakTupleMap {
/** /**
* @private * @private
* @param {any} thing thing * @param {EXPECTED_ANY} thing thing
* @returns {WeakTupleMap<T, V>} value * @returns {WeakTupleMap<T, V>} value
*/ */
_get(thing) { _get(thing) {

View File

@ -5,9 +5,9 @@
"use strict"; "use strict";
/** @type {WeakMap<object, WeakMap<object, object>>} */ /** @type {WeakMap<TODO, WeakMap<TODO, TODO>>} */
const mergeCache = new WeakMap(); const mergeCache = new WeakMap();
/** @type {WeakMap<object, Map<string, Map<string|number|boolean, object>>>} */ /** @type {WeakMap<TODO, Map<string, Map<string | number | boolean, TODO>>>} */
const setPropertyCache = new WeakMap(); const setPropertyCache = new WeakMap();
const DELETE = Symbol("DELETE"); const DELETE = Symbol("DELETE");
const DYNAMIC_INFO = Symbol("cleverMerge dynamic info"); const DYNAMIC_INFO = Symbol("cleverMerge dynamic info");
@ -44,7 +44,7 @@ const cachedCleverMerge = (first, second) => {
if (prevMerge !== undefined) return prevMerge; if (prevMerge !== undefined) return prevMerge;
const newMerge = _cleverMerge(first, second, true); const newMerge = _cleverMerge(first, second, true);
innerCache.set(second, newMerge); 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 * @property {{ byProperty: string, fn: DynamicFunction } | undefined} dynamic dynamic part
*/ */
/** @type {WeakMap<object, ParsedObject>} */ /** @type {WeakMap<TODO, ParsedObject>} */
const parseCache = new WeakMap(); const parseCache = new WeakMap();
/** /**
* @param {object} obj the object * @template {object} T
* @param {T} obj the object
* @returns {ParsedObject} parsed object * @returns {ParsedObject} parsed object
*/ */
const cachedParseObject = obj => { const cachedParseObject = obj => {
@ -140,7 +141,7 @@ const parseObject = obj => {
for (const key of Object.keys(obj)) { for (const key of Object.keys(obj)) {
if (key.startsWith("by")) { if (key.startsWith("by")) {
const byProperty = /** @type {keyof T} */ (key); const byProperty = /** @type {keyof T} */ (key);
const byObj = /** @type {object} */ (obj[byProperty]); const byObj = /** @type {TODO} */ (obj[byProperty]);
if (typeof byObj === "object") { if (typeof byObj === "object") {
for (const byValue of Object.keys(byObj)) { for (const byValue of Object.keys(byObj)) {
const obj = byObj[/** @type {keyof (keyof T)} */ (byValue)]; 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. * Merges two objects. Objects are deeply clever merged.
* @param {object} first first object * @param {T} first first
* @param {object} second second object * @param {O} second second
* @param {boolean} internalCaching should parsing of objects and nested merges be cached * @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 _cleverMerge = (first, second, internalCaching = false) => {
const firstObject = internalCaching const firstObject = internalCaching
@ -302,9 +305,13 @@ const _cleverMerge = (first, second, internalCaching = false) => {
let { byProperty, fn } = firstDynamicInfo; let { byProperty, fn } = firstDynamicInfo;
const fnInfo = fn[DYNAMIC_INFO]; const fnInfo = fn[DYNAMIC_INFO];
if (fnInfo) { if (fnInfo) {
second = internalCaching second =
? cachedCleverMerge(fnInfo[1], second) /** @type {TODO} */
: cleverMerge(fnInfo[1], second); (
internalCaching
? cachedCleverMerge(fnInfo[1], second)
: cleverMerge(fnInfo[1], second)
);
fn = fnInfo[0]; fn = fnInfo[0];
} }
/** @type {DynamicFunction} */ /** @type {DynamicFunction} */
@ -315,7 +322,9 @@ const _cleverMerge = (first, second, internalCaching = false) => {
: cleverMerge(fnResult, second); : cleverMerge(fnResult, second);
}; };
newFn[DYNAMIC_INFO] = [fn, 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 // 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); resultInfo.set(key, secondEntry);
} }
} }
return serializeObject(resultInfo, secondDynamicInfo); return /** @type {T & O} */ (serializeObject(resultInfo, secondDynamicInfo));
}; };
/** /**

View File

@ -21,26 +21,27 @@ const { compareRuntime } = require("./runtime");
* @typedef {(a: T, b: T) => -1 | 0 | 1} Comparator * @typedef {(a: T, b: T) => -1 | 0 | 1} Comparator
*/ */
/** /**
* @template TArg * @template {object} TArg
* @template T * @template T
* @typedef {(tArg: TArg, a: T, b: T) => -1 | 0 | 1} RawParameterizedComparator * @typedef {(tArg: TArg, a: T, b: T) => -1 | 0 | 1} RawParameterizedComparator
*/ */
/** /**
* @template TArg * @template {object} TArg
* @template T * @template T
* @typedef {(tArg: TArg) => Comparator<T>} ParameterizedComparator * @typedef {(tArg: TArg) => Comparator<T>} ParameterizedComparator
*/ */
/** /**
* @template T * @template {object} TArg
* @param {RawParameterizedComparator<any, T>} fn comparator with argument * @template {object} T
* @returns {ParameterizedComparator<any, T>} comparator * @param {RawParameterizedComparator<TArg, T>} fn comparator with argument
* @returns {ParameterizedComparator<TArg, T>} comparator
*/ */
const createCachedParameterizedComparator = fn => { const createCachedParameterizedComparator = fn => {
/** @type {WeakMap<object, Comparator<T>>} */ /** @type {WeakMap<EXPECTED_OBJECT, Comparator<T>>} */
const map = new WeakMap(); const map = new WeakMap();
return arg => { return arg => {
const cachedResult = map.get(arg); const cachedResult = map.get(/** @type {EXPECTED_OBJECT} */ (arg));
if (cachedResult !== undefined) return cachedResult; if (cachedResult !== undefined) return cachedResult;
/** /**
* @param {T} a first item * @param {T} a first item
@ -48,7 +49,7 @@ const createCachedParameterizedComparator = fn => {
* @returns {-1|0|1} compare result * @returns {-1|0|1} compare result
*/ */
const result = fn.bind(null, arg); const result = fn.bind(null, arg);
map.set(arg, result); map.set(/** @type {EXPECTED_OBJECT} */ (arg), result);
return result; return result;
}; };
}; };
@ -233,7 +234,7 @@ module.exports.compareModulesByIdOrIdentifier =
* @param {ChunkGraph} chunkGraph the chunk graph * @param {ChunkGraph} chunkGraph the chunk graph
* @param {Chunk} a chunk * @param {Chunk} a chunk
* @param {Chunk} b 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); const compareChunks = (chunkGraph, a, b) => chunkGraph.compareChunks(a, b);
/** @type {ParameterizedComparator<ChunkGraph, Chunk>} */ /** @type {ParameterizedComparator<ChunkGraph, Chunk>} */
@ -241,9 +242,9 @@ module.exports.compareChunks =
createCachedParameterizedComparator(compareChunks); createCachedParameterizedComparator(compareChunks);
/** /**
* @param {string|number} a first id * @param {string | number} a first id
* @param {string|number} b second id * @param {string | number} b second id
* @returns {-1|0|1} compare result * @returns {-1 | 0 | 1} compare result
*/ */
const compareIds = (a, b) => { const compareIds = (a, b) => {
if (typeof a !== typeof b) { if (typeof a !== typeof b) {
@ -272,15 +273,15 @@ module.exports.compareStrings = compareStrings;
/** /**
* @param {ChunkGroup} a first chunk group * @param {ChunkGroup} a first chunk group
* @param {ChunkGroup} b second chunk group * @param {ChunkGroup} b second chunk group
* @returns {-1|0|1} compare result * @returns {-1 | 0 | 1} compare result
*/ */
const compareChunkGroupsByIndex = (a, b) => const compareChunkGroupsByIndex = (a, b) =>
/** @type {number} */ (a.index) < /** @type {number} */ (b.index) ? -1 : 1; /** @type {number} */ (a.index) < /** @type {number} */ (b.index) ? -1 : 1;
module.exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex; module.exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex;
/** /**
* @template {object} K1 * @template {EXPECTED_OBJECT} K1
* @template {object} K2 * @template {EXPECTED_OBJECT} K2
* @template T * @template T
*/ */
class TwoKeyWeakMap { class TwoKeyWeakMap {

View File

@ -23,7 +23,12 @@ const createSchemaValidation = (check, getSchema, options) => {
getSchema = memoize(getSchema); getSchema = memoize(getSchema);
return value => { return value => {
if (check && value && !check(value)) { if (check && value && !check(value)) {
getValidate()(getSchema(), value, options); getValidate()(
getSchema(),
/** @type {EXPECTED_OBJECT | EXPECTED_OBJECT[]} */
(value),
options
);
require("util").deprecate( require("util").deprecate(
() => {}, () => {},
"webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.",

View File

@ -227,17 +227,17 @@ module.exports.createArrayToSetDeprecationSet = name => {
* @param {string} name property name * @param {string} name property name
* @param {string} code deprecation code * @param {string} code deprecation code
* @param {string} note additional note * @param {string} note additional note
* @returns {Proxy<T>} frozen object with deprecation when modifying * @returns {T} frozen object with deprecation when modifying
*/ */
module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => {
const message = `${name} will be frozen in future, all modifications are deprecated.${ const message = `${name} will be frozen in future, all modifications are deprecated.${
note && `\n${note}` note && `\n${note}`
}`; }`;
return /** @type {Proxy<T>} */ ( return /** @type {T} */ (
new Proxy(/** @type {T} */ (obj), { new Proxy(obj, {
set: util.deprecate( set: util.deprecate(
/** /**
* @param {T} target target * @param {object} target target
* @param {string | symbol} property property * @param {string | symbol} property property
* @param {EXPECTED_ANY} value value * @param {EXPECTED_ANY} value value
* @param {EXPECTED_ANY} receiver receiver * @param {EXPECTED_ANY} receiver receiver
@ -250,7 +250,7 @@ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => {
), ),
defineProperty: util.deprecate( defineProperty: util.deprecate(
/** /**
* @param {T} target target * @param {object} target target
* @param {string | symbol} property property * @param {string | symbol} property property
* @param {PropertyDescriptor} descriptor descriptor * @param {PropertyDescriptor} descriptor descriptor
* @returns {boolean} result * @returns {boolean} result
@ -262,7 +262,7 @@ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => {
), ),
deleteProperty: util.deprecate( deleteProperty: util.deprecate(
/** /**
* @param {T} target target * @param {object} target target
* @param {string | symbol} property property * @param {string | symbol} property property
* @returns {boolean} result * @returns {boolean} result
*/ */
@ -272,7 +272,7 @@ module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => {
), ),
setPrototypeOf: util.deprecate( setPrototypeOf: util.deprecate(
/** /**
* @param {T} target target * @param {object} target target
* @param {EXPECTED_OBJECT | null} proto proto * @param {EXPECTED_OBJECT | null} proto proto
* @returns {boolean} result * @returns {boolean} result
*/ */

View File

@ -13,7 +13,7 @@ const { register } = require("./serialization");
/** @typedef {{ serialize: (context: ObjectSerializerContext) => void, deserialize: (context: ObjectDeserializerContext) => void }} SerializableClass */ /** @typedef {{ serialize: (context: ObjectSerializerContext) => void, deserialize: (context: ObjectDeserializerContext) => void }} SerializableClass */
/** /**
* @template {SerializableClass} T * @template {SerializableClass} T
* @typedef {(new (...params: any[]) => T) & { deserialize?: (context: ObjectDeserializerContext) => T }} SerializableClassConstructor * @typedef {(new (...params: EXPECTED_ANY[]) => T) & { deserialize?: (context: ObjectDeserializerContext) => T }} SerializableClassConstructor
*/ */
/** /**

View File

@ -10,7 +10,8 @@ exports.default = function (source) {
try { try {
const source = await this.importModule("../loader!" + ref); const source = await this.importModule("../loader!" + ref);
loadedRefs.push([ref, source]); loadedRefs.push([ref, source]);
} catch(err) { } catch (_err) {
const err = /** @type {Error} */ (_err);
loadedRefs.push([ref, `err: ${err && err.message}`]); loadedRefs.push([ref, `err: ${err && err.message}`]);
} }
} }

View File

@ -17,7 +17,8 @@ exports.default = function (source) {
try { try {
const source = await loadModulePromise("../loader!" + ref); const source = await loadModulePromise("../loader!" + ref);
loadedRefs.push([ref, JSON.parse(source)]); loadedRefs.push([ref, JSON.parse(source)]);
} catch(err) { } catch(_err) {
const err = /** @type {Error} */ (_err);
loadedRefs.push([ref, `err: ${err && err.message}`]); loadedRefs.push([ref, `err: ${err && err.message}`]);
} }
} }

View File

@ -17,7 +17,7 @@ module.exports = {
}, },
assets => { assets => {
const name = "bundle0.css"; const name = "bundle0.css";
const code = assets[name].source(); const code = /** @type {string} */ (assets[name].source());
compilation.updateAsset( compilation.updateAsset(
name, name,

View File

@ -7,10 +7,11 @@ const webpack = require("../../../../");
/** @typedef {import("../../../../").Compiler} Compiler */ /** @typedef {import("../../../../").Compiler} Compiler */
/** @typedef {import("../../../../").ParserState} ParserState */ /** @typedef {import("../../../../").ParserState} ParserState */
/** @typedef {import("../../../../lib/Parser").PreparsedAst} PreparsedAst */
class LocalizationParser extends Parser { class LocalizationParser extends Parser {
/** /**
* @param {string | Buffer | Record<string, any>} source input source * @param {string | Buffer | PreparsedAst} source input source
* @param {ParserState} state state * @param {ParserState} state state
* @returns {ParserState} state * @returns {ParserState} state
*/ */

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600"><title>icon-square-small</title><path fill="#FFF" d="M300 .1L565 150v299.9L300 599.8 35 449.9V150z"/><path fill="#8ED6FB" d="M517.7 439.5L308.8 557.8v-92L439 394.1l78.7 45.4zm14.3-12.9V179.4l-76.4 44.1v159l76.4 44.1zM81.5 439.5l208.9 118.2v-92l-130.2-71.6-78.7 45.4zm-14.3-12.9V179.4l76.4 44.1v159l-76.4 44.1zm8.9-263.2L290.4 42.2v89l-137.3 75.5-1.1.6-75.9-43.9zm446.9 0L308.8 42.2v89L446 206.8l1.1.6 75.9-44z"/><path fill="#1C78C0" d="M290.4 444.8L162 374.1V234.2l128.4 74.1v136.5zm18.4 0l128.4-70.6v-140l-128.4 74.1v136.5zM299.6 303zm-129-85l129-70.9L428.5 218l-128.9 74.4-129-74.4z"/></svg>

After

Width:  |  Height:  |  Size: 656 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600"><title>icon-square-small</title><path fill="#FFF" d="M300 .1L565 150v299.9L300 599.8 35 449.9V150z"/><path fill="#8ED6FB" d="M517.7 439.5L308.8 557.8v-92L439 394.1l78.7 45.4zm14.3-12.9V179.4l-76.4 44.1v159l76.4 44.1zM81.5 439.5l208.9 118.2v-92l-130.2-71.6-78.7 45.4zm-14.3-12.9V179.4l76.4 44.1v159l-76.4 44.1zm8.9-263.2L290.4 42.2v89l-137.3 75.5-1.1.6-75.9-43.9zm446.9 0L308.8 42.2v89L446 206.8l1.1.6 75.9-44z"/><path fill="#1C78C0" d="M290.4 444.8L162 374.1V234.2l128.4 74.1v136.5zm18.4 0l128.4-70.6v-140l-128.4 74.1v136.5zM299.6 303zm-129-85l129-70.9L428.5 218l-128.9 74.4-129-74.4z"/></svg>

After

Width:  |  Height:  |  Size: 656 B

View File

@ -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();
});

View File

@ -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;
}
}
}
}
);
});
}
}
]
};

View File

@ -1,6 +1,10 @@
const { resolve, join } = require("path"); const { resolve, join } = require("path");
const { NormalModule } = require("../../../../"); const { NormalModule } = require("../../../../");
/**
* @typedef {TODO} Module
*/
/** /**
* @param {import("../../../../").Compiler} compiler the compiler * @param {import("../../../../").Compiler} compiler the compiler
*/ */
@ -10,7 +14,8 @@ var testPlugin = compiler => {
NormalModule.getCompilationHooks(compilation).loader.tap( NormalModule.getCompilationHooks(compilation).loader.tap(
"TestPlugin", "TestPlugin",
loaderContext => { loaderContext => {
/** @type {any} */ (loaderContext).shouldReplace = shouldReplace; /** @type {any} */
(loaderContext).shouldReplace = shouldReplace;
} }
); );
compilation.hooks.finishModules.tapAsync( compilation.hooks.finishModules.tapAsync(
@ -19,7 +24,7 @@ var testPlugin = compiler => {
const src = resolve(join(__dirname, "other-file.js")); const src = resolve(join(__dirname, "other-file.js"));
/** /**
* @param {any} m test * @param {Module} m test
* @returns {boolean} test * @returns {boolean} test
*/ */
function matcher(m) { function matcher(m) {

View File

@ -1,6 +1,10 @@
const { resolve, join } = require("path"); const { resolve, join } = require("path");
const { NormalModule } = require("../../../../"); const { NormalModule } = require("../../../../");
/**
* @typedef {TODO} Module
*/
/** /**
* @param {import("../../../../").Compiler} compiler the compiler * @param {import("../../../../").Compiler} compiler the compiler
*/ */
@ -10,7 +14,8 @@ var testPlugin = compiler => {
NormalModule.getCompilationHooks(compilation).loader.tap( NormalModule.getCompilationHooks(compilation).loader.tap(
"TestPlugin", "TestPlugin",
loaderContext => { loaderContext => {
/** @type {any} */ (loaderContext).shouldReplace = shouldReplace; /** @type {any} */
(loaderContext).shouldReplace = shouldReplace;
} }
); );
compilation.hooks.finishModules.tapAsync( compilation.hooks.finishModules.tapAsync(
@ -19,7 +24,7 @@ var testPlugin = compiler => {
const src = resolve(join(__dirname, "a.js")); const src = resolve(join(__dirname, "a.js"));
/** /**
* @param {any} m test * @param {Module} m test
* @returns {boolean} test * @returns {boolean} test
*/ */
function matcher(m) { function matcher(m) {

View File

@ -5,7 +5,8 @@ const plugins = [
const result = asset.source.sourceAndMap(); const result = asset.source.sourceAndMap();
try { try {
expect(result.map).toBe(null); expect(result.map).toBe(null);
} catch (err) { } catch (_err) {
const err = /** @type {Error} */ (_err);
err.message += `\nfor asset ${asset.name}`; err.message += `\nfor asset ${asset.name}`;
throw err; throw err;
} }

View File

@ -14,7 +14,7 @@ const errorsFilter = [PERSISTENCE_CACHE_INVALIDATE_ERROR];
/** /**
* @param {string[]} logs logs * @param {string[]} logs logs
* @param {object} config config * @param {TODO} config config
* @returns {string[]} errors * @returns {string[]} errors
*/ */
module.exports = function filterInfraStructureErrors(logs, config) { module.exports = function filterInfraStructureErrors(logs, config) {

View File

@ -47,7 +47,8 @@ module.exports = {
defines[Number(currentWatchStep.step || 0)] defines[Number(currentWatchStep.step || 0)]
); );
plugin.apply( plugin.apply(
/** @type {any} */ ({ /** @type {any} */
({
hooks: { hooks: {
compilation: { compilation: {
tap: (name, fn) => { tap: (name, fn) => {

View File

@ -7,7 +7,6 @@
"checkJs": true, "checkJs": true,
"noEmit": true, "noEmit": true,
"strict": true, "strict": true,
"alwaysStrict": true,
"types": ["node"], "types": ["node"],
"esModuleInterop": true "esModuleInterop": true
}, },

View File

@ -7,7 +7,6 @@
"checkJs": true, "checkJs": true,
"noEmit": true, "noEmit": true,
"strict": true, "strict": true,
"alwaysStrict": true,
"types": ["node"], "types": ["node"],
"esModuleInterop": true "esModuleInterop": true
}, },

View File

@ -6,13 +6,15 @@
"allowJs": true, "allowJs": true,
"checkJs": true, "checkJs": true,
"noEmit": true, "noEmit": true,
"strict": false, "strict": true,
"noImplicitThis": true, "noImplicitAny": false,
"alwaysStrict": true, "strictNullChecks": false,
"types": ["node", "jest"], "types": ["node", "jest"],
"esModuleInterop": true "esModuleInterop": true
}, },
"include": [ "include": [
"declarations.d.ts",
"declarations/*.d.ts",
"test/**/webpack.config.js", "test/**/webpack.config.js",
"test/cases/**/*loader*.js", "test/cases/**/*loader*.js",
"test/watchCases/**/*loader*.js", "test/watchCases/**/*loader*.js",

149
types.d.ts vendored
View File

@ -115,16 +115,7 @@ declare interface Abortable {
signal?: AbortSignal; signal?: AbortSignal;
} }
declare class AbstractLibraryPlugin<T> { declare class AbstractLibraryPlugin<T> {
constructor(__0: { constructor(__0: AbstractLibraryPluginOptions);
/**
* name of the plugin
*/
pluginName: string;
/**
* used library type
*/
type: string;
});
/** /**
* Apply the plugin * Apply the plugin
@ -169,6 +160,17 @@ declare class AbstractLibraryPlugin<T> {
): void; ): void;
static COMMON_LIBRARY_NAME_MESSAGE: string; static COMMON_LIBRARY_NAME_MESSAGE: string;
} }
declare interface AbstractLibraryPluginOptions {
/**
* name of the plugin
*/
pluginName: string;
/**
* used library type
*/
type: string;
}
declare interface AdditionalData { declare interface AdditionalData {
[index: string]: any; [index: string]: any;
webpackAST: object; webpackAST: object;
@ -2187,7 +2189,7 @@ declare class Compilation {
newSourceOrFunction: Source | ((source: Source) => Source), newSourceOrFunction: Source | ((source: Source) => Source),
assetInfoUpdateOrFunction?: assetInfoUpdateOrFunction?:
| AssetInfo | AssetInfo
| ((assetInfo?: AssetInfo) => AssetInfo) | ((assetInfo?: AssetInfo) => undefined | AssetInfo)
): void; ): void;
renameAsset(file: string, newFile: string): void; renameAsset(file: string, newFile: string): void;
deleteAsset(file: string): void; deleteAsset(file: string): void;
@ -5555,8 +5557,7 @@ declare interface HashedModuleIdsPluginOptions {
} }
declare abstract class HelperRuntimeModule extends RuntimeModule {} declare abstract class HelperRuntimeModule extends RuntimeModule {}
declare class HotModuleReplacementPlugin { declare class HotModuleReplacementPlugin {
constructor(options?: object); constructor();
options: object;
/** /**
* Apply the plugin * Apply the plugin
@ -6800,12 +6801,12 @@ declare class JavascriptParser extends Parser {
walkImportExpression(expression: ImportExpressionJavascriptParser): void; walkImportExpression(expression: ImportExpressionJavascriptParser): void;
walkCallExpression(expression: CallExpression): void; walkCallExpression(expression: CallExpression): void;
walkMemberExpression(expression: MemberExpression): void; walkMemberExpression(expression: MemberExpression): void;
walkMemberExpressionWithExpressionName( walkMemberExpressionWithExpressionName<R>(
expression: any, expression: MemberExpression,
name: string, name: string,
rootInfo: string | VariableInfo, rootInfo: string | VariableInfo,
members: string[], members: string[],
onUnhandled?: any onUnhandled: () => undefined | R
): void; ): void;
walkThisExpression(expression: ThisExpression): void; walkThisExpression(expression: ThisExpression): void;
walkIdentifier(expression: Identifier): void; walkIdentifier(expression: Identifier): void;
@ -6881,7 +6882,7 @@ declare class JavascriptParser extends Parser {
rootInfo: string | VariableInfo | ScopeInfo, rootInfo: string | VariableInfo | ScopeInfo,
getMembers: () => string[] getMembers: () => string[]
) => any), ) => any),
defined: undefined | ((result?: string) => any), defined: undefined | ((result?: string) => undefined | R),
...args: AsArray<T> ...args: AsArray<T>
): undefined | R; ): undefined | R;
callHooksForName<T, R>( callHooksForName<T, R>(
@ -6904,8 +6905,8 @@ declare class JavascriptParser extends Parser {
callHooksForNameWithFallback<T, R>( callHooksForNameWithFallback<T, R>(
hookMap: HookMap<SyncBailHook<T, R>>, hookMap: HookMap<SyncBailHook<T, R>>,
name: string, name: string,
fallback: undefined | ((value: string) => any), fallback: undefined | ((value: string) => undefined | R),
defined: undefined | (() => any), defined: undefined | (() => R),
...args: AsArray<T> ...args: AsArray<T>
): undefined | R; ): undefined | R;
inScope( inScope(
@ -7756,7 +7757,7 @@ declare interface KnownStatsError {
chunkId?: string | number; chunkId?: string | number;
moduleId?: string | number; moduleId?: string | number;
moduleTrace?: StatsModuleTraceItem[]; moduleTrace?: StatsModuleTraceItem[];
details?: any; details?: string;
stack?: string; stack?: string;
} }
declare interface KnownStatsFactoryContext { declare interface KnownStatsFactoryContext {
@ -8383,7 +8384,7 @@ declare interface LoaderPluginLoaderContext {
importModule( importModule(
request: string, request: string,
options: undefined | ImportModuleOptions, options: undefined | ImportModuleOptions,
callback: (err?: null | Error, exports?: any) => any callback: (err?: null | Error, exports?: ExecuteModuleExports) => any
): void; ): void;
importModule(request: string, options?: ImportModuleOptions): Promise<any>; importModule(request: string, options?: ImportModuleOptions): Promise<any>;
} }
@ -9210,13 +9211,13 @@ declare class ModuleGraph {
setDepthIfLower(module: Module, depth: number): boolean; setDepthIfLower(module: Module, depth: number): boolean;
isAsync(module: Module): boolean; isAsync(module: Module): boolean;
setAsync(module: Module): void; setAsync(module: Module): void;
getMeta(thing?: any): object; getMeta(thing: object): any;
getMetaIfExisting(thing?: any): undefined | object; getMetaIfExisting(thing: object): any;
freeze(cacheStage?: string): void; freeze(cacheStage?: string): void;
unfreeze(): void; unfreeze(): void;
cached<T extends any[], V>( cached<T, V>(
fn: (moduleGraph: ModuleGraph, ...args: T) => V, fn: (moduleGraph: ModuleGraph, ...args: T[]) => V,
...args: T ...args: T[]
): V; ): V;
setModuleMemCaches( setModuleMemCaches(
moduleMemCaches: Map<Module, WeakTupleMap<any, any>> moduleMemCaches: Map<Module, WeakTupleMap<any, any>>
@ -9608,7 +9609,9 @@ declare class MultiCompiler {
run: MultiHook<AsyncSeriesHook<[Compiler]>>; run: MultiHook<AsyncSeriesHook<[Compiler]>>;
watchClose: SyncHook<[]>; watchClose: SyncHook<[]>;
watchRun: MultiHook<AsyncSeriesHook<[Compiler]>>; watchRun: MultiHook<AsyncSeriesHook<[Compiler]>>;
infrastructureLog: MultiHook<SyncBailHook<[string, string, any[]], true>>; infrastructureLog: MultiHook<
SyncBailHook<[string, string, undefined | any[]], true | void>
>;
}>; }>;
compilers: Compiler[]; compilers: Compiler[];
dependencies: WeakMap<Compiler, string[]>; dependencies: WeakMap<Compiler, string[]>;
@ -9719,24 +9722,20 @@ declare class NoEmitOnErrorsPlugin {
} }
type Node = false | NodeOptions; type Node = false | NodeOptions;
declare class NodeEnvironmentPlugin { declare class NodeEnvironmentPlugin {
constructor(options: { constructor(options: NodeEnvironmentPluginOptions);
/** options: NodeEnvironmentPluginOptions;
* infrastructure logging options
*/
infrastructureLogging: InfrastructureLogging;
});
options: {
/**
* infrastructure logging options
*/
infrastructureLogging: InfrastructureLogging;
};
/** /**
* Apply the plugin * Apply the plugin
*/ */
apply(compiler: Compiler): void; apply(compiler: Compiler): void;
} }
declare interface NodeEnvironmentPluginOptions {
/**
* infrastructure logging options
*/
infrastructureLogging: InfrastructureLogging;
}
/** /**
* Options object for node compatibility features. * Options object for node compatibility features.
@ -9972,8 +9971,8 @@ declare abstract class NormalModuleFactory extends ModuleFactory {
ruleSet: RuleSet; ruleSet: RuleSet;
context: string; context: string;
fs: InputFileSystem; fs: InputFileSystem;
parserCache: Map<string, WeakMap<object, Parser>>; parserCache: Map<string, WeakMap<ParserOptions, Parser>>;
generatorCache: Map<string, WeakMap<object, Generator>>; generatorCache: Map<string, WeakMap<GeneratorOptions, Generator>>;
cleanupForCache(): void; cleanupForCache(): void;
resolveResource( resolveResource(
contextInfo: ModuleFactoryCreateDataContextInfo, contextInfo: ModuleFactoryCreateDataContextInfo,
@ -10163,7 +10162,7 @@ declare interface ObjectSerializerContext {
snapshot: () => ObjectSerializerSnapshot; snapshot: () => ObjectSerializerSnapshot;
rollback: (snapshot: ObjectSerializerSnapshot) => void; rollback: (snapshot: ObjectSerializerSnapshot) => void;
writeLazy?: (item?: any) => void; writeLazy?: (item?: any) => void;
writeSeparate?: (item?: any, obj?: object) => () => any; writeSeparate?: (item?: any, obj?: any) => () => any;
} }
declare interface ObjectSerializerSnapshot { declare interface ObjectSerializerSnapshot {
length: number; length: number;
@ -11247,7 +11246,7 @@ declare interface OutputNormalized {
*/ */
workerWasmLoading?: string | false; workerWasmLoading?: string | false;
} }
declare interface ParameterizedComparator<TArg, T> { declare interface ParameterizedComparator<TArg extends object, T> {
(tArg: TArg): Comparator<T>; (tArg: TArg): Comparator<T>;
} }
declare interface ParsedIdentifier { declare interface ParsedIdentifier {
@ -12238,16 +12237,7 @@ declare interface ReadlinkTypes {
): void; ): void;
} }
declare class RealContentHashPlugin { declare class RealContentHashPlugin {
constructor(__0: { constructor(__0: RealContentHashPluginOptions);
/**
* the hash function to use
*/
hashFunction: string | typeof Hash;
/**
* the hash digest to use
*/
hashDigest: string;
});
/** /**
* Apply the plugin * Apply the plugin
@ -12257,6 +12247,17 @@ declare class RealContentHashPlugin {
compilation: Compilation compilation: Compilation
): CompilationHooksRealContentHashPlugin; ): CompilationHooksRealContentHashPlugin;
} }
declare interface RealContentHashPluginOptions {
/**
* the hash function to use
*/
hashFunction: string | typeof Hash;
/**
* the hash digest to use
*/
hashDigest?: string;
}
declare interface RealDependencyLocation { declare interface RealDependencyLocation {
start: SourcePosition; start: SourcePosition;
end?: SourcePosition; end?: SourcePosition;
@ -13057,7 +13058,7 @@ declare abstract class Resolver {
normalize(path: string): string; normalize(path: string): string;
} }
declare interface ResolverCache { declare interface ResolverCache {
direct: WeakMap<object, ResolverWithOptions>; direct: WeakMap<ResolveOptionsWithDependencyType, ResolverWithOptions>;
stringified: Map<string, ResolverWithOptions>; stringified: Map<string, ResolverWithOptions>;
} }
declare abstract class ResolverFactory { declare abstract class ResolverFactory {
@ -15250,30 +15251,34 @@ type StatsValue =
| "detailed"; | "detailed";
type Supports = undefined | string; type Supports = undefined | string;
declare class SyncModuleIdsPlugin { declare class SyncModuleIdsPlugin {
constructor(__0: { constructor(__0: 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";
});
/** /**
* Apply the plugin * Apply the plugin
*/ */
apply(compiler: Compiler): void; 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 { declare interface SyntheticDependencyLocation {
name: string; name: string;
index?: number; index?: number;