diff --git a/declarations.d.ts b/declarations.d.ts index ea8453ea7..3cbffd71b 100644 --- a/declarations.d.ts +++ b/declarations.d.ts @@ -370,6 +370,12 @@ declare module "watchpack" { } declare module "eslint-scope/lib/referencer" { - class Referencer {} + type Property = import("estree").Property; + type PropertyDefinition = import("estree").PropertyDefinition; + + class Referencer { + Property(node: PropertyDefinition | Property): void; + PropertyDefinition(node: PropertyDefinition): void; + } export = Referencer; } diff --git a/declarations/WebpackOptions.d.ts b/declarations/WebpackOptions.d.ts index 2a784faf1..2339e4d75 100644 --- a/declarations/WebpackOptions.d.ts +++ b/declarations/WebpackOptions.d.ts @@ -82,10 +82,7 @@ export type EntryFilename = FilenameTemplate; */ export type FilenameTemplate = | string - | (( - pathData: import("../lib/Compilation").PathData, - assetInfo?: import("../lib/Compilation").AssetInfo - ) => string); + | import("../lib/TemplatedPathPlugin").TemplatePathFn; /** * Specifies the layer in which modules of this entrypoint are placed. */ @@ -144,10 +141,7 @@ export type PublicPath = "auto" | RawPublicPath; */ export type RawPublicPath = | string - | (( - pathData: import("../lib/Compilation").PathData, - assetInfo?: import("../lib/Compilation").AssetInfo - ) => string); + | import("../lib/TemplatedPathPlugin").TemplatePathFn; /** * The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime. */ @@ -466,10 +460,7 @@ export type OptimizationSplitChunksSizes = */ export type AssetModuleFilename = | string - | (( - pathData: import("../lib/Compilation").PathData, - assetInfo?: import("../lib/Compilation").AssetInfo - ) => string); + | import("../lib/TemplatedPathPlugin").TemplatePathFn; /** * Add charset attribute for script tag. */ @@ -729,10 +720,7 @@ export type WarningFilterTypes = export type WarningFilterItemTypes = | RegExp | string - | (( - warning: import("../lib/stats/DefaultStatsFactoryPlugin").StatsError, - value: string - ) => boolean); + | import("../lib/stats/DefaultStatsPresetPlugin").WarningFilterFn; /** * Environment to build for. An array of environments to build for all of them when possible. */ @@ -764,10 +752,7 @@ export type AssetGeneratorOptions = AssetInlineGeneratorOptions & */ export type AssetModuleOutputPath = | string - | (( - pathData: import("../lib/Compilation").PathData, - assetInfo?: import("../lib/Compilation").AssetInfo - ) => string); + | import("../lib/TemplatedPathPlugin").TemplatePathFn; /** * Function that executes for module and should return whenever asset should be inlined as DataUrl. */ @@ -1901,7 +1886,7 @@ export interface OptimizationSplitChunksOptions { chunks?: | ("initial" | "async" | "all") | RegExp - | ((chunk: import("../lib/Chunk")) => boolean); + | import("../lib/optimize/SplitChunksPlugin").ChunkFilterFn; /** * Sets the size types which are used when a number is used for sizes. */ @@ -1924,7 +1909,7 @@ export interface OptimizationSplitChunksOptions { chunks?: | ("initial" | "async" | "all") | RegExp - | ((chunk: import("../lib/Chunk")) => boolean); + | import("../lib/optimize/SplitChunksPlugin").ChunkFilterFn; /** * Maximal size hint for the on-demand chunks. */ @@ -1949,12 +1934,7 @@ export interface OptimizationSplitChunksOptions { /** * Sets the template for the filename for created chunks. */ - filename?: - | string - | (( - pathData: import("../lib/Compilation").PathData, - assetInfo?: import("../lib/Compilation").AssetInfo - ) => string); + filename?: string | import("../lib/TemplatedPathPlugin").TemplatePathFn; /** * Prevents exposing path info when creating names for parts splitted by maxSize. */ @@ -1998,14 +1978,7 @@ export interface OptimizationSplitChunksOptions { /** * Give chunks created a name (chunks with equal name are merged). */ - name?: - | false - | string - | (( - module: import("../lib/Module"), - chunks: import("../lib/Chunk")[], - key: string - ) => string | undefined); + name?: false | string | import("../lib/optimize/SplitChunksPlugin").GetNameFn; /** * Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal. */ @@ -2025,7 +1998,7 @@ export interface OptimizationSplitChunksCacheGroup { chunks?: | ("initial" | "async" | "all") | RegExp - | ((chunk: import("../lib/Chunk")) => boolean); + | import("../lib/optimize/SplitChunksPlugin").ChunkFilterFn; /** * Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group. */ @@ -2037,12 +2010,7 @@ export interface OptimizationSplitChunksCacheGroup { /** * Sets the template for the filename for created chunks. */ - filename?: - | string - | (( - pathData: import("../lib/Compilation").PathData, - assetInfo?: import("../lib/Compilation").AssetInfo - ) => string); + filename?: string | import("../lib/TemplatedPathPlugin").TemplatePathFn; /** * Sets the hint for chunk id. */ @@ -2090,14 +2058,7 @@ export interface OptimizationSplitChunksCacheGroup { /** * Give chunks for this cache group a name (chunks with equal name are merged). */ - name?: - | false - | string - | (( - module: import("../lib/Module"), - chunks: import("../lib/Chunk")[], - key: string - ) => string | undefined); + name?: false | string | import("../lib/optimize/SplitChunksPlugin").GetNameFn; /** * Priority of this cache group. */ @@ -2361,7 +2322,7 @@ export interface CleanOptions { /** * Keep these assets. */ - keep?: RegExp | string | ((filename: string) => boolean); + keep?: RegExp | string | import("../lib/CleanPlugin").KeepFn; } /** * The abilities of the environment where the webpack generated code should run. @@ -3465,9 +3426,7 @@ export interface JsonParserOptions { /** * Function to parser content and return JSON. */ - parse?: ( - input: string - ) => Buffer | import("../lib/json/JsonParser").JsonValue; + parse?: import("../lib/json/JsonParser").ParseFn; } /** * Options for the default backend. @@ -3496,7 +3455,7 @@ export interface LazyCompilationDefaultBackendOptions { | import("../lib/hmr/lazyCompilationBackend").HttpsServerOptions | import("../lib/hmr/lazyCompilationBackend").HttpServerOptions ) - | (() => import("../lib/hmr/lazyCompilationBackend").Server); + | import("../lib/hmr/lazyCompilationBackend").CreateServerFunction; } /** * Options for compiling entrypoints and import()s only when they are accessed. @@ -3506,18 +3465,7 @@ export interface LazyCompilationOptions { * Specifies the backend that should be used for handling client keep alive. */ backend?: - | ( - | (( - compiler: import("../lib/Compiler"), - callback: ( - err: Error | null, - api?: import("../lib/hmr/LazyCompilationPlugin").BackendApi - ) => void - ) => void) - | (( - compiler: import("../lib/Compiler") - ) => Promise) - ) + | import("../lib/hmr/LazyCompilationPlugin").BackEnd | LazyCompilationDefaultBackendOptions; /** * Enable/disable lazy compilation for entries. @@ -3530,7 +3478,7 @@ export interface LazyCompilationOptions { /** * Specify which entrypoints or import()ed modules should be lazily compiled. This is matched with the imported module and not the entrypoint name. */ - test?: RegExp | string | ((module: import("../lib/Module")) => boolean); + test?: RegExp | string | import("../lib/hmr/LazyCompilationPlugin").TestFn; } /** * Options affecting the normal modules (`NormalModuleFactory`). diff --git a/declarations/plugins/IgnorePlugin.d.ts b/declarations/plugins/IgnorePlugin.d.ts index b298110d7..5d8e042ce 100644 --- a/declarations/plugins/IgnorePlugin.d.ts +++ b/declarations/plugins/IgnorePlugin.d.ts @@ -19,5 +19,5 @@ export type IgnorePluginOptions = /** * A filter function for resource and context. */ - checkResource: (resource: string, context: string) => boolean; + checkResource: import("../../lib/IgnorePlugin").CheckResourceFn; }; diff --git a/declarations/plugins/ProgressPlugin.d.ts b/declarations/plugins/ProgressPlugin.d.ts index f478945f0..8aeb05913 100644 --- a/declarations/plugins/ProgressPlugin.d.ts +++ b/declarations/plugins/ProgressPlugin.d.ts @@ -8,11 +8,7 @@ export type ProgressPluginArgument = ProgressPluginOptions | HandlerFunction; /** * Function that executes for every progress step. */ -export type HandlerFunction = ( - percentage: number, - msg: string, - ...args: string[] -) => void; +export type HandlerFunction = import("../../lib/ProgressPlugin").HandlerFn; /** * Options object for the ProgressPlugin. diff --git a/declarations/plugins/SourceMapDevToolPlugin.d.ts b/declarations/plugins/SourceMapDevToolPlugin.d.ts index b231011d4..d471a20c5 100644 --- a/declarations/plugins/SourceMapDevToolPlugin.d.ts +++ b/declarations/plugins/SourceMapDevToolPlugin.d.ts @@ -20,10 +20,7 @@ export interface SourceMapDevToolPluginOptions { append?: | (false | null) | string - | (( - pathData: import("../../lib/Compilation").PathData, - assetInfo?: import("../../lib/Compilation").AssetInfo - ) => string); + | import("../../lib/TemplatedPathPlugin").TemplatePathFn; /** * Indicates whether column mappings should be used (defaults to true). */ diff --git a/declarations/plugins/schemes/VirtualUrlPlugin.d.ts b/declarations/plugins/schemes/VirtualUrlPlugin.d.ts index f2c92d304..485fcd37d 100644 --- a/declarations/plugins/schemes/VirtualUrlPlugin.d.ts +++ b/declarations/plugins/schemes/VirtualUrlPlugin.d.ts @@ -10,9 +10,7 @@ export type VirtualUrlPluginOptions = VirtualUrlOptions; */ export type VirtualModuleContent = | string - | (( - loaderContext: import("webpack").LoaderContext - ) => Promise | string) + | import("../../../lib/schemes/VirtualUrlPlugin").SourceFn | VirtualModule; /** @@ -37,9 +35,7 @@ export interface VirtualModule { /** * The source function that provides the virtual content. */ - source: ( - loaderContext: import("webpack").LoaderContext - ) => Promise | string; + source: import("../../../lib/schemes/VirtualUrlPlugin").SourceFn; /** * The module type. */ @@ -47,5 +43,8 @@ export interface VirtualModule { /** * Optional version function or value for cache invalidation. */ - version?: true | string | (() => string | undefined); + version?: + | true + | string + | import("../../../lib/schemes/VirtualUrlPlugin").VersionFn; } diff --git a/lib/AsyncDependenciesBlock.js b/lib/AsyncDependenciesBlock.js index afa9f6f32..6c5147be6 100644 --- a/lib/AsyncDependenciesBlock.js +++ b/lib/AsyncDependenciesBlock.js @@ -38,7 +38,7 @@ class AsyncDependenciesBlock extends DependenciesBlock { } /** - * @returns {string | null | undefined} The name of the chunk + * @returns {ChunkGroupOptions["name"]} The name of the chunk */ get chunkName() { return this.groupOptions.name; diff --git a/lib/Chunk.js b/lib/Chunk.js index f5dff15e9..0ff363a37 100644 --- a/lib/Chunk.js +++ b/lib/Chunk.js @@ -31,36 +31,41 @@ const { mergeRuntime } = require("./util/runtime"); /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {string | null} ChunkName */ -/** @typedef {number | string} ChunkId */ +/** @typedef {string | number} ChunkId */ /** @typedef {SortableSet} IdNameHints */ const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files"); /** - * @typedef {object} WithId an object who has an id property * - * @property {string | number} id the id of the object + * @deprecated + * @typedef {object} ChunkMaps + * @property {Record} hash + * @property {Record>} contentHash + * @property {Record} name */ /** * @deprecated - * @typedef {object} ChunkMaps - * @property {Record} hash - * @property {Record>} contentHash - * @property {Record} name + * @typedef {Record} ChunkModuleIdMap + */ + +/** + * @deprecated + * @typedef {Record} chunkModuleHashMap */ /** * @deprecated * @typedef {object} ChunkModuleMaps - * @property {Record} id - * @property {Record} hash + * @property {ChunkModuleIdMap} id + * @property {chunkModuleHashMap} hash */ /** @typedef {Set} Chunks */ /** @typedef {Set} Entrypoints */ /** @typedef {Set} Queue */ /** @typedef {SortableSet} SortableChunkGroups */ -/** @typedef {Record} ChunkChildIdsByOrdersMap */ +/** @typedef {Record} ChunkChildIdsByOrdersMap */ /** @typedef {Record} ChunkChildIdsByOrdersMapByData */ let debugId = 1000; @@ -356,9 +361,9 @@ class Chunk { "Chunk.getChunkModuleMaps", "DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS" ); - /** @type {Record} */ + /** @type {ChunkModuleIdMap} */ const chunkModuleIdMap = Object.create(null); - /** @type {Record} */ + /** @type {chunkModuleHashMap} */ const chunkModuleHashMap = Object.create(null); for (const asyncChunk of this.getAllAsyncChunks()) { @@ -743,7 +748,7 @@ class Chunk { } } } - /** @type {Record} */ + /** @type {Record} */ const result = Object.create(null); for (const [name, list] of lists) { list.sort((a, b) => { diff --git a/lib/ChunkGroup.js b/lib/ChunkGroup.js index f6e48ef80..8cb66d7a0 100644 --- a/lib/ChunkGroup.js +++ b/lib/ChunkGroup.js @@ -113,13 +113,12 @@ class ChunkGroup { * @returns {void} */ addOptions(options) { - for (const _key of Object.keys(options)) { - const key = - /** @type {keyof ChunkGroupOptions} */ - (_key); + for (const key of /** @type {(keyof ChunkGroupOptions)[]} */ ( + Object.keys(options) + )) { if (this.options[key] === undefined) { - /** @type {EXPECTED_ANY} */ - (this.options)[key] = options[key]; + /** @type {ChunkGroupOptions[keyof ChunkGroupOptions]} */ + (this.options[key]) = options[key]; } else if (this.options[key] !== options[key]) { if (key.endsWith("Order")) { const orderKey = @@ -143,7 +142,7 @@ class ChunkGroup { /** * returns the name of current ChunkGroup - * @returns {string | null | undefined} returns the ChunkGroup name + * @returns {ChunkGroupOptions["name"]} returns the ChunkGroup name */ get name() { return this.options.name; diff --git a/lib/CleanPlugin.js b/lib/CleanPlugin.js index 5a43a7dc3..6fb555f4a 100644 --- a/lib/CleanPlugin.js +++ b/lib/CleanPlugin.js @@ -30,7 +30,7 @@ const processAsyncTree = require("./util/processAsyncTree"); /** * @callback KeepFn * @param {string} path path - * @returns {boolean | void} true, if the path should be kept + * @returns {boolean | undefined} true, if the path should be kept */ const validate = createSchemaValidation( @@ -170,7 +170,7 @@ const doStat = (fs, filename, callback) => { * @param {boolean} dry only log instead of fs modification * @param {Logger} logger logger * @param {Diff} diff filenames of the assets that shouldn't be there - * @param {(path: string) => boolean | void} isKept check if the entry is ignored + * @param {KeepFn} isKept check if the entry is ignored * @param {(err?: Error, assets?: Assets) => void} callback callback * @returns {void} */ @@ -436,7 +436,7 @@ class CleanPlugin { /** * @param {string} path path - * @returns {boolean | void} true, if needs to be kept + * @returns {boolean | undefined} true, if needs to be kept */ const isKept = (path) => { const result = hooks.keep.call(path); diff --git a/lib/Compilation.js b/lib/Compilation.js index 487299d0c..c5c28599b 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -108,8 +108,9 @@ const { isSourceEqual } = require("./util/source"); /** @typedef {import("./Compiler").Records} Records */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("./Module").NameForCondition} NameForCondition */ /** @typedef {import("./Module").BuildInfo} BuildInfo */ /** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */ /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ @@ -753,7 +754,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */ succeedEntry: new SyncHook(["entry", "options", "module"]), - /** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */ + /** @type {SyncWaterfallHook<[ReferencedExports, Dependency, RuntimeSpec]>} */ dependencyReferencedExports: new SyncWaterfallHook([ "referencedExports", "dependency", @@ -1195,7 +1196,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si ); /** @type {Record} */ this.childrenCounters = {}; - /** @type {Set | null} */ + /** @type {Set | null} */ this.usedChunkIds = null; /** @type {Set | null} */ this.usedModuleIds = null; @@ -1984,7 +1985,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si { contextInfo: { issuer: originModule - ? /** @type {string} */ (originModule.nameForCondition()) + ? /** @type {NameForCondition} */ (originModule.nameForCondition()) : "", issuerLayer: originModule ? originModule.layer : null, compiler: this.compiler.name, @@ -4144,7 +4145,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o /** * @param {Dependency} dependency the dependency * @param {RuntimeSpec} runtime the runtime - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getDependencyReferencedExports(dependency, runtime) { const referencedExports = dependency.getReferencedExports( diff --git a/lib/Compiler.js b/lib/Compiler.js index ae59a7e87..7fde4b152 100644 --- a/lib/Compiler.js +++ b/lib/Compiler.js @@ -117,7 +117,8 @@ const webpack = require("."); /** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, memCache: MemCache }} ModuleMemCachesItem */ /** - * @param {string[]} array an array + * @template T + * @param {T[]} array an array * @returns {boolean} true, if the array is sorted */ const isSorted = (array) => { diff --git a/lib/ConcatenationScope.js b/lib/ConcatenationScope.js index bfdb0a810..041128ce2 100644 --- a/lib/ConcatenationScope.js +++ b/lib/ConcatenationScope.js @@ -14,13 +14,14 @@ const { /** @typedef {import("./Module")} Module */ /** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */ /** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */ +/** @typedef {import("./optimize/ConcatenatedModule").ExportName} Ids */ const MODULE_REFERENCE_REGEXP = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(_deferredImport)?(?:_asiSafe(\d))?__$/; /** * @typedef {object} ModuleReferenceOptions - * @property {string[]} ids the properties/exports of the module + * @property {Ids} ids the properties/exports of the module * @property {boolean} call true, when this referenced export is called * @property {boolean} directImport true, when this referenced export is directly imported (not via property access) * @property {boolean} deferredImport true, when this referenced export is deferred diff --git a/lib/ContextModule.js b/lib/ContextModule.js index 8fc905d15..f38eac6f5 100644 --- a/lib/ContextModule.js +++ b/lib/ContextModule.js @@ -33,11 +33,13 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */ /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Chunk").ChunkId} ChunkId */ +/** @typedef {import("./Chunk").ChunkName} ChunkName */ /** @typedef {import("./ChunkGraph")} ChunkGraph */ /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ /** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ /** @typedef {import("./Compilation")} Compilation */ /** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").RawReferencedExports} RawReferencedExports */ /** @typedef {import("./Generator").SourceTypes} SourceTypes */ /** @typedef {import("./Module").BuildCallback} BuildCallback */ /** @typedef {import("./Module").BuildInfo} BuildInfo */ @@ -46,6 +48,7 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").LibIdent} LibIdent */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./RequestShortener")} RequestShortener */ @@ -66,13 +69,13 @@ const makeSerializable = require("./util/makeSerializable"); * @property {RegExp | false | null} regExp * @property {"strict" | boolean=} namespaceObject * @property {string=} addon - * @property {string | null=} chunkName + * @property {ChunkName=} chunkName * @property {RegExp | null=} include * @property {RegExp | null=} exclude * @property {RawChunkGroupOptions=} groupOptions * @property {string=} typePrefix * @property {string=} category - * @property {string[][] | null=} referencedExports exports referenced from modules (won't be mangled) + * @property {RawReferencedExports | null=} referencedExports exports referenced from modules (won't be mangled) * @property {string | null=} layer * @property {ImportAttributes=} attributes */ @@ -331,7 +334,7 @@ class ContextModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { let identifier; diff --git a/lib/DelegatedModule.js b/lib/DelegatedModule.js index a6c6ff392..aea91c8b2 100644 --- a/lib/DelegatedModule.js +++ b/lib/DelegatedModule.js @@ -20,17 +20,20 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("./Generator").SourceTypes} SourceTypes */ /** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */ +/** @typedef {import("./Module").ModuleId} ModuleId */ /** @typedef {import("./Module").BuildCallback} BuildCallback */ /** @typedef {import("./Module").BuildMeta} BuildMeta */ /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").LibIdent} LibIdent */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./dependencies/StaticExportsDependency").Exports} Exports */ /** @typedef {import("./util/Hash")} Hash */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ @@ -41,8 +44,8 @@ const makeSerializable = require("./util/makeSerializable"); /** * @typedef {object} DelegatedModuleData * @property {BuildMeta=} buildMeta build meta - * @property {true | string[]=} exports exports - * @property {number | string} id module id + * @property {Exports=} exports exports + * @property {ModuleId} id module id */ const RUNTIME_REQUIREMENTS = new Set([ @@ -82,7 +85,7 @@ class DelegatedModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return typeof this.originalRequest === "string" diff --git a/lib/Dependency.js b/lib/Dependency.js index 290ec04dc..e70ab7c80 100644 --- a/lib/Dependency.js +++ b/lib/Dependency.js @@ -80,6 +80,9 @@ const memoize = require("./util/memoize"); * @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true */ +/** @typedef {string[][]} RawReferencedExports */ +/** @typedef {(string[] | ReferencedExport)[]} ReferencedExports */ + /** @typedef {(moduleGraphConnection: ModuleGraphConnection, runtime: RuntimeSpec) => ConnectionState} GetConditionFn */ const TRANSITIVE = Symbol("transitive"); @@ -227,7 +230,7 @@ class Dependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return Dependency.EXPORTS_OBJECT_REFERENCED; @@ -329,9 +332,9 @@ class Dependency { } } -/** @type {string[][]} */ +/** @type {RawReferencedExports} */ Dependency.NO_EXPORTS_REFERENCED = []; -/** @type {string[][]} */ +/** @type {RawReferencedExports} */ Dependency.EXPORTS_OBJECT_REFERENCED = [[]]; // TODO remove in webpack 6 diff --git a/lib/ExportsInfo.js b/lib/ExportsInfo.js index d86d670e6..24eb26005 100644 --- a/lib/ExportsInfo.js +++ b/lib/ExportsInfo.js @@ -24,15 +24,16 @@ const { forEachRuntime } = require("./util/runtime"); /** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */ /** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */ +/** @typedef {string} ExportInfoName */ + /** @typedef {Map} UsedInRuntime */ -/** @typedef {{ module: Module, export: string[], deferred: boolean }} TargetItemWithoutConnection */ -/** @typedef {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} TargetItemWithConnection */ +/** @typedef {{ module: Module, export: ExportInfoName[], deferred: boolean }} TargetItemWithoutConnection */ +/** @typedef {{ module: Module, connection: ModuleGraphConnection, export: ExportInfoName[] | undefined }} TargetItemWithConnection */ /** @typedef {(target: TargetItemWithConnection) => boolean} ResolveTargetFilter */ /** @typedef {(module: Module) => boolean} ValidTargetModuleFilter */ -/** @typedef {{ connection: ModuleGraphConnection, export: string[], priority: number }} TargetItem */ +/** @typedef {{ connection: ModuleGraphConnection, export: ExportInfoName[], priority: number }} TargetItem */ /** @typedef {Map} Target */ -/** @typedef {string} ExportInfoName */ /** @typedef {string | null} ExportInfoUsedName */ /** @typedef {boolean | null} ExportInfoProvided */ @@ -186,7 +187,7 @@ class ExportsInfo { */ _sortExportsMap(exports) { if (exports.size > 1) { - /** @type {string[]} */ + /** @type {ExportInfoName[]} */ const namesInOrder = []; for (const entry of exports.values()) { namesInOrder.push(entry.name); @@ -520,7 +521,7 @@ class ExportsInfo { /** * @param {RuntimeSpec} runtime the runtime - * @returns {SortableSet | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) + * @returns {SortableSet | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) */ getUsedExports(runtime) { switch (this._otherExportsInfo.getUsed(runtime)) { @@ -532,6 +533,7 @@ class ExportsInfo { return true; } + /** @type {ExportInfoName[]} */ const array = []; if (!this._exportsAreOrdered) this._sortExports(); for (const exportInfo of this._exports.values()) { @@ -563,11 +565,11 @@ class ExportsInfo { return false; } } - return /** @type {SortableSet} */ (new SortableSet(array)); + return /** @type {SortableSet} */ (new SortableSet(array)); } /** - * @returns {null | true | string[]} list of exports when known + * @returns {null | true | ExportInfoName[]} list of exports when known */ getProvidedExports() { switch (this._otherExportsInfo.provided) { @@ -579,7 +581,7 @@ class ExportsInfo { return true; } - /** @type {string[]} */ + /** @type {ExportInfoName[]} */ const array = []; if (!this._exportsAreOrdered) this._sortExports(); for (const exportInfo of this._exports.values()) { @@ -1055,8 +1057,8 @@ class ExportInfo { } } else { let changed = false; - forEachRuntime(runtime, (_runtime) => { - const runtime = /** @type {string} */ (_runtime); + forEachRuntime(runtime, (runtime_) => { + const runtime = /** @type {string} */ (runtime_); const usedInRuntime = /** @type {UsedInRuntime} */ (this._usedInRuntime); @@ -1145,7 +1147,7 @@ class ExportInfo { /** * @param {Dependency} key the key * @param {ModuleGraphConnection} connection the target module if a single one - * @param {(string[] | null)=} exportName the exported name + * @param {ExportInfoName[] | null=} exportName the exported name * @param {number=} priority priority * @returns {boolean} true, if something has changed */ @@ -1155,7 +1157,7 @@ class ExportInfo { this._target = new Map(); this._target.set(key, { connection, - export: /** @type {string[]} */ (exportName), + export: /** @type {ExportInfoName[]} */ (exportName), priority }); return true; @@ -1165,7 +1167,7 @@ class ExportInfo { if (oldTarget === null && !connection) return false; this._target.set(key, { connection, - export: /** @type {string[]} */ (exportName), + export: /** @type {ExportInfoName[]} */ (exportName), priority }); this._maxTarget = undefined; @@ -1179,7 +1181,7 @@ class ExportInfo { : oldTarget.export) ) { oldTarget.connection = connection; - oldTarget.export = /** @type {string[]} */ (exportName); + oldTarget.export = /** @type {ExportInfoName[]} */ (exportName); oldTarget.priority = priority; this._maxTarget = undefined; return true; diff --git a/lib/ExternalModule.js b/lib/ExternalModule.js index 0e2582641..1499ac813 100644 --- a/lib/ExternalModule.js +++ b/lib/ExternalModule.js @@ -45,6 +45,7 @@ const { register } = require("./util/serialization"); /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").LibIdent} LibIdent */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ @@ -87,7 +88,7 @@ const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([ const EMPTY_RUNTIME_REQUIREMENTS = new Set([]); /** - * @param {string|string[]} variableName the variable name or path + * @param {string | string[]} variableName the variable name or path * @param {string} type the module system * @returns {SourceData} the generated source */ @@ -107,8 +108,10 @@ const getSourceForGlobalVariableExternal = (variableName, type) => { }; }; +/** @typedef {string | string[]} ModuleAndSpecifiers */ + /** - * @param {string|string[]} moduleAndSpecifiers the module request + * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request * @returns {SourceData} the generated source */ const getSourceForCommonJsExternal = (moduleAndSpecifiers) => { @@ -144,7 +147,7 @@ const getExternalModuleNodeCommonjsInitFragment = (runtimeTemplate) => { }; /** - * @param {string | string[]} moduleAndSpecifiers the module request + * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request * @param {RuntimeTemplate} runtimeTemplate the runtime template * @returns {SourceData} the generated source */ @@ -173,7 +176,7 @@ const getSourceForCommonJsExternalInNodeModule = ( }; /** - * @param {string|string[]} moduleAndSpecifiers the module request + * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {ImportDependencyMeta=} dependencyMeta the dependency meta * @returns {SourceData} the generated source @@ -423,7 +426,7 @@ const generateModuleRemapping = ( }; /** - * @param {string|string[]} moduleAndSpecifiers the module request + * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request * @param {ExportsInfo} exportsInfo exports info of this module * @param {RuntimeSpec} runtime the runtime * @param {RuntimeTemplate} runtimeTemplate the runtime template @@ -526,7 +529,7 @@ const getSourceForModuleExternal = ( }; /** - * @param {string|string[]} urlAndGlobal the script request + * @param {string | string[]} urlAndGlobal the script request * @param {RuntimeTemplate} runtimeTemplate the runtime template * @returns {SourceData} the generated source */ @@ -576,7 +579,7 @@ const checkExternalVariable = (variableName, request, runtimeTemplate) => /** * @param {ModuleId | string} id the module id * @param {boolean} optional true, if the module is optional - * @param {string|string[]} request the request path + * @param {string | string[]} request the request path * @param {RuntimeTemplate} runtimeTemplate the runtime template * @returns {SourceData} the generated source */ @@ -603,7 +606,7 @@ const getSourceForAmdOrUmdExternal = ( /** * @param {boolean} optional true, if the module is optional - * @param {string|string[]} request the request path + * @param {string | string[]} request the request path * @param {RuntimeTemplate} runtimeTemplate the runtime template * @returns {SourceData} the generated source */ @@ -624,10 +627,11 @@ const getSourceForDefaultCase = (optional, request, runtimeTemplate) => { }; /** @typedef {Record} RequestRecord */ +/** @typedef {string | string[] | RequestRecord} ExternalModuleRequest */ class ExternalModule extends Module { /** - * @param {string | string[] | RequestRecord} request request + * @param {ExternalModuleRequest} request request * @param {string} type type * @param {string} userRequest user request * @param {DependencyMeta=} dependencyMeta dependency meta @@ -636,7 +640,7 @@ class ExternalModule extends Module { super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); // Info from Factory - /** @type {string | string[] | Record} */ + /** @type {ExternalModuleRequest} */ this.request = request; /** @type {string} */ this.externalType = type; @@ -666,7 +670,7 @@ class ExternalModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return this.userRequest; diff --git a/lib/FileSystemInfo.js b/lib/FileSystemInfo.js index 365b4e82c..9e55166be 100644 --- a/lib/FileSystemInfo.js +++ b/lib/FileSystemInfo.js @@ -1212,34 +1212,34 @@ class FileSystemInfo { processor: this._getManagedItemDirectoryInfo.bind(this) }); const _unmanagedPaths = [...unmanagedPaths]; - this.unmanagedPathsWithSlash = - /** @type {string[]} */ - (_unmanagedPaths.filter((p) => typeof p === "string")).map((p) => - join(fs, p, "_").slice(0, -1) - ); - this.unmanagedPathsRegExps = - /** @type {RegExp[]} */ - (_unmanagedPaths.filter((p) => typeof p !== "string")); + /** @type {string[]} */ + this.unmanagedPathsWithSlash = _unmanagedPaths + .filter((p) => typeof p === "string") + .map((p) => join(fs, p, "_").slice(0, -1)); + /** @type {RegExp[]} */ + this.unmanagedPathsRegExps = _unmanagedPaths.filter( + (p) => typeof p !== "string" + ); this.managedPaths = [...managedPaths]; - this.managedPathsWithSlash = - /** @type {string[]} */ - (this.managedPaths.filter((p) => typeof p === "string")).map((p) => - join(fs, p, "_").slice(0, -1) - ); + /** @type {string[]} */ + this.managedPathsWithSlash = this.managedPaths + .filter((p) => typeof p === "string") + .map((p) => join(fs, p, "_").slice(0, -1)); + /** @type {RegExp[]} */ + this.managedPathsRegExps = this.managedPaths.filter( + (p) => typeof p !== "string" + ); - this.managedPathsRegExps = - /** @type {RegExp[]} */ - (this.managedPaths.filter((p) => typeof p !== "string")); this.immutablePaths = [...immutablePaths]; - this.immutablePathsWithSlash = - /** @type {string[]} */ - (this.immutablePaths.filter((p) => typeof p === "string")).map((p) => - join(fs, p, "_").slice(0, -1) - ); - this.immutablePathsRegExps = - /** @type {RegExp[]} */ - (this.immutablePaths.filter((p) => typeof p !== "string")); + /** @type {string[]} */ + this.immutablePathsWithSlash = this.immutablePaths + .filter((p) => typeof p === "string") + .map((p) => join(fs, p, "_").slice(0, -1)); + /** @type {RegExp[]} */ + this.immutablePathsRegExps = this.immutablePaths.filter( + (p) => typeof p !== "string" + ); this._cachedDeprecatedFileTimestamps = undefined; this._cachedDeprecatedContextTimestamps = undefined; diff --git a/lib/FlagDependencyUsagePlugin.js b/lib/FlagDependencyUsagePlugin.js index 565a2c9ce..c49c609fa 100644 --- a/lib/FlagDependencyUsagePlugin.js +++ b/lib/FlagDependencyUsagePlugin.js @@ -16,6 +16,7 @@ const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime"); /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("./ExportsInfo")} ExportsInfo */ /** @typedef {import("./Module")} Module */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ @@ -59,7 +60,7 @@ class FlagDependencyUsagePlugin { /** * @param {Module} module module to process - * @param {(string[] | ReferencedExport)[]} usedExports list of used exports + * @param {ReferencedExports} usedExports list of used exports * @param {RuntimeSpec} runtime part of which runtime * @param {boolean} forceSideEffects always apply side effects * @returns {void} @@ -166,7 +167,7 @@ class FlagDependencyUsagePlugin { * @returns {void} */ const processModule = (module, runtime, forceSideEffects) => { - /** @type {Map>} */ + /** @type {Map>} */ const map = new Map(); /** @type {ArrayQueue} */ diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js index 1bfa4ac71..0eafc406b 100644 --- a/lib/HotModuleReplacementPlugin.js +++ b/lib/HotModuleReplacementPlugin.js @@ -59,10 +59,12 @@ const { /** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {string[]} Requests */ + /** * @typedef {object} HMRJavascriptParserHooks - * @property {SyncBailHook<[Expression | SpreadElement, string[]], void>} hotAcceptCallback - * @property {SyncBailHook<[CallExpression, string[]], void>} hotAcceptWithoutCallback + * @property {SyncBailHook<[Expression | SpreadElement, Requests], void>} hotAcceptCallback + * @property {SyncBailHook<[CallExpression, Requests], void>} hotAcceptWithoutCallback */ /** @typedef {number} HotIndex */ @@ -147,7 +149,7 @@ class HotModuleReplacementPlugin { /** @type {BasicEvaluatedExpression[]} */ (arg.items).filter((param) => param.isString()); } - /** @type {string[]} */ + /** @type {Requests} */ const requests = []; if (params.length > 0) { for (const [idx, param] of params.entries()) { @@ -555,7 +557,7 @@ class HotModuleReplacementPlugin { } // List of completely removed modules - /** @type {Set} */ + /** @type {Set} */ const completelyRemovedModules = new Set(); for (const key of Object.keys(records.chunkHashes)) { diff --git a/lib/IgnorePlugin.js b/lib/IgnorePlugin.js index 75a956430..0bbf18726 100644 --- a/lib/IgnorePlugin.js +++ b/lib/IgnorePlugin.js @@ -23,6 +23,8 @@ const validate = createSchemaValidation( } ); +/** @typedef {(resource: string, context: string) => boolean} CheckResourceFn */ + const PLUGIN_NAME = "IgnorePlugin"; class IgnorePlugin { diff --git a/lib/LibManifestPlugin.js b/lib/LibManifestPlugin.js index a55b2d379..eecf95853 100644 --- a/lib/LibManifestPlugin.js +++ b/lib/LibManifestPlugin.js @@ -15,12 +15,13 @@ const { dirname, mkdirp } = require("./util/fs"); /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */ /** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */ /** * @typedef {object} ManifestModuleData - * @property {string | number} id + * @property {ModuleId} id * @property {BuildMeta=} buildMeta - * @property {boolean | string[]=} exports + * @property {ExportInfoName[]=} exports */ /** diff --git a/lib/Module.js b/lib/Module.js index 73a2259e5..75f092fc6 100644 --- a/lib/Module.js +++ b/lib/Module.js @@ -34,6 +34,7 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */ /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ /** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */ +/** @typedef {import("./ModuleGraph").OptimizationBailouts} OptimizationBailouts */ /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ @@ -201,6 +202,9 @@ const deprecatedNeedRebuild = util.deprecate( "DEP_WEBPACK_MODULE_NEED_REBUILD" ); +/** @typedef {string} LibIdent */ +/** @typedef {string} NameForCondition */ + /** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ class Module extends DependenciesBlock { @@ -420,7 +424,7 @@ class Module extends DependenciesBlock { /** * @deprecated - * @returns {(string | OptimizationBailoutFunction)[]} list + * @returns {OptimizationBailouts} list */ get optimizationBailout() { return ModuleGraph.getModuleGraphForModule( @@ -975,14 +979,14 @@ class Module extends DependenciesBlock { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return null; } /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path) */ nameForCondition() { return null; diff --git a/lib/ModuleGraph.js b/lib/ModuleGraph.js index a719460b0..6e591ba72 100644 --- a/lib/ModuleGraph.js +++ b/lib/ModuleGraph.js @@ -17,6 +17,7 @@ const { sortWithSourceOrder } = require("./util/comparators"); /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("./Module")} Module */ /** @typedef {import("./ModuleProfile")} ModuleProfile */ /** @typedef {import("./RequestShortener")} RequestShortener */ @@ -82,6 +83,8 @@ const getConnectionsByModule = (set) => /** @typedef {SortableSet} IncomingConnections */ /** @typedef {SortableSet} OutgoingConnections */ +/** @typedef {Module | null | undefined} Issuer */ +/** @typedef {(string | OptimizationBailoutFunction)[]} OptimizationBailouts */ class ModuleGraphModule { constructor() { @@ -89,9 +92,9 @@ class ModuleGraphModule { this.incomingConnections = new SortableSet(); /** @type {OutgoingConnections | undefined} */ this.outgoingConnections = undefined; - /** @type {Module | null | undefined} */ + /** @type {Issuer} */ this.issuer = undefined; - /** @type {(string | OptimizationBailoutFunction)[]} */ + /** @type {OptimizationBailouts} */ this.optimizationBailout = []; /** @type {ExportsInfo} */ this.exports = new ExportsInfo(); @@ -617,7 +620,7 @@ class ModuleGraph { /** * @param {Module} module the module - * @returns {Module | null | undefined} the issuer module + * @returns {Issuer} the issuer module */ getIssuer(module) { const mgm = this._getModuleGraphModule(module); @@ -646,7 +649,7 @@ class ModuleGraph { /** * @param {Module} module the module - * @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts + * @returns {OptimizationBailouts} optimization bailouts */ getOptimizationBailout(module) { const mgm = this._getModuleGraphModule(module); @@ -655,7 +658,7 @@ class ModuleGraph { /** * @param {Module} module the module - * @returns {true | string[] | null} the provided exports + * @returns {null | true | ExportInfoName[]} the provided exports */ getProvidedExports(module) { const mgm = this._getModuleGraphModule(module); @@ -664,7 +667,7 @@ class ModuleGraph { /** * @param {Module} module the module - * @param {string | string[]} exportName a name of an export + * @param {ExportInfoName | ExportInfoName[]} exportName a name of an export * @returns {boolean | null} true, if the export is provided by the module. * null, if it's unknown. * false, if it's not provided. diff --git a/lib/NormalModule.js b/lib/NormalModule.js index ff6ba0f81..12894448d 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -73,6 +73,8 @@ const memoize = require("./util/memoize"); /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").LibIdent} LibIdent */ +/** @typedef {import("./Module").NameForCondition} NameForCondition */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").BuildCallback} BuildCallback */ @@ -222,14 +224,16 @@ makeSerializable( /** @typedef {[string | Buffer, string | RawSourceMap | undefined, PreparsedAst | undefined]} Result */ +/** @typedef {LoaderContext} AnyLoaderContext */ + /** * @typedef {object} NormalModuleCompilationHooks - * @property {SyncHook<[LoaderContext, NormalModule]>} loader - * @property {SyncHook<[LoaderItem[], NormalModule, LoaderContext]>} beforeLoaders + * @property {SyncHook<[AnyLoaderContext, NormalModule]>} loader + * @property {SyncHook<[LoaderItem[], NormalModule, AnyLoaderContext]>} beforeLoaders * @property {SyncHook<[NormalModule]>} beforeParse * @property {SyncHook<[NormalModule]>} beforeSnapshot * @property {HookMap>>} readResourceForScheme - * @property {HookMap], string | Buffer | null>>} readResource + * @property {HookMap>} readResource * @property {SyncWaterfallHook<[Result, NormalModule]>} processResult * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild */ @@ -255,7 +259,7 @@ makeSerializable( */ /** - * @typedef {(resourcePath: string, getLoaderContext: (resourcePath: string) => LoaderContext) => Promise>} ReadResource + * @typedef {(resourcePath: string, getLoaderContext: (resourcePath: string) => AnyLoaderContext) => Promise>} ReadResource */ /** @type {WeakMap} */ @@ -438,7 +442,7 @@ class NormalModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { let ident = contextify( @@ -451,7 +455,7 @@ class NormalModule extends Module { } /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path) */ nameForCondition() { const resource = /** @type {string} */ (this.getResource()); @@ -600,7 +604,8 @@ class NormalModule extends Module { const { requestShortener } = compilation.runtimeTemplate; const getCurrentLoaderName = () => { const currentLoader = this.getCurrentLoader( - /** @type {LoaderContext} */ (loaderContext) + /** @type {AnyLoaderContext} */ + (loaderContext) ); if (!currentLoader) return "(not in loader scope)"; return requestShortener.shorten(currentLoader.loader); @@ -611,21 +616,18 @@ class NormalModule extends Module { const getResolveContext = () => ({ fileDependencies: { add: (d) => - /** @type {LoaderContext} */ ( - loaderContext - ).addDependency(d) + /** @type {AnyLoaderContext} */ + (loaderContext).addDependency(d) }, contextDependencies: { add: (d) => - /** @type {LoaderContext} */ ( - loaderContext - ).addContextDependency(d) + /** @type {AnyLoaderContext} */ + (loaderContext).addContextDependency(d) }, missingDependencies: { add: (d) => - /** @type {LoaderContext} */ ( - loaderContext - ).addMissingDependency(d) + /** @type {AnyLoaderContext} */ + (loaderContext).addMissingDependency(d) } }); const getAbsolutify = memoize(() => @@ -683,7 +685,8 @@ class NormalModule extends Module { */ getOptions: (schema) => { const loader = this.getCurrentLoader( - /** @type {LoaderContext} */ (loaderContext) + /** @type {AnyLoaderContext} */ + (loaderContext) ); let { options } = /** @type {LoaderItem} */ (loader); @@ -745,7 +748,8 @@ class NormalModule extends Module { }, getLogger: (name) => { const currentLoader = this.getCurrentLoader( - /** @type {LoaderContext} */ (loaderContext) + /** @type {AnyLoaderContext} */ + (loaderContext) ); return compilation.getLogger(() => [currentLoader && currentLoader.loader, name, this.identifier()] @@ -834,19 +838,18 @@ class NormalModule extends Module { Object.assign(loaderContext, options.loader); - // After `hooks.loader.call` is called, the loaderContext is typed as LoaderContext hooks.loader.call( - /** @type {LoaderContext} */ + /** @type {AnyLoaderContext} */ (loaderContext), this ); - return /** @type {LoaderContext} */ (loaderContext); + return /** @type {AnyLoaderContext} */ (loaderContext); } // TODO remove `loaderContext` in webpack@6 /** - * @param {LoaderContext} loaderContext loader context + * @param {AnyLoaderContext} loaderContext loader context * @param {number} index index * @returns {LoaderItem | null} loader */ @@ -995,7 +998,7 @@ class NormalModule extends Module { hooks.beforeLoaders.call( this.loaders, this, - /** @type {LoaderContext} */ + /** @type {AnyLoaderContext} */ (loaderContext) ); } catch (err) { @@ -1014,7 +1017,7 @@ class NormalModule extends Module { loaders: this.loaders, context: loaderContext, /** - * @param {LoaderContext} loaderContext the loader context + * @param {AnyLoaderContext} loaderContext the loader context * @param {string} resourcePath the resource Path * @param {(err: Error | null, result?: string | Buffer, sourceMap?: Result[1]) => void} callback callback * @returns {Promise} @@ -1062,7 +1065,8 @@ class NormalModule extends Module { readResource( resourcePath, (resourcePath) => - /** @type {LoaderContext} */ ({ + /** @type {AnyLoaderContext} */ + ({ addDependency(dependency) { loaderContext.addDependency(dependency); }, diff --git a/lib/ProgressPlugin.js b/lib/ProgressPlugin.js index 0e5fa46e3..82d26bb19 100644 --- a/lib/ProgressPlugin.js +++ b/lib/ProgressPlugin.js @@ -16,7 +16,6 @@ const { contextify } = require("./util/identifier"); * @template T, R, AdditionalOptions * @typedef {import("tapable").Hook} Hook */ -/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */ /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ /** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */ /** @typedef {import("./Dependency")} Dependency */ @@ -53,20 +52,18 @@ const validate = createSchemaValidation( */ const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c); +/** @typedef {(percentage: number, msg: string, ...args: string[]) => void} HandlerFn */ + /** * @param {boolean | null | undefined} profile need profile * @param {Logger} logger logger - * @returns {defaultHandler} default handler + * @returns {HandlerFn} default handler */ const createDefaultHandler = (profile, logger) => { /** @type {{ value: string | undefined, time: number }[]} */ const lastStateInfo = []; - /** - * @param {number} percentage percentage - * @param {string} msg message - * @param {...string} args additional arguments - */ + /** @type {HandlerFn} */ const defaultHandler = (percentage, msg, ...args) => { if (profile) { if (percentage === 0) { @@ -198,7 +195,7 @@ class ProgressPlugin { /** * @param {MultiCompiler} compiler webpack multi-compiler - * @param {HandlerFunction} handler function that executes for every progress step + * @param {HandlerFn} handler function that executes for every progress step * @returns {void} */ _applyOnMultiCompiler(compiler, handler) { @@ -217,7 +214,7 @@ class ProgressPlugin { /** * @param {Compiler} compiler webpack compiler - * @param {HandlerFunction} handler function that executes for every progress step + * @param {HandlerFn} handler function that executes for every progress step * @returns {void} */ _applyOnCompiler(compiler, handler) { diff --git a/lib/ProvidePlugin.js b/lib/ProvidePlugin.js index 898bd0d08..68f2d0a8f 100644 --- a/lib/ProvidePlugin.js +++ b/lib/ProvidePlugin.js @@ -59,13 +59,11 @@ class ProvidePlugin { */ const handler = (parser, parserOptions) => { for (const name of Object.keys(definitions)) { - const request = - /** @type {string[]} */ - ([ - ...(Array.isArray(definitions[name]) - ? definitions[name] - : [definitions[name]]) - ]); + const request = [ + ...(Array.isArray(definitions[name]) + ? definitions[name] + : [definitions[name]]) + ]; const splittedName = name.split("."); if (splittedName.length > 0) { for (const [i, _] of splittedName.slice(1).entries()) { diff --git a/lib/RecordIdsPlugin.js b/lib/RecordIdsPlugin.js index 538cdb375..abf1b306c 100644 --- a/lib/RecordIdsPlugin.js +++ b/lib/RecordIdsPlugin.js @@ -110,12 +110,14 @@ class RecordIdsPlugin { } }); + /** @typedef {string[]} ChunkSources */ + /** * @param {Chunk} chunk the chunk - * @returns {string[]} sources of the chunk + * @returns {ChunkSources} sources of the chunk */ const getChunkSources = (chunk) => { - /** @type {string[]} */ + /** @type {ChunkSources} */ const sources = []; for (const chunkGroup of chunk.groupsIterable) { const index = chunkGroup.chunks.indexOf(chunk); diff --git a/lib/Template.js b/lib/Template.js index 81cfd6d9a..99a4af21a 100644 --- a/lib/Template.js +++ b/lib/Template.js @@ -221,7 +221,7 @@ class Template { } /** - * @param {string|string[]} s string to create prefix for + * @param {string | string[]} s string to create prefix for * @param {string} prefix prefix to compose * @returns {string} returns new prefix string */ @@ -233,7 +233,7 @@ class Template { } /** - * @param {string|string[]} str string or string collection + * @param {string | string[]} str string or string collection * @returns {string} returns a single string from array */ static asString(str) { diff --git a/lib/TemplatedPathPlugin.js b/lib/TemplatedPathPlugin.js index 0afb5aff2..fafd04b4c 100644 --- a/lib/TemplatedPathPlugin.js +++ b/lib/TemplatedPathPlugin.js @@ -133,7 +133,8 @@ const deprecated = (fn, message, code) => { ); }; -/** @typedef {string | ((pathData: PathData, assetInfo?: AssetInfo) => string)} TemplatePath */ +/** @typedef {(pathData: PathData, assetInfo?: AssetInfo) => string} TemplatePathFn */ +/** @typedef {string | TemplatePathFn} TemplatePath */ /** * @param {TemplatePath} path the raw path diff --git a/lib/asset/AssetGenerator.js b/lib/asset/AssetGenerator.js index d09d9a4f0..a10dcef17 100644 --- a/lib/asset/AssetGenerator.js +++ b/lib/asset/AssetGenerator.js @@ -40,6 +40,7 @@ const getMimeTypes = memoize(() => require("mime-types")); /** @typedef {import("../Compilation").AssetInfo} AssetInfo */ /** @typedef {import("../Generator").GenerateContext} GenerateContext */ /** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").NameForCondition} NameForCondition */ /** @typedef {import("../Module").BuildInfo} BuildInfo */ /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -412,7 +413,7 @@ class AssetGenerator extends Generator { (this.dataUrlOptions).mimetype; if (mimeType === undefined) { const ext = path.extname( - /** @type {string} */ + /** @type {NameForCondition} */ (module.nameForCondition()) ); if ( diff --git a/lib/container/ContainerEntryModule.js b/lib/container/ContainerEntryModule.js index ce6c420d9..987025d3a 100644 --- a/lib/container/ContainerEntryModule.js +++ b/lib/container/ContainerEntryModule.js @@ -22,6 +22,7 @@ const ContainerExposedDependency = require("./ContainerExposedDependency"); /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").LibIdent} LibIdent */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -78,7 +79,7 @@ class ContainerEntryModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${ diff --git a/lib/container/FallbackModule.js b/lib/container/FallbackModule.js index 477152ccc..29dd647b9 100644 --- a/lib/container/FallbackModule.js +++ b/lib/container/FallbackModule.js @@ -21,6 +21,8 @@ const FallbackItemDependency = require("./FallbackItemDependency"); /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").LibIdent} LibIdent */ +/** @typedef {import("../Module").NameForCondition} NameForCondition */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -29,12 +31,13 @@ const FallbackItemDependency = require("./FallbackItemDependency"); /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./RemoteModule").ExternalRequests} ExternalRequests */ const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); class FallbackModule extends Module { /** - * @param {string[]} requests list of requests to choose one + * @param {ExternalRequests} requests list of requests to choose one */ constructor(requests) { super(WEBPACK_MODULE_TYPE_FALLBACK); @@ -59,7 +62,7 @@ class FallbackModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${ diff --git a/lib/container/RemoteModule.js b/lib/container/RemoteModule.js index 20f9afdfb..15bb27233 100644 --- a/lib/container/RemoteModule.js +++ b/lib/container/RemoteModule.js @@ -22,6 +22,8 @@ const RemoteToExternalDependency = require("./RemoteToExternalDependency"); /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").LibIdent} LibIdent */ +/** @typedef {import("../Module").NameForCondition} NameForCondition */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -70,7 +72,7 @@ class RemoteModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${ @@ -129,7 +131,7 @@ class RemoteModule extends Module { } /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path) */ nameForCondition() { return this.request; diff --git a/lib/dependencies/AMDDefineDependencyParserPlugin.js b/lib/dependencies/AMDDefineDependencyParserPlugin.js index c23350335..3bbcf0d9a 100644 --- a/lib/dependencies/AMDDefineDependencyParserPlugin.js +++ b/lib/dependencies/AMDDefineDependencyParserPlugin.js @@ -29,6 +29,7 @@ const { addLocalModule, getLocalModule } = require("./LocalModulesHelpers"); /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").ExportedVariableInfo} ExportedVariableInfo */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @@ -67,6 +68,8 @@ const isCallable = (expr) => { return false; }; +/** @typedef {Record} Identifiers */ + const PLUGIN_NAME = "AMDDefineDependencyParserPlugin"; class AMDDefineDependencyParserPlugin { @@ -91,7 +94,7 @@ class AMDDefineDependencyParserPlugin { * @param {JavascriptParser} parser the parser * @param {CallExpression} expr call expression * @param {BasicEvaluatedExpression} param param - * @param {Record} identifiers identifiers + * @param {Identifiers} identifiers identifiers * @param {string=} namedModule named module * @returns {boolean | undefined} result */ @@ -105,7 +108,7 @@ class AMDDefineDependencyParserPlugin { /** @type {string} */ (item.string) ) ) { - identifiers[/** @type {number} */ (idx)] = + identifiers[idx] = /** @type {string} */ (item.string); } @@ -346,9 +349,10 @@ class AMDDefineDependencyParserPlugin { } } } + /** @type {Map} */ const fnRenames = new Map(); if (array) { - /** @type {Record} */ + /** @type {Identifiers} */ const identifiers = {}; const param = parser.evaluateExpression(array); const result = this.processArray( diff --git a/lib/dependencies/AMDPlugin.js b/lib/dependencies/AMDPlugin.js index 10fe5a070..4fa2f412a 100644 --- a/lib/dependencies/AMDPlugin.js +++ b/lib/dependencies/AMDPlugin.js @@ -38,6 +38,7 @@ const UnsupportedDependency = require("./UnsupportedDependency"); /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../javascript/JavascriptParser")} Parser */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/BasicEvaluatedExpression").GetMembers} GetMembers */ const PLUGIN_NAME = "AMDPlugin"; @@ -142,7 +143,7 @@ class AMDPlugin { /** * @param {string} optionExpr option expression * @param {string} rootName root name - * @param {() => string[]} getMembers callback + * @param {GetMembers} getMembers callback */ const tapOptionsHooks = (optionExpr, rootName, getMembers) => { parser.hooks.expression diff --git a/lib/dependencies/CommonJsExportRequireDependency.js b/lib/dependencies/CommonJsExportRequireDependency.js index 2050d100a..96b361a57 100644 --- a/lib/dependencies/CommonJsExportRequireDependency.js +++ b/lib/dependencies/CommonJsExportRequireDependency.js @@ -17,11 +17,13 @@ const processExportInfo = require("./processExportInfo"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ExportsInfo")} ExportsInfo */ /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ @@ -30,8 +32,6 @@ const processExportInfo = require("./processExportInfo"); /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ -/** @typedef {string[]} IDs */ - const idsSymbol = Symbol("CommonJsExportRequireDependency.ids"); const EMPTY_OBJECT = {}; @@ -44,9 +44,9 @@ class CommonJsExportRequireDependency extends ModuleDependency { * @param {Range} range range * @param {Range | null} valueRange value range * @param {CommonJSDependencyBaseKeywords} base base - * @param {string[]} names names + * @param {ExportInfoName[]} names names * @param {string} request request - * @param {IDs} ids ids + * @param {ExportInfoName[]} ids ids * @param {boolean} resultUsed true, when the result is used */ constructor(range, valueRange, base, names, request, ids, resultUsed) { @@ -73,7 +73,7 @@ class CommonJsExportRequireDependency extends ModuleDependency { /** * @param {ModuleGraph} moduleGraph the module graph - * @returns {IDs} the imported id + * @returns {ExportInfoName[]} the imported id */ getIds(moduleGraph) { return moduleGraph.getMeta(this)[idsSymbol] || this.ids; @@ -81,7 +81,7 @@ class CommonJsExportRequireDependency extends ModuleDependency { /** * @param {ModuleGraph} moduleGraph the module graph - * @param {IDs} ids the imported ids + * @param {ExportInfoName[]} ids the imported ids * @returns {void} */ setIds(moduleGraph, ids) { @@ -92,7 +92,7 @@ class CommonJsExportRequireDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { const ids = this.getIds(moduleGraph); @@ -113,9 +113,9 @@ class CommonJsExportRequireDependency extends ModuleDependency { /** @type {Module} */ (moduleGraph.getParentModule(this)) ); for (const name of this.names) { - const exportInfo = /** @type {ExportInfo} */ ( - exportsInfo.getReadOnlyExportInfo(name) - ); + const exportInfo = + /** @type {ExportInfo} */ + (exportsInfo.getReadOnlyExportInfo(name)); const used = exportInfo.getUsed(runtime); if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED; if (used !== UsageState.OnlyPropertiesUsed) return getFullResult(); @@ -125,7 +125,7 @@ class CommonJsExportRequireDependency extends ModuleDependency { if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { return getFullResult(); } - /** @type {string[][]} */ + /** @type {RawReferencedExports} */ const referencedExports = []; for (const exportInfo of exportsInfo.orderedExports) { processExportInfo( diff --git a/lib/dependencies/CommonJsExportsDependency.js b/lib/dependencies/CommonJsExportsDependency.js index 93c831b5d..18f8f5910 100644 --- a/lib/dependencies/CommonJsExportsDependency.js +++ b/lib/dependencies/CommonJsExportsDependency.js @@ -16,6 +16,7 @@ const NullDependency = require("./NullDependency"); /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ @@ -28,7 +29,7 @@ class CommonJsExportsDependency extends NullDependency { * @param {Range} range range * @param {Range | null} valueRange value range * @param {CommonJSDependencyBaseKeywords} base base - * @param {string[]} names names + * @param {ExportInfoName[]} names names */ constructor(range, valueRange, base, names) { super(); diff --git a/lib/dependencies/CommonJsExportsParserPlugin.js b/lib/dependencies/CommonJsExportsParserPlugin.js index 972f5ff90..66c4c26a5 100644 --- a/lib/dependencies/CommonJsExportsParserPlugin.js +++ b/lib/dependencies/CommonJsExportsParserPlugin.js @@ -22,9 +22,11 @@ const ModuleDecoratorDependency = require("./ModuleDecoratorDependency"); /** @typedef {import("estree").Super} Super */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/JavascriptParser").Members} Members */ /** @typedef {import("../javascript/JavascriptParser").StatementPath} StatementPath */ /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ /** @typedef {import("../Module").BuildMeta} BuildMeta */ @@ -94,9 +96,10 @@ const isFalsyLiteral = (expr) => { /** * @param {JavascriptParser} parser the parser * @param {Expression} expr expression - * @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call + * @returns {{ argument: BasicEvaluatedExpression, ids: ExportInfoName[] } | undefined} parsed call */ const parseRequireCall = (parser, expr) => { + /** @type {ExportInfoName[]} */ const ids = []; while (expr.type === "MemberExpression") { if (expr.object.type === "Super") return; @@ -146,7 +149,7 @@ class CommonJsExportsParserPlugin { /** * @param {boolean} topLevel true, when the export is on top level - * @param {string[]} members members of the export + * @param {Members} members members of the export * @param {Expression | undefined} valueExpr expression for the value * @returns {void} */ @@ -189,7 +192,7 @@ class CommonJsExportsParserPlugin { /** * @param {AssignmentExpression} expr expression * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords - * @param {string[]} members members of the export + * @param {Members} members members of the export * @returns {boolean | undefined} true, when the expression was handled */ const handleAssignExport = (expr, base, members) => { @@ -312,7 +315,7 @@ class CommonJsExportsParserPlugin { /** * @param {Expression | Super} expr expression * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords - * @param {string[]} members members of the export + * @param {Members} members members of the export * @param {CallExpression=} call call expression * @returns {boolean | void} true, when the expression was handled */ diff --git a/lib/dependencies/CommonJsFullRequireDependency.js b/lib/dependencies/CommonJsFullRequireDependency.js index 98b3b4cb1..3cf98bb8a 100644 --- a/lib/dependencies/CommonJsFullRequireDependency.js +++ b/lib/dependencies/CommonJsFullRequireDependency.js @@ -14,20 +14,22 @@ const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../util/chainedImports").IdRanges} IdRanges */ class CommonJsFullRequireDependency extends ModuleDependency { /** * @param {string} request the request string * @param {Range} range location in source code - * @param {string[]} names accessed properties on module - * @param {Range[]=} idRanges ranges for members of ids; the two arrays are right-aligned + * @param {ExportInfoName[]} names accessed properties on module + * @param {IdRanges=} idRanges ranges for members of ids; the two arrays are right-aligned */ constructor( request, @@ -47,7 +49,7 @@ class CommonJsFullRequireDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { if (this.call) { diff --git a/lib/dependencies/CommonJsImportsParserPlugin.js b/lib/dependencies/CommonJsImportsParserPlugin.js index 25cea6a33..67d495cea 100644 --- a/lib/dependencies/CommonJsImportsParserPlugin.js +++ b/lib/dependencies/CommonJsImportsParserPlugin.js @@ -38,6 +38,8 @@ const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser").ImportSource} ImportSource */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/JavascriptParser").Members} Members */ +/** @typedef {import("../javascript/JavascriptParser").CalleeMembers} CalleeMembers */ /** * @typedef {object} CommonJsImportSettings @@ -76,7 +78,7 @@ class CommonJsImportsParserPlugin { // #region metadata /** * @param {string} expression expression - * @param {() => string[]} getMembers get members + * @param {() => Members} getMembers get members */ const tapRequireExpression = (expression, getMembers) => { parser.hooks.typeof @@ -373,9 +375,9 @@ class CommonJsImportsParserPlugin { // #region Require with property access /** * @param {Expression} expr expression - * @param {string[]} calleeMembers callee members + * @param {CalleeMembers} calleeMembers callee members * @param {CallExpression} callExpr call expression - * @param {string[]} members members + * @param {Members} members members * @param {Range[]} memberRanges member ranges * @returns {boolean | void} true when handled */ @@ -409,9 +411,9 @@ class CommonJsImportsParserPlugin { }; /** * @param {CallExpression} expr expression - * @param {string[]} calleeMembers callee members + * @param {CalleeMembers} calleeMembers callee members * @param {CallExpression} callExpr call expression - * @param {string[]} members members + * @param {Members} members members * @param {Range[]} memberRanges member ranges * @returns {boolean | void} true when handled */ diff --git a/lib/dependencies/CommonJsSelfReferenceDependency.js b/lib/dependencies/CommonJsSelfReferenceDependency.js index bdccdaa66..5aea9bbaa 100644 --- a/lib/dependencies/CommonJsSelfReferenceDependency.js +++ b/lib/dependencies/CommonJsSelfReferenceDependency.js @@ -13,9 +13,10 @@ const NullDependency = require("./NullDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ @@ -26,7 +27,7 @@ class CommonJsSelfReferenceDependency extends NullDependency { /** * @param {Range} range range * @param {CommonJSDependencyBaseKeywords} base base - * @param {string[]} names names + * @param {ExportInfoName[]} names names * @param {boolean} call is a call */ constructor(range, base, names, call) { @@ -56,7 +57,7 @@ class CommonJsSelfReferenceDependency extends NullDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return [this.call ? this.names.slice(0, -1) : this.names]; diff --git a/lib/dependencies/ConstDependency.js b/lib/dependencies/ConstDependency.js index 35512dbed..966664638 100644 --- a/lib/dependencies/ConstDependency.js +++ b/lib/dependencies/ConstDependency.js @@ -9,6 +9,7 @@ const makeSerializable = require("../util/makeSerializable"); const NullDependency = require("./NullDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("./NullDependency").RawRuntimeRequirements} RawRuntimeRequirements */ /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ @@ -23,7 +24,7 @@ class ConstDependency extends NullDependency { /** * @param {string} expression the expression * @param {number | Range} range the source range - * @param {(string[] | null)=} runtimeRequirements runtime requirements + * @param {RawRuntimeRequirements | null=} runtimeRequirements runtime requirements */ constructor(expression, range, runtimeRequirements) { super(); diff --git a/lib/dependencies/ContextElementDependency.js b/lib/dependencies/ContextElementDependency.js index 3ada649a7..88e98db30 100644 --- a/lib/dependencies/ContextElementDependency.js +++ b/lib/dependencies/ContextElementDependency.js @@ -10,7 +10,8 @@ const makeSerializable = require("../util/makeSerializable"); const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("../ContextModule")} ContextModule */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ @@ -24,7 +25,7 @@ class ContextElementDependency extends ModuleDependency { * @param {string | undefined} userRequest user request * @param {string | undefined} typePrefix type prefix * @param {string} category category - * @param {(string[][] | null)=} referencedExports referenced exports + * @param {RawReferencedExports | null=} referencedExports referenced exports * @param {string=} context context * @param {ImportAttributes=} attributes import assertions */ @@ -66,7 +67,7 @@ class ContextElementDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED; diff --git a/lib/dependencies/CssIcssSymbolDependency.js b/lib/dependencies/CssIcssSymbolDependency.js index 298e5d1cd..adcbf7f0a 100644 --- a/lib/dependencies/CssIcssSymbolDependency.js +++ b/lib/dependencies/CssIcssSymbolDependency.js @@ -11,7 +11,7 @@ const NullDependency = require("./NullDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ @@ -77,7 +77,7 @@ class CssIcssSymbolDependency extends NullDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return [[this.name]]; diff --git a/lib/dependencies/CssSelfLocalIdentifierDependency.js b/lib/dependencies/CssSelfLocalIdentifierDependency.js index 6d4ac1ed1..f86dcb4a2 100644 --- a/lib/dependencies/CssSelfLocalIdentifierDependency.js +++ b/lib/dependencies/CssSelfLocalIdentifierDependency.js @@ -11,7 +11,7 @@ const CssLocalIdentifierDependency = require("./CssLocalIdentifierDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../css/CssParser").Range} Range */ @@ -60,7 +60,7 @@ class CssSelfLocalIdentifierDependency extends CssLocalIdentifierDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { if (this.declaredSet && !this.declaredSet.has(this.name)) { diff --git a/lib/dependencies/ExportsInfoDependency.js b/lib/dependencies/ExportsInfoDependency.js index 6116673a4..2745532db 100644 --- a/lib/dependencies/ExportsInfoDependency.js +++ b/lib/dependencies/ExportsInfoDependency.js @@ -14,6 +14,7 @@ const NullDependency = require("./NullDependency"); /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ @@ -27,13 +28,13 @@ const NullDependency = require("./NullDependency"); /** * @param {ModuleGraph} moduleGraph the module graph * @param {Module} module the module - * @param {string[] | null} _exportName name of the export if any + * @param {ExportInfoName[] | null} exportName_ name of the export if any * @param {string | null} property name of the requested property * @param {RuntimeSpec} runtime for which runtime - * @returns {undefined | null | number | boolean | string[] | SortableSet} value of the property + * @returns {undefined | null | boolean | ExportInfoName[]} value of the property */ -const getProperty = (moduleGraph, module, _exportName, property, runtime) => { - if (!_exportName) { +const getProperty = (moduleGraph, module, exportName_, property, runtime) => { + if (!exportName_) { switch (property) { case "usedExports": { const usedExports = moduleGraph @@ -50,7 +51,7 @@ const getProperty = (moduleGraph, module, _exportName, property, runtime) => { } } } - const exportName = /** @type {string[]} */ (_exportName); + const exportName = /** @type {ExportInfoName[]} */ (exportName_); switch (property) { case "canMangle": { const exportsInfo = moduleGraph.getExportsInfo(module); @@ -89,7 +90,7 @@ const getProperty = (moduleGraph, module, _exportName, property, runtime) => { class ExportsInfoDependency extends NullDependency { /** * @param {Range} range range - * @param {string[] | null} exportName export name + * @param {ExportInfoName[] | null} exportName export name * @param {string | null} property property */ constructor(range, exportName, property) { diff --git a/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js b/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js index c1861bf09..80104bfcc 100644 --- a/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +++ b/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js @@ -17,6 +17,7 @@ const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDepend /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./HarmonyImportDependency").Ids} Ids */ /** * Dependency for static evaluating import specifier. e.g. @@ -29,7 +30,7 @@ class HarmonyEvaluatedImportSpecifierDependency extends HarmonyImportSpecifierDe /** * @param {string} request the request string * @param {number} sourceOrder source order - * @param {string[]} ids ids + * @param {Ids} ids ids * @param {string} name name * @param {Range} range location in source code * @param {ImportAttributes | undefined} attributes import assertions diff --git a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js index a7b668603..c839e43e3 100644 --- a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +++ b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js @@ -33,7 +33,8 @@ const processExportInfo = require("./processExportInfo"); /** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ExportsInfo")} ExportsInfo */ @@ -54,8 +55,8 @@ const processExportInfo = require("./processExportInfo"); /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./HarmonyImportDependency").Ids} Ids */ /** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */ -/** @typedef {import("./processExportInfo").ReferencedExports} ReferencedExports */ /** @typedef {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */ @@ -63,12 +64,10 @@ const { ExportPresenceModes } = HarmonyImportDependency; const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids"); -/** @typedef {string[]} IDs */ - class NormalReexportItem { /** * @param {string} name export name - * @param {IDs} ids reexported ids from other module + * @param {Ids} ids reexported ids from other module * @param {ExportInfo} exportInfo export info from other module * @param {boolean} checked true, if it should be checked at runtime if this export exists * @param {boolean} hidden true, if it is hidden behind another active export in the same module @@ -121,14 +120,13 @@ class ExportMode { } } -/** @typedef {string[]} Names */ /** @typedef {number[]} DependencyIndices */ /** * @param {ModuleGraph} moduleGraph module graph * @param {HarmonyExportImportedSpecifierDependency[]} dependencies dependencies * @param {HarmonyExportImportedSpecifierDependency=} additionalDependency additional dependency - * @returns {{ names: Names, dependencyIndices: DependencyIndices }} result + * @returns {{ names: ExportInfoName[], dependencyIndices: DependencyIndices }} result */ const determineExportAssignments = ( moduleGraph, @@ -137,7 +135,7 @@ const determineExportAssignments = ( ) => { /** @type {Set} */ const names = new Set(); - /** @type {number[]} */ + /** @type {DependencyIndices} */ const dependencyIndices = []; if (additionalDependency) { @@ -169,7 +167,7 @@ const determineExportAssignments = ( /** * @param {object} options options - * @param {Names} options.names names + * @param {ExportInfoName[]} options.names names * @param {DependencyIndices} options.dependencyIndices dependency indices * @param {string} name name * @param {ReadonlyArray} dependencies dependencies @@ -372,7 +370,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { /** * @param {string} request the request string * @param {number} sourceOrder the order in the original source file - * @param {IDs} ids the requested export name of the imported module + * @param {Ids} ids the requested export name of the imported module * @param {string | null} name the export name of for this module * @param {Set} activeExports other named exports in the module * @param {ReadonlyArray | null} otherStarExports other star exports in the module before this import @@ -431,7 +429,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { /** * @param {ModuleGraph} moduleGraph the module graph - * @returns {IDs} the imported id + * @returns {Ids} the imported id */ getIds(moduleGraph) { return moduleGraph.getMeta(this)[idsSymbol] || this.ids; @@ -439,7 +437,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { /** * @param {ModuleGraph} moduleGraph the module graph - * @param {IDs} ids the imported ids + * @param {Ids} ids the imported ids * @returns {void} */ setIds(moduleGraph, ids) { @@ -568,7 +566,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { const mode = this.getMode(moduleGraph, runtime); @@ -587,7 +585,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { if (!mode.partialNamespaceExportInfo) { return Dependency.EXPORTS_OBJECT_REFERENCED; } - /** @type {ReferencedExports} */ + /** @type {RawReferencedExports} */ const referencedExports = []; processExportInfo( runtime, @@ -603,7 +601,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { if (!mode.partialNamespaceExportInfo) { return Dependency.EXPORTS_OBJECT_REFERENCED; } - /** @type {ReferencedExports} */ + /** @type {RawReferencedExports} */ const referencedExports = []; processExportInfo( runtime, @@ -619,7 +617,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { return Dependency.EXPORTS_OBJECT_REFERENCED; case "normal-reexport": { - /** @type {ReferencedExports} */ + /** @type {RawReferencedExports} */ const referencedExports = []; for (const { ids, @@ -639,7 +637,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { /** * @param {ModuleGraph} moduleGraph the module graph - * @returns {{ names: Names, namesSlice: number, dependencyIndices: DependencyIndices, dependencyIndex: number } | undefined} exported names and their origin dependency + * @returns {{ names: ExportInfoName[], namesSlice: number, dependencyIndices: DependencyIndices, dependencyIndex: number } | undefined} exported names and their origin dependency */ _discoverActiveExportsFromOtherStarExports(moduleGraph) { if (!this.otherStarExports) return; @@ -881,7 +879,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { const importedModule = moduleGraph.getModule(this); if (importedModule) { const exportsInfo = moduleGraph.getExportsInfo(importedModule); - /** @type {Map} */ + /** @type {Map} */ const conflicts = new Map(); for (const exportInfo of exportsInfo.orderedExports) { if (exportInfo.provided !== true) continue; @@ -1279,7 +1277,7 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS * @param {string} comment comment * @param {UsedName} key key * @param {string} name name - * @param {string | string[] | null | false} valueKey value key + * @param {UsedName | null} valueKey value key * @param {RuntimeRequirements} runtimeRequirements runtime requirements * @returns {HarmonyExportInitFragment} harmony export init fragment */ @@ -1304,7 +1302,7 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS /** * @param {Module} module module - * @param {string | string[] | false} key key + * @param {UsedName} key key * @param {string} name name * @param {number} fakeType fake type * @param {RuntimeRequirements} runtimeRequirements runtime requirements @@ -1343,7 +1341,7 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS /** * @param {Module} module module * @param {ChunkGraph} chunkGraph chunkGraph - * @param {string | false | string[]} key key + * @param {UsedName} key key * @param {string} name name * @param {ExportsType} exportsType exportsType * @param {RuntimeRequirements} runtimeRequirements runtimeRequirements diff --git a/lib/dependencies/HarmonyImportDependency.js b/lib/dependencies/HarmonyImportDependency.js index 2c90f5bfd..34c057215 100644 --- a/lib/dependencies/HarmonyImportDependency.js +++ b/lib/dependencies/HarmonyImportDependency.js @@ -15,7 +15,7 @@ const { filterRuntime, mergeRuntime } = require("../util/runtime"); const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ExportsInfo")} ExportsInfo */ /** @typedef {import("../Module")} Module */ @@ -54,6 +54,8 @@ const ExportPresenceModes = { } }; +/** @typedef {string[]} Ids */ + class HarmonyImportDependency extends ModuleDependency { /** * @param {string} request request string @@ -76,7 +78,7 @@ class HarmonyImportDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return Dependency.NO_EXPORTS_REFERENCED; @@ -157,7 +159,7 @@ class HarmonyImportDependency extends ModuleDependency { /** * @param {ModuleGraph} moduleGraph module graph - * @param {string[]} ids imported ids + * @param {Ids} ids imported ids * @param {string} additionalMessage extra info included in the error message * @returns {WebpackError[] | undefined} errors */ diff --git a/lib/dependencies/HarmonyImportDependencyParserPlugin.js b/lib/dependencies/HarmonyImportDependencyParserPlugin.js index 2427ec6cd..9dc0dc51a 100644 --- a/lib/dependencies/HarmonyImportDependencyParserPlugin.js +++ b/lib/dependencies/HarmonyImportDependencyParserPlugin.js @@ -33,12 +33,15 @@ const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDepend /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ /** @typedef {import("../javascript/JavascriptParser").ImportDeclaration} ImportDeclaration */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/JavascriptParser").Members} Members */ +/** @typedef {import("../javascript/JavascriptParser").MembersOptionals} MembersOptionals */ +/** @typedef {import("./HarmonyImportDependency").Ids} Ids */ const harmonySpecifierTag = Symbol("harmony import"); /** * @typedef {object} HarmonySettings - * @property {string[]} ids + * @property {Ids} ids * @property {string} source * @property {number} sourceOrder * @property {string} name @@ -74,9 +77,9 @@ module.exports = class HarmonyImportDependencyParserPlugin { const { exportPresenceMode } = this; /** - * @param {string[]} members members - * @param {boolean[]} membersOptionals members Optionals - * @returns {string[]} a non optional part + * @param {Members} members members + * @param {MembersOptionals} membersOptionals members Optionals + * @returns {Ids} a non optional part */ function getNonOptionalPart(members, membersOptionals) { let i = 0; @@ -188,7 +191,7 @@ module.exports = class HarmonyImportDependencyParserPlugin { /** @type {HarmonySettings} */ (rootInfo.tagInfo.data); const members = - /** @type {(() => string[])} */ + /** @type {(() => Members)} */ (rightPart.getMembers)(); const dep = new HarmonyEvaluatedImportSpecifierDependency( settings.source, diff --git a/lib/dependencies/HarmonyImportSpecifierDependency.js b/lib/dependencies/HarmonyImportSpecifierDependency.js index c6bd10981..27018c997 100644 --- a/lib/dependencies/HarmonyImportSpecifierDependency.js +++ b/lib/dependencies/HarmonyImportSpecifierDependency.js @@ -17,7 +17,8 @@ const HarmonyImportDependency = require("./HarmonyImportDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../Module").BuildMeta} BuildMeta */ @@ -31,9 +32,9 @@ const HarmonyImportDependency = require("./HarmonyImportDependency"); /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../util/chainedImports").IdRanges} IdRanges */ /** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */ - -/** @typedef {string[]} IDs */ +/** @typedef {HarmonyImportDependency.Ids} Ids */ const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids"); @@ -43,12 +44,12 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency { /** * @param {string} request request * @param {number} sourceOrder source order - * @param {IDs} ids ids + * @param {Ids} ids ids * @param {string} name name * @param {Range} range range * @param {ExportPresenceMode} exportPresenceMode export presence mode * @param {ImportAttributes | undefined} attributes import attributes - * @param {Range[] | undefined} idRanges ranges for members of ids; the two arrays are right-aligned + * @param {IdRanges | undefined} idRanges ranges for members of ids; the two arrays are right-aligned * @param {boolean=} defer is defer phase */ constructor( @@ -100,7 +101,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency { /** * @param {ModuleGraph} moduleGraph the module graph - * @returns {IDs} the imported ids + * @returns {Ids} the imported ids */ getIds(moduleGraph) { const meta = moduleGraph.getMetaIfExisting(this); @@ -111,7 +112,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency { /** * @param {ModuleGraph} moduleGraph the module graph - * @param {IDs} ids the imported ids + * @param {Ids} ids the imported ids * @returns {void} */ setIds(moduleGraph, ids) { @@ -142,7 +143,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { let ids = this.getIds(moduleGraph); @@ -188,12 +189,12 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency { } /** - * @param {IDs=} ids ids - * @returns {IDs[]} referenced exports + * @param {Ids=} ids ids + * @returns {RawReferencedExports} referenced exports */ _getReferencedExportsInDestructuring(ids) { if (this.referencedPropertiesInDestructuring) { - /** @type {string[][]} */ + /** @type {RawReferencedExports} */ const refs = []; for (const { id } of this.referencedPropertiesInDestructuring) { refs.push(ids ? [...ids, id] : [id]); @@ -378,7 +379,7 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen shorthand, range } of dep.referencedPropertiesInDestructuring) { - /** @type {IDs} */ + /** @type {Ids} */ const concatedIds = [...prefixedIds, id]; const module = /** @type {Module} */ (moduleGraph.getModule(dep)); const used = moduleGraph @@ -406,7 +407,7 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen * @param {HarmonyImportSpecifierDependency} dep dependency * @param {ReplaceSource} source source * @param {DependencyTemplateContext} templateContext context - * @param {IDs} ids ids + * @param {Ids} ids ids * @returns {string} generated code */ _getCodeForIds(dep, source, templateContext, ids) { diff --git a/lib/dependencies/ImportDependency.js b/lib/dependencies/ImportDependency.js index 1368d405a..051cfb7ab 100644 --- a/lib/dependencies/ImportDependency.js +++ b/lib/dependencies/ImportDependency.js @@ -11,7 +11,8 @@ const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../Module").BuildMeta} BuildMeta */ @@ -26,7 +27,7 @@ class ImportDependency extends ModuleDependency { /** * @param {string} request the request * @param {Range} range expression range - * @param {(string[][] | null)=} referencedExports list of referenced exports + * @param {RawReferencedExports | null=} referencedExports list of referenced exports * @param {ImportAttributes=} attributes import attributes */ constructor(request, range, referencedExports, attributes) { @@ -48,7 +49,7 @@ class ImportDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED; diff --git a/lib/dependencies/ImportEagerDependency.js b/lib/dependencies/ImportEagerDependency.js index d7ebcfe6a..9d8217a70 100644 --- a/lib/dependencies/ImportEagerDependency.js +++ b/lib/dependencies/ImportEagerDependency.js @@ -15,12 +15,13 @@ const ImportDependency = require("./ImportDependency"); /** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {ImportDependency.RawReferencedExports} RawReferencedExports */ class ImportEagerDependency extends ImportDependency { /** * @param {string} request the request * @param {Range} range expression range - * @param {(string[][] | null)=} referencedExports list of referenced exports + * @param {RawReferencedExports | null=} referencedExports list of referenced exports * @param {ImportAttributes=} attributes import attributes */ constructor(request, range, referencedExports, attributes) { diff --git a/lib/dependencies/ImportMetaContextDependencyParserPlugin.js b/lib/dependencies/ImportMetaContextDependencyParserPlugin.js index cc2415b6f..72aeea6d0 100644 --- a/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +++ b/lib/dependencies/ImportMetaContextDependencyParserPlugin.js @@ -18,10 +18,14 @@ const ImportMetaContextDependency = require("./ImportMetaContextDependency"); /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../ContextModule").ContextModuleOptions} ContextModuleOptions */ +/** @typedef {import("../ContextModule").ContextMode} ContextMode */ +/** @typedef {import("../Chunk").ChunkName} ChunkName */ /** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ -/** @typedef {Pick&{groupOptions: RawChunkGroupOptions, exports?: ContextModuleOptions["referencedExports"]}} ImportMetaContextOptions */ + +/** @typedef {Pick & { groupOptions: RawChunkGroupOptions, exports?: RawReferencedExports }} ImportMetaContextOptions */ /** * @param {Property} prop property @@ -83,7 +87,7 @@ module.exports = class ImportMetaContextDependencyParserPlugin { const errors = []; let regExp = /^\.\/.*$/; let recursive = true; - /** @type {ContextModuleOptions["mode"]} */ + /** @type {ContextMode} */ let mode = "sync"; /** @type {ContextModuleOptions["include"]} */ let include; @@ -91,9 +95,9 @@ module.exports = class ImportMetaContextDependencyParserPlugin { let exclude; /** @type {RawChunkGroupOptions} */ const groupOptions = {}; - /** @type {ContextModuleOptions["chunkName"]} */ + /** @type {ChunkName | undefined} */ let chunkName; - /** @type {ContextModuleOptions["referencedExports"]} */ + /** @type {RawReferencedExports | undefined} */ let exports; if (optionsNode) { for (const prop of /** @type {ObjectExpression} */ (optionsNode) diff --git a/lib/dependencies/ImportMetaPlugin.js b/lib/dependencies/ImportMetaPlugin.js index e904a526c..1a4abfe9b 100644 --- a/lib/dependencies/ImportMetaPlugin.js +++ b/lib/dependencies/ImportMetaPlugin.js @@ -30,6 +30,7 @@ const ConstDependency = require("./ConstDependency"); /** @typedef {import("../NormalModule")} NormalModule */ /** @typedef {import("../javascript/JavascriptParser")} Parser */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/JavascriptParser").Members} Members */ const getCriticalDependencyWarning = memoize(() => require("./CriticalDependencyWarning") @@ -83,7 +84,7 @@ class ImportMetaPlugin { JSON.stringify(getUrl(parser.state.module)); const importMetaWebpackVersion = () => JSON.stringify(webpackVersion); /** - * @param {string[]} members members + * @param {Members} members members * @returns {string} error message */ const importMetaUnknownProperty = (members) => diff --git a/lib/dependencies/ImportParserPlugin.js b/lib/dependencies/ImportParserPlugin.js index 449bc4cab..6cde561b9 100644 --- a/lib/dependencies/ImportParserPlugin.js +++ b/lib/dependencies/ImportParserPlugin.js @@ -19,14 +19,17 @@ const ImportWeakDependency = require("./ImportWeakDependency"); /** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ /** @typedef {import("../ContextModule").ContextMode} ContextMode */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ /** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser").ImportExpression} ImportExpression */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").ParserState} ParserState */ +/** @typedef {import("../javascript/JavascriptParser").Members} Members */ +/** @typedef {import("../javascript/JavascriptParser").MembersOptionals} MembersOptionals */ -/** @typedef {{ references: string[][], expression: ImportExpression }} ImportSettings */ -/** @typedef {WeakMap} State */ +/** @typedef {{ references: RawReferencedExports, expression: ImportExpression }} ImportSettings */ +/** @typedef {WeakMap} State */ /** @type {WeakMap} */ const parserStateMap = new WeakMap(); @@ -67,8 +70,8 @@ class ImportParserPlugin { Array.from(enumerable, (e) => [e]); /** - * @param {string[]} members members - * @param {boolean[]} membersOptionals members Optionals + * @param {Members} members members + * @param {MembersOptionals} membersOptionals members Optionals * @returns {string[]} a non optional part */ function getNonOptionalPart(members, membersOptionals) { @@ -92,7 +95,7 @@ class ImportParserPlugin { ) { const importCall = decl.init.argument; const state = getState(parser); - /** @type {string[][]} */ + /** @type {RawReferencedExports} */ const references = []; state.set(importCall, references); parser.tagVariable( @@ -140,7 +143,7 @@ class ImportParserPlugin { let mode = /** @type {ContextMode} */ (this.options.dynamicImportMode); let include = null; let exclude = null; - /** @type {string[][] | null} */ + /** @type {RawReferencedExports | null} */ let exports = null; /** @type {RawChunkGroupOptions} */ const groupOptions = {}; @@ -326,7 +329,7 @@ class ImportParserPlugin { !( typeof importOptions.webpackExports === "string" || (Array.isArray(importOptions.webpackExports) && - /** @type {string[]} */ (importOptions.webpackExports).every( + importOptions.webpackExports.every( (item) => typeof item === "string" )) ) diff --git a/lib/dependencies/ImportWeakDependency.js b/lib/dependencies/ImportWeakDependency.js index 464ba7bfe..6c6495599 100644 --- a/lib/dependencies/ImportWeakDependency.js +++ b/lib/dependencies/ImportWeakDependency.js @@ -15,12 +15,13 @@ const ImportDependency = require("./ImportDependency"); /** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {ImportDependency.RawReferencedExports} RawReferencedExports */ class ImportWeakDependency extends ImportDependency { /** * @param {string} request the request * @param {Range} range expression range - * @param {(string[][] | null)=} referencedExports list of referenced exports + * @param {RawReferencedExports | null=} referencedExports list of referenced exports * @param {ImportAttributes=} attributes import attributes */ constructor(request, range, referencedExports, attributes) { diff --git a/lib/dependencies/ModuleDecoratorDependency.js b/lib/dependencies/ModuleDecoratorDependency.js index 607884b98..72951e608 100644 --- a/lib/dependencies/ModuleDecoratorDependency.js +++ b/lib/dependencies/ModuleDecoratorDependency.js @@ -12,7 +12,7 @@ const makeSerializable = require("../util/makeSerializable"); const NullDependency = require("./NullDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ @@ -55,7 +55,7 @@ class ModuleDecoratorDependency extends NullDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return this.allowExportsAccess diff --git a/lib/dependencies/NullDependency.js b/lib/dependencies/NullDependency.js index c22cafc7c..3764ec8dc 100644 --- a/lib/dependencies/NullDependency.js +++ b/lib/dependencies/NullDependency.js @@ -12,6 +12,8 @@ const DependencyTemplate = require("../DependencyTemplate"); /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {string[]} RawRuntimeRequirements */ + class NullDependency extends Dependency { get type() { return "null"; diff --git a/lib/dependencies/ProvidedDependency.js b/lib/dependencies/ProvidedDependency.js index 6eebd659f..0a0ca28ae 100644 --- a/lib/dependencies/ProvidedDependency.js +++ b/lib/dependencies/ProvidedDependency.js @@ -11,11 +11,12 @@ const makeSerializable = require("../util/makeSerializable"); const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ @@ -23,7 +24,7 @@ const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @param {string[]|null} path the property path array + * @param {string[] | null} path the property path array * @returns {string} the converted path */ const pathToString = (path) => @@ -35,7 +36,7 @@ class ProvidedDependency extends ModuleDependency { /** * @param {string} request request * @param {string} identifier identifier - * @param {string[]} ids ids + * @param {ExportInfoName[]} ids ids * @param {Range} range range */ constructor(request, identifier, ids, range) { @@ -58,7 +59,7 @@ class ProvidedDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { const ids = this.ids; @@ -139,7 +140,7 @@ class ProvidedDependencyTemplate extends ModuleDependency.Template { chunkGraph, request: dep.request, runtimeRequirements - })}${pathToString(/** @type {string[]} */ (usedName))};\n`, + })}${pathToString(/** @type {string[] | null} */ (usedName))};\n`, InitFragment.STAGE_PROVIDES, 1, `provided ${dep.identifier}` diff --git a/lib/dependencies/RequireIncludeDependency.js b/lib/dependencies/RequireIncludeDependency.js index 3a25e84a8..c6aae6cc9 100644 --- a/lib/dependencies/RequireIncludeDependency.js +++ b/lib/dependencies/RequireIncludeDependency.js @@ -11,7 +11,7 @@ const makeSerializable = require("../util/makeSerializable"); const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ @@ -32,7 +32,7 @@ class RequireIncludeDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { // This doesn't use any export diff --git a/lib/dependencies/RequireResolveDependency.js b/lib/dependencies/RequireResolveDependency.js index 3205925d2..fb70a86ea 100644 --- a/lib/dependencies/RequireResolveDependency.js +++ b/lib/dependencies/RequireResolveDependency.js @@ -10,7 +10,7 @@ const makeSerializable = require("../util/makeSerializable"); const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyAsId = require("./ModuleDependencyTemplateAsId"); -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ @@ -40,7 +40,7 @@ class RequireResolveDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { // This doesn't use any export diff --git a/lib/dependencies/RuntimeRequirementsDependency.js b/lib/dependencies/RuntimeRequirementsDependency.js index b3c4ac65c..ec4650358 100644 --- a/lib/dependencies/RuntimeRequirementsDependency.js +++ b/lib/dependencies/RuntimeRequirementsDependency.js @@ -9,6 +9,7 @@ const makeSerializable = require("../util/makeSerializable"); const NullDependency = require("./NullDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("./NullDependency").RawRuntimeRequirements} RawRuntimeRequirements */ /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ @@ -18,7 +19,7 @@ const NullDependency = require("./NullDependency"); class RuntimeRequirementsDependency extends NullDependency { /** - * @param {string[]} runtimeRequirements runtime requirements + * @param {RawRuntimeRequirements} runtimeRequirements runtime requirements */ constructor(runtimeRequirements) { super(); diff --git a/lib/dependencies/StaticExportsDependency.js b/lib/dependencies/StaticExportsDependency.js index b6d8c6d73..2a74dfd39 100644 --- a/lib/dependencies/StaticExportsDependency.js +++ b/lib/dependencies/StaticExportsDependency.js @@ -13,9 +13,11 @@ const NullDependency = require("./NullDependency"); /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {string[] | true} Exports */ + class StaticExportsDependency extends NullDependency { /** - * @param {string[] | true} exports export names + * @param {Exports} exports export names * @param {boolean} canMangle true, if mangling exports names is allowed */ constructor(exports, canMangle) { diff --git a/lib/dependencies/WebAssemblyExportImportedDependency.js b/lib/dependencies/WebAssemblyExportImportedDependency.js index 4ae5bd881..182ddd141 100644 --- a/lib/dependencies/WebAssemblyExportImportedDependency.js +++ b/lib/dependencies/WebAssemblyExportImportedDependency.js @@ -9,7 +9,7 @@ const Dependency = require("../Dependency"); const makeSerializable = require("../util/makeSerializable"); const ModuleDependency = require("./ModuleDependency"); -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ @@ -44,7 +44,7 @@ class WebAssemblyExportImportedDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return [[this.name]]; diff --git a/lib/dependencies/WebAssemblyImportDependency.js b/lib/dependencies/WebAssemblyImportDependency.js index de23f76f1..5b53d01f5 100644 --- a/lib/dependencies/WebAssemblyImportDependency.js +++ b/lib/dependencies/WebAssemblyImportDependency.js @@ -10,7 +10,7 @@ const UnsupportedWebAssemblyFeatureError = require("../wasm-sync/UnsupportedWebA const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../WebpackError")} WebpackError */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ @@ -46,7 +46,7 @@ class WebAssemblyImportDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return [[this.name]]; diff --git a/lib/dependencies/WebpackIsIncludedDependency.js b/lib/dependencies/WebpackIsIncludedDependency.js index 431c4c8d4..8869e1402 100644 --- a/lib/dependencies/WebpackIsIncludedDependency.js +++ b/lib/dependencies/WebpackIsIncludedDependency.js @@ -11,7 +11,7 @@ const makeSerializable = require("../util/makeSerializable"); const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ @@ -33,7 +33,7 @@ class WebpackIsIncludedDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { // This doesn't use any export diff --git a/lib/dependencies/WorkerDependency.js b/lib/dependencies/WorkerDependency.js index 4ff6a28f1..17bece870 100644 --- a/lib/dependencies/WorkerDependency.js +++ b/lib/dependencies/WorkerDependency.js @@ -12,7 +12,7 @@ const ModuleDependency = require("./ModuleDependency"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../Entrypoint")} Entrypoint */ @@ -44,7 +44,7 @@ class WorkerDependency extends ModuleDependency { * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {ReferencedExports} referenced exports */ getReferencedExports(moduleGraph, runtime) { return Dependency.NO_EXPORTS_REFERENCED; diff --git a/lib/dependencies/WorkerPlugin.js b/lib/dependencies/WorkerPlugin.js index 14e03a28e..8cb86a9d8 100644 --- a/lib/dependencies/WorkerPlugin.js +++ b/lib/dependencies/WorkerPlugin.js @@ -288,8 +288,8 @@ class WorkerPlugin { } = arg2 && arg2.type === "ObjectExpression" ? parseObjectExpression(parser, arg2) : { - /** @type {Record} */ - expressions: {}, + expressions: + /** @type {Record} */ ({}), otherElements: [], /** @type {Values} */ values: {}, diff --git a/lib/dependencies/processExportInfo.js b/lib/dependencies/processExportInfo.js index ff4388557..f0149b04e 100644 --- a/lib/dependencies/processExportInfo.js +++ b/lib/dependencies/processExportInfo.js @@ -7,14 +7,13 @@ const { UsageState } = require("../ExportsInfo"); +/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -/** @typedef {string[][]} ReferencedExports */ - /** * @param {RuntimeSpec} runtime the runtime - * @param {ReferencedExports} referencedExports list of referenced exports, will be added to + * @param {RawReferencedExports} referencedExports list of referenced exports, will be added to * @param {string[]} prefix export prefix * @param {ExportInfo=} exportInfo the export info * @param {boolean} defaultPointsToSelf when true, using default will reference itself diff --git a/lib/hmr/LazyCompilationPlugin.js b/lib/hmr/LazyCompilationPlugin.js index f6e535bb6..a7791899b 100644 --- a/lib/hmr/LazyCompilationPlugin.js +++ b/lib/hmr/LazyCompilationPlugin.js @@ -28,6 +28,7 @@ const { registerNotSerializable } = require("../util/serialization"); /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").LibIdent} LibIdent */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -160,7 +161,7 @@ class LazyCompilationProxyModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return `${this.originalModule.libIdent( @@ -344,12 +345,14 @@ class LazyCompilationDependencyFactory extends ModuleFactory { /** @typedef {BackendHandler | PromiseBackendHandler} BackEnd */ +/** @typedef {(module: Module) => boolean} TestFn */ + /** * @typedef {object} Options options * @property {BackEnd} backend the backend * @property {boolean=} entries * @property {boolean=} imports - * @property {(RegExp | string | ((module: Module) => boolean))=} test additional filter for lazy compiled entrypoint modules + * @property {RegExp | string | TestFn=} test additional filter for lazy compiled entrypoint modules */ const PLUGIN_NAME = "LazyCompilationPlugin"; diff --git a/lib/hmr/lazyCompilationBackend.js b/lib/hmr/lazyCompilationBackend.js index 9ba32e066..e8dd3e9a5 100644 --- a/lib/hmr/lazyCompilationBackend.js +++ b/lib/hmr/lazyCompilationBackend.js @@ -16,6 +16,7 @@ /** @typedef {HttpServer | HttpsServer} Server */ /** @typedef {(server: Server) => void} Listen */ +/** @typedef {() => Server} CreateServerFunction */ /** * @param {Omit & { client: NonNullable}} options additional options for the backend @@ -31,7 +32,7 @@ module.exports = (options) => (compiler, callback) => { (typeof options.server === "object" && ("key" in options.server || "pfx" in options.server)); - /** @type {() => Server} */ + /** @type {CreateServerFunction} */ const createServer = typeof options.server === "function" ? options.server diff --git a/lib/ids/SyncModuleIdsPlugin.js b/lib/ids/SyncModuleIdsPlugin.js index 6b6673904..a3ff0957f 100644 --- a/lib/ids/SyncModuleIdsPlugin.js +++ b/lib/ids/SyncModuleIdsPlugin.js @@ -10,6 +10,7 @@ const { getUsedModuleIdsAndModules } = require("./IdHelpers"); /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").ModuleId} ModuleId */ /** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ const plugin = "SyncModuleIdsPlugin"; @@ -42,7 +43,7 @@ class SyncModuleIdsPlugin { * @returns {void} */ apply(compiler) { - /** @type {Map} */ + /** @type {Map} */ let data; let dataChanged = false; if (this._read) { @@ -70,7 +71,7 @@ class SyncModuleIdsPlugin { if (this._write) { compiler.hooks.emitRecords.tapAsync(plugin, (callback) => { if (!data || !dataChanged) return callback(); - /** @type {{[key: string]: string | number}} */ + /** @type {{[key: string]: ModuleId}} */ const json = {}; const sorted = [...data].sort(([a], [b]) => (a < b ? -1 : 1)); for (const [key, value] of sorted) { @@ -108,7 +109,7 @@ class SyncModuleIdsPlugin { err.module = module; compilation.errors.push(err); } - chunkGraph.setModuleId(module, /** @type {string | number} */ (id)); + chunkGraph.setModuleId(module, /** @type {ModuleId} */ (id)); usedIds.add(idAsString); } }); diff --git a/lib/javascript/BasicEvaluatedExpression.js b/lib/javascript/BasicEvaluatedExpression.js index 2318c8f91..ef5933fc3 100644 --- a/lib/javascript/BasicEvaluatedExpression.js +++ b/lib/javascript/BasicEvaluatedExpression.js @@ -8,6 +8,9 @@ /** @typedef {import("estree").Node} Node */ /** @typedef {import("./JavascriptParser").Range} Range */ /** @typedef {import("./JavascriptParser").VariableInfo} VariableInfo */ +/** @typedef {import("./JavascriptParser").Members} Members */ +/** @typedef {import("./JavascriptParser").MembersOptionals} MembersOptionals */ +/** @typedef {import("./JavascriptParser").MemberRanges} MemberRanges */ const TypeUnknown = 0; const TypeUndefined = 1; @@ -24,6 +27,10 @@ const TypeWrapped = 11; const TypeTemplateString = 12; const TypeBigInt = 13; +/** @typedef {() => Members} GetMembers */ +/** @typedef {() => MembersOptionals} GetMembersOptionals */ +/** @typedef {() => MemberRanges} GetMemberRanges */ + class BasicEvaluatedExpression { constructor() { this.type = TypeUnknown; @@ -67,11 +74,11 @@ class BasicEvaluatedExpression { this.identifier = undefined; /** @type {string | VariableInfo | undefined} */ this.rootInfo = undefined; - /** @type {(() => string[]) | undefined} */ + /** @type {GetMembers | undefined} */ this.getMembers = undefined; - /** @type {(() => boolean[]) | undefined} */ + /** @type {GetMembersOptionals | undefined} */ this.getMembersOptionals = undefined; - /** @type {(() => Range[]) | undefined} */ + /** @type {GetMemberRanges | undefined} */ this.getMemberRanges = undefined; /** @type {Node | undefined} */ this.expression = undefined; @@ -388,9 +395,9 @@ class BasicEvaluatedExpression { * Set's the value of this expression to a particular identifier and its members. * @param {string | VariableInfo} identifier identifier to set * @param {string | VariableInfo} rootInfo root info - * @param {() => string[]} getMembers members - * @param {() => boolean[]=} getMembersOptionals optional members - * @param {() => Range[]=} getMemberRanges ranges of progressively increasing sub-expressions + * @param {GetMembers} getMembers members + * @param {GetMembersOptionals=} getMembersOptionals optional members + * @param {GetMemberRanges=} getMemberRanges ranges of progressively increasing sub-expressions * @returns {this} this */ setIdentifier( diff --git a/lib/javascript/JavascriptParser.js b/lib/javascript/JavascriptParser.js index 7bc20b8e7..a620bdd4b 100644 --- a/lib/javascript/JavascriptParser.js +++ b/lib/javascript/JavascriptParser.js @@ -97,7 +97,7 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); /** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ -/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[] }} GetInfoResult */ +/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} GetInfoResult */ /** @typedef {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} StatementPathItem */ /** @typedef {(ident: string) => void} OnIdentString */ /** @typedef {(ident: string, identifier: Identifier) => void} OnIdent */ @@ -308,7 +308,7 @@ class VariableInfo { /** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */ /** @typedef {HarmonySettings | ImportSettings | CommonJsImportSettings | TopLevelSymbol | CompatibilitySettings} KnownTagData */ -/** @typedef {KnownTagData & Record} TagData */ +/** @typedef {KnownTagData | Record} TagData */ /** * @typedef {object} TagInfo @@ -317,6 +317,11 @@ class VariableInfo { * @property {TagInfo | undefined} next */ +/** @typedef {string[]} CalleeMembers */ +/** @typedef {string[]} Members */ +/** @typedef {boolean[]} MembersOptionals */ +/** @typedef {Range[]} MemberRanges */ + const SCOPE_INFO_TERMINATED_RETURN = 1; const SCOPE_INFO_TERMINATED_THROW = 2; @@ -366,7 +371,7 @@ const joinRanges = (startRange, endRange) => { * Helper function used to generate a string representation of a * [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression). * @param {string} object object to name - * @param {string[]} membersReversed reversed list of members + * @param {Members} membersReversed reversed list of members * @returns {string} member expression as a string * @example * ```js @@ -539,7 +544,7 @@ class JavascriptParser extends Parser { rename: new HookMap(() => new SyncBailHook(["initExpression"])), /** @type {HookMap>} */ assign: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ + /** @type {HookMap>} */ assignMemberChain: new HookMap( () => new SyncBailHook(["expression", "members"]) ), @@ -552,7 +557,7 @@ class JavascriptParser extends Parser { /** @type {HookMap>} */ call: new HookMap(() => new SyncBailHook(["expression"])), /** Something like "a.b()" */ - /** @type {HookMap>} */ + /** @type {HookMap>} */ callMemberChain: new HookMap( () => new SyncBailHook([ @@ -563,7 +568,7 @@ class JavascriptParser extends Parser { ]) ), /** Something like "a.b().c.d" */ - /** @type {HookMap>} */ + /** @type {HookMap>} */ memberChainOfCallMemberChain: new HookMap( () => new SyncBailHook([ @@ -575,7 +580,7 @@ class JavascriptParser extends Parser { ]) ), /** Something like "a.b().c.d()"" */ - /** @type {HookMap>} */ + /** @type {HookMap>} */ callMemberChainOfCallMemberChain: new HookMap( () => new SyncBailHook([ @@ -594,7 +599,7 @@ class JavascriptParser extends Parser { binaryExpression: new SyncBailHook(["binaryExpression"]), /** @type {HookMap>} */ expression: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ + /** @type {HookMap>} */ expressionMemberChain: new HookMap( () => new SyncBailHook([ @@ -604,7 +609,7 @@ class JavascriptParser extends Parser { "memberRanges" ]) ), - /** @type {HookMap>} */ + /** @type {HookMap>} */ unhandledExpressionMemberChain: new HookMap( () => new SyncBailHook(["expression", "members"]) ), @@ -3949,7 +3954,7 @@ class JavascriptParser extends Parser { * @param {MemberExpression} expression member expression * @param {string} name name * @param {string | VariableInfo} rootInfo root info - * @param {string[]} members members + * @param {Members} members members * @param {() => R | undefined} onUnhandled on unhandled callback */ walkMemberExpressionWithExpressionName( @@ -4031,7 +4036,7 @@ class JavascriptParser extends Parser { * @template R * @param {HookMap>} hookMap hooks the should be called * @param {Expression | Super} expr expression info - * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => string[]) => R) | undefined} fallback callback when variable in not handled by hooks + * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => Members) => R) | undefined} fallback callback when variable in not handled by hooks * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined * @param {AsArray} args args for the hook * @returns {R | undefined} result of hook @@ -4964,7 +4969,7 @@ class JavascriptParser extends Parser { /** * @param {string} name variable name - * @returns {string | ExportedVariableInfo} info for this variable + * @returns {ExportedVariableInfo} info for this variable */ getVariableInfo(name) { const value = this.scope.definitions.get(name); @@ -4976,7 +4981,7 @@ class JavascriptParser extends Parser { /** * @param {string} name variable name - * @param {string | ExportedVariableInfo} variableInfo new info for this variable + * @param {ExportedVariableInfo} variableInfo new info for this variable * @returns {void} */ setVariable(name, variableInfo) { @@ -5057,7 +5062,7 @@ class JavascriptParser extends Parser { /** * @param {Expression | Super} expression a member expression - * @returns {{ members: string[], object: Expression | Super, membersOptionals: boolean[], memberRanges: Range[] }} member names (reverse order) and remaining object + * @returns {{ members: Members, object: Expression | Super, membersOptionals: MembersOptionals, memberRanges: MemberRanges }} member names (reverse order) and remaining object */ extractMemberExpressionChain(expression) { /** @type {Node} */ @@ -5123,8 +5128,8 @@ class JavascriptParser extends Parser { return { info, name }; } - /** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} CallExpressionInfo */ - /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} ExpressionExpressionInfo */ + /** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => CalleeMembers, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges}} CallExpressionInfo */ + /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges}} ExpressionExpressionInfo */ /** * @param {Expression | Super} expression a member expression @@ -5185,7 +5190,7 @@ class JavascriptParser extends Parser { /** * @param {Expression} expression an expression - * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]} | undefined} name info + * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => Members} | undefined} name info */ getNameForExpression(expression) { return this.getMemberExpressionInfo( diff --git a/lib/javascript/JavascriptParserHelpers.js b/lib/javascript/JavascriptParserHelpers.js index 0f71ee6db..e8e7e33ac 100644 --- a/lib/javascript/JavascriptParserHelpers.js +++ b/lib/javascript/JavascriptParserHelpers.js @@ -13,6 +13,7 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); /** @typedef {import("estree").SourceLocation} SourceLocation */ /** @typedef {import("./JavascriptParser")} JavascriptParser */ /** @typedef {import("./JavascriptParser").Range} Range */ +/** @typedef {import("./BasicEvaluatedExpression").GetMembers} GetMembers */ module.exports.approve = () => true; @@ -30,7 +31,7 @@ module.exports.evaluateToBoolean = (value) => /** * @param {string} identifier identifier * @param {string} rootInfo rootInfo - * @param {() => string[]} getMembers getMembers + * @param {GetMembers} getMembers getMembers * @param {boolean | null=} truthy is truthy, null if nullish * @returns {(expression: Expression) => BasicEvaluatedExpression} callback */ diff --git a/lib/json/JsonParser.js b/lib/json/JsonParser.js index 96a1410c1..004882292 100644 --- a/lib/json/JsonParser.js +++ b/lib/json/JsonParser.js @@ -17,6 +17,8 @@ const JsonData = require("./JsonData"); /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ /** @typedef {import("../util/fs").JsonValue} JsonValue */ +/** @typedef {(input: string) => Buffer | JsonValue} ParseFn */ + const getParseJson = memoize(() => require("json-parse-even-better-errors")); class JsonParser extends Parser { @@ -38,7 +40,7 @@ class JsonParser extends Parser { source = source.toString("utf8"); } - /** @type {NonNullable} */ + /** @type {ParseFn} */ const parseFn = typeof this.options.parse === "function" ? this.options.parse diff --git a/lib/library/AssignLibraryPlugin.js b/lib/library/AssignLibraryPlugin.js index 6330a265d..f8f00df18 100644 --- a/lib/library/AssignLibraryPlugin.js +++ b/lib/library/AssignLibraryPlugin.js @@ -16,15 +16,21 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryExport} LibraryExport */ /** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ /** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @template T + * @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext + */ const KEYWORD_REGEX = /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/; @@ -90,19 +96,23 @@ const accessWithInit = (accessor, existingLength, initLast = false) => { return current; }; +/** @typedef {string[] | "global"} LibraryPrefix */ + /** * @typedef {object} AssignLibraryPluginOptions * @property {LibraryType} type - * @property {string[] | "global"} prefix name prefix + * @property {LibraryPrefix} prefix name prefix * @property {string | false} declare declare name as variable - * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name - * @property {"copy"|"assign"=} named behavior for named library name + * @property {"error" | "static" | "copy" | "assign"} unnamed behavior for unnamed library name + * @property {"copy" | "assign"=} named behavior for named library name */ +/** @typedef {string | string[]} LibraryName */ + /** * @typedef {object} AssignLibraryPluginParsed - * @property {string | string[]} name - * @property {string | string[] | undefined} export + * @property {LibraryName} name + * @property {LibraryExport=} export */ /** @@ -141,7 +151,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` ); } - const _name = /** @type {string | string[]} */ (name); + const _name = /** @type {LibraryName} */ (name); return { name: _name, export: library.export @@ -176,7 +186,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { /** * @param {Compilation} compilation the compilation - * @returns {string[]} the prefix + * @returns {LibraryPrefix} the prefix */ _getPrefix(compilation) { return this.prefix === "global" @@ -197,7 +207,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { ...prefix, ...(Array.isArray(options.name) ? options.name : [options.name]) ] - : prefix; + : /** @type {string[]} */ (prefix); return fullName.map((n) => compilation.getPath(n, { chunk @@ -312,7 +322,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { true ); - /** @type {string[]} */ + /** @type {ExportInfoName[]} */ const provided = []; for (const exportInfo of exportsInfo.orderedExports) { if (!exportInfo.provided) continue; diff --git a/lib/library/ExportPropertyLibraryPlugin.js b/lib/library/ExportPropertyLibraryPlugin.js index 1a00fe6b9..e5050d4a0 100644 --- a/lib/library/ExportPropertyLibraryPlugin.js +++ b/lib/library/ExportPropertyLibraryPlugin.js @@ -15,6 +15,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryExport} LibraryExport */ /** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ @@ -23,7 +24,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); /** * @typedef {object} ExportPropertyLibraryPluginParsed - * @property {string | string[]} export + * @property {LibraryExport=} export */ /** @@ -51,7 +52,7 @@ class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin { */ parseOptions(library) { return { - export: /** @type {string | string[]} */ (library.export) + export: library.export }; } diff --git a/lib/library/ModuleLibraryPlugin.js b/lib/library/ModuleLibraryPlugin.js index f8c272836..7f562df69 100644 --- a/lib/library/ModuleLibraryPlugin.js +++ b/lib/library/ModuleLibraryPlugin.js @@ -17,6 +17,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryExport} LibraryExport */ /** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ @@ -37,7 +38,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); /** * @typedef {object} ModuleLibraryPluginParsed * @property {string} name - * @property {string | string[]=} export + * @property {LibraryExport=} export */ const PLUGIN_NAME = "ModuleLibraryPlugin"; diff --git a/lib/library/UmdLibraryPlugin.js b/lib/library/UmdLibraryPlugin.js index 1eca63784..e0269e027 100644 --- a/lib/library/UmdLibraryPlugin.js +++ b/lib/library/UmdLibraryPlugin.js @@ -31,9 +31,11 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); const accessorToObjectAccess = (accessor) => accessor.map((a) => `[${JSON.stringify(a)}]`).join(""); +/** @typedef {string | string[]} Accessor */ + /** * @param {string|undefined} base the path prefix - * @param {string|string[]} accessor the accessor + * @param {Accessor} accessor the accessor * @param {string=} joinWith the element separator * @returns {string} the path */ @@ -53,8 +55,6 @@ const accessorAccess = (base, accessor, joinWith = ", ") => { .join(joinWith); }; -/** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */ - /** * @typedef {object} UmdLibraryPluginOptions * @property {LibraryType} type @@ -192,10 +192,9 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin { /** @type {RequestRecord} */ (request).root; } - return `root${accessorToObjectAccess( - /** @type {string[]} */ - ([...(Array.isArray(request) ? request : [request])]) - )}`; + return `root${accessorToObjectAccess([ + ...(Array.isArray(request) ? request : [request]) + ])}`; }) .join(", ") ); @@ -248,17 +247,14 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin { .join(", "); /** - * @param {string| string[]} library library name + * @param {Accessor} library library name * @returns {string} stringified library name */ const libraryName = (library) => JSON.stringify( replaceKeys( /** @type {string} */ - ( - /** @type {string[]} */ - ([...(Array.isArray(library) ? library : [library])]).pop() - ) + ([...(Array.isArray(library) ? library : [library])].pop()) ) ); @@ -322,7 +318,7 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin { "commonjs" )} else if(typeof exports === 'object')\n` + ` exports[${libraryName( - /** @type {string | string[]} */ + /** @type {Accessor} */ (names.commonjs || names.root) )}] = factory(${externalsRequireArray( "commonjs" @@ -330,7 +326,7 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin { ` ${replaceKeys( accessorAccess( "root", - /** @type {string | string[]} */ + /** @type {Accessor} */ (names.root || names.commonjs) ) )} = factory(${externalsRootArray(externals)});\n` diff --git a/lib/logging/Logger.js b/lib/logging/Logger.js index d785e0c00..2987e2a59 100644 --- a/lib/logging/Logger.js +++ b/lib/logging/Logger.js @@ -35,9 +35,11 @@ const LOG_SYMBOL = Symbol("webpack logger raw log method"); const TIMERS_SYMBOL = Symbol("webpack logger times"); const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); +/** @typedef {EXPECTED_ANY[]} Args */ + class WebpackLogger { /** - * @param {(type: LogTypeEnum, args?: EXPECTED_ANY[]) => void} log log function + * @param {(type: LogTypeEnum, args?: Args) => void} log log function * @param {(name: string | (() => string)) => WebpackLogger} getChildLogger function to create child logger */ constructor(log, getChildLogger) { @@ -46,35 +48,35 @@ class WebpackLogger { } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ error(...args) { this[LOG_SYMBOL](LogType.error, args); } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ warn(...args) { this[LOG_SYMBOL](LogType.warn, args); } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ info(...args) { this[LOG_SYMBOL](LogType.info, args); } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ log(...args) { this[LOG_SYMBOL](LogType.log, args); } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ debug(...args) { this[LOG_SYMBOL](LogType.debug, args); @@ -82,7 +84,7 @@ class WebpackLogger { /** * @param {EXPECTED_ANY} assertion assertion - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ assert(assertion, ...args) { if (!assertion) { @@ -99,21 +101,21 @@ class WebpackLogger { } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ status(...args) { this[LOG_SYMBOL](LogType.status, args); } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ group(...args) { this[LOG_SYMBOL](LogType.group, args); } /** - * @param {...EXPECTED_ANY} args args + * @param {Args} args args */ groupCollapsed(...args) { this[LOG_SYMBOL](LogType.groupCollapsed, args); diff --git a/lib/logging/createConsoleLogger.js b/lib/logging/createConsoleLogger.js index 072ce19ae..39e72f079 100644 --- a/lib/logging/createConsoleLogger.js +++ b/lib/logging/createConsoleLogger.js @@ -10,26 +10,27 @@ const { LogType } = require("./Logger"); /** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ /** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ /** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ +/** @typedef {import("./Logger").Args} Args */ /** @typedef {(item: string) => boolean} FilterFunction */ -/** @typedef {(value: string, type: LogTypeEnum, args?: EXPECTED_ANY[]) => void} LoggingFunction */ +/** @typedef {(value: string, type: LogTypeEnum, args?: Args) => void} LoggingFunction */ /** * @typedef {object} LoggerConsole * @property {() => void} clear * @property {() => void} trace - * @property {(...args: EXPECTED_ANY[]) => void} info - * @property {(...args: EXPECTED_ANY[]) => void} log - * @property {(...args: EXPECTED_ANY[]) => void} warn - * @property {(...args: EXPECTED_ANY[]) => void} error - * @property {(...args: EXPECTED_ANY[]) => void=} debug - * @property {(...args: EXPECTED_ANY[]) => void=} group - * @property {(...args: EXPECTED_ANY[]) => void=} groupCollapsed - * @property {(...args: EXPECTED_ANY[]) => void=} groupEnd - * @property {(...args: EXPECTED_ANY[]) => void=} status - * @property {(...args: EXPECTED_ANY[]) => void=} profile - * @property {(...args: EXPECTED_ANY[]) => void=} profileEnd - * @property {(...args: EXPECTED_ANY[]) => void=} logTime + * @property {(...args: Args) => void} info + * @property {(...args: Args) => void} log + * @property {(...args: Args) => void} warn + * @property {(...args: Args) => void} error + * @property {(...args: Args) => void=} debug + * @property {(...args: Args) => void=} group + * @property {(...args: Args) => void=} groupCollapsed + * @property {(...args: Args) => void=} groupEnd + * @property {(...args: Args) => void=} status + * @property {(...args: Args) => void=} profile + * @property {(...args: Args) => void=} profileEnd + * @property {(...args: Args) => void=} logTime */ /** @@ -94,7 +95,7 @@ module.exports = ({ level = "info", debug = false, console }) => { /** * @param {string} name name of the logger * @param {LogTypeEnum} type type of the log entry - * @param {EXPECTED_ANY[]=} args arguments of the log entry + * @param {Args=} args arguments of the log entry * @returns {void} */ const logger = (name, type, args) => { diff --git a/lib/optimize/ConcatenatedModule.js b/lib/optimize/ConcatenatedModule.js index 97df2fdc5..4a6854454 100644 --- a/lib/optimize/ConcatenatedModule.js +++ b/lib/optimize/ConcatenatedModule.js @@ -71,6 +71,8 @@ const { /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").LibIdent} LibIdent */ +/** @typedef {import("../Module").NameForCondition} NameForCondition */ /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -102,27 +104,23 @@ const { // fix eslint-scope to support class properties correctly // cspell:word Referencer -const ReferencerClass = /** @type {EXPECTED_ANY} */ (Referencer); +const ReferencerClass = Referencer; if (!ReferencerClass.prototype.PropertyDefinition) { ReferencerClass.prototype.PropertyDefinition = ReferencerClass.prototype.Property; } -/** - * @typedef {object} ReexportInfo - * @property {Module} module - * @property {string[]} export - */ - /** @typedef {RawBinding | SymbolBinding} Binding */ +/** @typedef {string[]} ExportName */ + /** * @typedef {object} RawBinding * @property {ModuleInfo} info * @property {string} rawName * @property {string=} comment - * @property {string[]} ids - * @property {string[]} exportName + * @property {ExportName} ids + * @property {ExportName} exportName */ /** @@ -130,8 +128,8 @@ if (!ReferencerClass.prototype.PropertyDefinition) { * @property {ConcatenatedModuleInfo} info * @property {string} name * @property {string=} comment - * @property {string[]} ids - * @property {string[]} exportName + * @property {ExportName} ids + * @property {ExportName} exportName */ /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ @@ -269,7 +267,7 @@ const joinIterableWithComma = (iterable) => { /** * @param {ModuleGraph} moduleGraph the module graph * @param {ModuleInfo} info module info - * @param {string[]} exportName exportName + * @param {ExportName} exportName exportName * @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap * @param {RuntimeSpec} runtime for which runtime * @param {RequestShortener} requestShortener the request shortener @@ -478,7 +476,7 @@ const getFinalBinding = ( } const directExport = info.exportMap && info.exportMap.get(exportId); if (directExport) { - const usedName = /** @type {string[]} */ ( + const usedName = /** @type {ExportName} */ ( exportsInfo.getUsedName(exportName, runtime) ); if (!usedName) { @@ -541,7 +539,7 @@ const getFinalBinding = ( ); } if (info.namespaceExportSymbol) { - const usedName = /** @type {string[]} */ ( + const usedName = /** @type {ExportName} */ ( exportsInfo.getUsedName(exportName, runtime) ); return { @@ -559,7 +557,7 @@ const getFinalBinding = ( } case "external": { - const used = /** @type {string[]} */ ( + const used = /** @type {ExportName} */ ( exportsInfo.getUsedName(exportName, runtime) ); if (!used) { @@ -589,7 +587,7 @@ const getFinalBinding = ( /** * @param {ModuleGraph} moduleGraph the module graph * @param {ModuleInfo} info module info - * @param {string[]} exportName exportName + * @param {ExportName} exportName exportName * @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap * @param {RuntimeSpec} runtime for which runtime * @param {RequestShortener} requestShortener the request shortener @@ -795,14 +793,14 @@ class ConcatenatedModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return this.rootModule.libIdent(options); } /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path) */ nameForCondition() { return this.rootModule.nameForCondition(); diff --git a/lib/optimize/SideEffectsFlagPlugin.js b/lib/optimize/SideEffectsFlagPlugin.js index 6e77d6087..ea861d26c 100644 --- a/lib/optimize/SideEffectsFlagPlugin.js +++ b/lib/optimize/SideEffectsFlagPlugin.js @@ -36,11 +36,7 @@ const formatLocation = require("../formatLocation"); * @property {boolean} checked if the export is conditional */ -/** - * @typedef {object} ReexportInfo - * @property {Map} static - * @property {Map>} dynamic - */ +/** @typedef {string | boolean | string[] | undefined} SideEffectsFlagValue */ /** @typedef {Map} CacheItem */ @@ -104,9 +100,7 @@ class SideEffectsFlagPlugin { } const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects( resolveData.relativePath, - /** @type {string | boolean | string[] | undefined} */ ( - sideEffects - ), + /** @type {SideEffectsFlagValue} */ (sideEffects), /** @type {CacheItem} */ (cache) ); module.factoryMeta.sideEffectFree = !hasSideEffects; @@ -396,7 +390,7 @@ class SideEffectsFlagPlugin { /** * @param {string} moduleName the module name - * @param {undefined | boolean | string | string[]} flagValue the flag value + * @param {SideEffectsFlagValue} flagValue the flag value * @param {Map} cache cache for glob to regexp * @returns {boolean | undefined} true, when the module has side effects, undefined or false when not */ diff --git a/lib/optimize/SplitChunksPlugin.js b/lib/optimize/SplitChunksPlugin.js index 4c0b97c45..229adb261 100644 --- a/lib/optimize/SplitChunksPlugin.js +++ b/lib/optimize/SplitChunksPlugin.js @@ -36,10 +36,8 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); /** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ /** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ -/** @typedef {Record} SplitChunksSizes */ - /** - * @callback ChunkFilterFunction + * @callback ChunkFilterFn * @param {Chunk} chunk * @returns {boolean | undefined} */ @@ -51,12 +49,17 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); * @returns {number} */ +/** @typedef {string} SourceType */ +/** @typedef {SourceType[]} SourceTypes */ +/** @typedef {SourceType[]} DefaultSizeTypes */ +/** @typedef {Record} SplitChunksSizes */ + /** * @typedef {object} CacheGroupSource * @property {string} key * @property {number=} priority - * @property {GetName=} getName - * @property {ChunkFilterFunction=} chunksFilter + * @property {GetNameFn=} getName + * @property {ChunkFilterFn=} chunksFilter * @property {boolean=} enforce * @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} minSizeReduction @@ -78,8 +81,8 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); * @typedef {object} CacheGroup * @property {string} key * @property {number} priority - * @property {GetName=} getName - * @property {ChunkFilterFunction} chunksFilter + * @property {GetNameFn=} getName + * @property {ChunkFilterFn} chunksFilter * @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} minSizeReduction * @property {SplitChunksSizes} minRemainingSize @@ -102,7 +105,7 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); /** * @typedef {object} FallbackCacheGroup - * @property {ChunkFilterFunction} chunksFilter + * @property {ChunkFilterFn} chunksFilter * @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} maxAsyncSize * @property {SplitChunksSizes} maxInitialSize @@ -123,17 +126,17 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); */ /** - * @callback GetName + * @callback GetNameFn * @param {Module} module * @param {Chunk[]} chunks * @param {string} key - * @returns {string=} + * @returns {string | undefined} */ /** * @typedef {object} SplitChunksOptions - * @property {ChunkFilterFunction} chunksFilter - * @property {string[]} defaultSizeTypes + * @property {ChunkFilterFn} chunksFilter + * @property {DefaultSizeTypes} defaultSizeTypes * @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} minSizeReduction * @property {SplitChunksSizes} minRemainingSize @@ -147,7 +150,7 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); * @property {TemplatePath=} filename * @property {string} automaticNameDelimiter * @property {GetCacheGroups} getCacheGroups - * @property {GetName} getName + * @property {GetNameFn} getName * @property {boolean} usedExports * @property {FallbackCacheGroup} fallbackCacheGroup */ @@ -158,13 +161,13 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning"); * @property {CacheGroup} cacheGroup * @property {number} cacheGroupIndex * @property {string=} name - * @property {Record} sizes + * @property {Record} sizes * @property {Set} chunks * @property {Set} reusableChunks * @property {Set} chunksKeys */ -/** @type {GetName} */ +/** @type {GetNameFn} */ const defaultGetName = () => undefined; const deterministicGroupingForModules = @@ -285,7 +288,7 @@ const ALL_CHUNK_FILTER = (_chunk) => true; /** * @param {OptimizationSplitChunksSizes | undefined} value the sizes - * @param {string[]} defaultSizeTypes the default size types + * @param {DefaultSizeTypes} defaultSizeTypes the default size types * @returns {SplitChunksSizes} normalized representation */ const normalizeSizes = (value, defaultSizeTypes) => { @@ -378,7 +381,7 @@ const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => { /** * @param {SplitChunksSizes} sizes the sizes * @param {SplitChunksSizes} minSize the min sizes - * @returns {undefined | string[]} list of size types that are below min size + * @returns {undefined | SourceTypes} list of size types that are below min size */ const getViolatingMinSizes = (sizes, minSize) => { let list; @@ -407,20 +410,20 @@ const totalSize = (sizes) => { /** * @param {OptimizationSplitChunksCacheGroup["name"]} name the chunk name - * @returns {GetName | undefined} a function to get the name of the chunk + * @returns {GetNameFn | undefined} a function to get the name of the chunk */ const normalizeName = (name) => { if (typeof name === "string") { return () => name; } if (typeof name === "function") { - return /** @type {GetName} */ (name); + return /** @type {GetNameFn} */ (name); } }; /** * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option - * @returns {ChunkFilterFunction | undefined} the chunk filter function + * @returns {ChunkFilterFn | undefined} the chunk filter function */ const normalizeChunksFilter = (chunks) => { if (chunks === "initial") { @@ -442,7 +445,7 @@ const normalizeChunksFilter = (chunks) => { /** * @param {undefined | GetCacheGroups | Record} cacheGroups the cache group options - * @param {string[]} defaultSizeTypes the default size types + * @param {DefaultSizeTypes} defaultSizeTypes the default size types * @returns {GetCacheGroups} a function to get the cache groups */ const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { @@ -585,7 +588,7 @@ const checkModuleLayer = (test, module) => { /** * @param {OptimizationSplitChunksCacheGroup} options the group options * @param {string} key key of cache group - * @param {string[]} defaultSizeTypes the default size types + * @param {DefaultSizeTypes} defaultSizeTypes the default size types * @returns {CacheGroupSource} the normalized cached group */ const createCacheGroupSource = (options, key, defaultSizeTypes) => { @@ -652,7 +655,7 @@ module.exports = class SplitChunksPlugin { /** @type {SplitChunksOptions} */ this.options = { chunksFilter: - /** @type {ChunkFilterFunction} */ + /** @type {ChunkFilterFn} */ (normalizeChunksFilter(options.chunks || "all")), defaultSizeTypes, minSize, @@ -683,13 +686,13 @@ module.exports = class SplitChunksPlugin { defaultSizeTypes ), getName: options.name - ? /** @type {GetName} */ (normalizeName(options.name)) + ? /** @type {GetNameFn} */ (normalizeName(options.name)) : defaultGetName, automaticNameDelimiter: options.automaticNameDelimiter || "-", usedExports: options.usedExports || false, fallbackCacheGroup: { chunksFilter: - /** @type {ChunkFilterFunction} */ + /** @type {ChunkFilterFn} */ ( normalizeChunksFilter( fallbackCacheGroup.chunks || options.chunks || "all" @@ -1067,14 +1070,14 @@ module.exports = class SplitChunksPlugin { * @property {bigint | Chunk} key a key of the list */ - /** @type {WeakMap | Chunk, WeakMap>} */ + /** @type {WeakMap | Chunk, WeakMap>} */ const selectedChunksCacheByChunksSet = new WeakMap(); /** * get list and key by applying the filter function to the list * It is cached for performance reasons * @param {Set | Chunk} chunks list of chunks - * @param {ChunkFilterFunction} chunkFilter filter function for chunks + * @param {ChunkFilterFn} chunkFilter filter function for chunks * @returns {SelectedChunksResult} list and key */ const getSelectedChunks = (chunks, chunkFilter) => { @@ -1135,7 +1138,7 @@ module.exports = class SplitChunksPlugin { // Determine name for split chunk const name = - /** @type {GetName} */ + /** @type {GetNameFn} */ (cacheGroup.getName)(module, selectedChunks, cacheGroup.key); // Check if the name is ok const existingChunk = name && compilation.namedChunks.get(name); @@ -1297,7 +1300,7 @@ module.exports = class SplitChunksPlugin { const { chunks: selectedChunks, key: selectedChunksKey } = getSelectedChunks( chunkCombination, - /** @type {ChunkFilterFunction} */ + /** @type {ChunkFilterFn} */ (cacheGroup.chunksFilter) ); @@ -1319,7 +1322,7 @@ module.exports = class SplitChunksPlugin { /** * @param {ChunksInfoItem} info entry - * @param {string[]} sourceTypes source types to be removed + * @param {SourceTypes} sourceTypes source types to be removed */ const removeModulesWithSourceType = (info, sourceTypes) => { for (const module of info.modules) { diff --git a/lib/performance/SizeLimitsPlugin.js b/lib/performance/SizeLimitsPlugin.js index a57f2a797..1ad41e3ff 100644 --- a/lib/performance/SizeLimitsPlugin.js +++ b/lib/performance/SizeLimitsPlugin.js @@ -31,6 +31,7 @@ const NoAsyncChunksWarning = require("./NoAsyncChunksWarning"); * @property {string[]} files */ +/** @type {WeakSet} */ const isOverSizeLimitSet = new WeakSet(); /** @@ -55,7 +56,7 @@ module.exports = class SizeLimitsPlugin { } /** - * @param {ChunkGroup | Source} thing the resource to test + * @param {Entrypoint | ChunkGroup | Source} thing the resource to test * @returns {boolean} true if over the limit */ static isOverSizeLimit(thing) { diff --git a/lib/schemes/VirtualUrlPlugin.js b/lib/schemes/VirtualUrlPlugin.js index 70399eb26..ef2a05f84 100644 --- a/lib/schemes/VirtualUrlPlugin.js +++ b/lib/schemes/VirtualUrlPlugin.js @@ -20,18 +20,21 @@ const { parseResourceWithoutFragment } = require("../util/identifier"); const PLUGIN_NAME = "VirtualUrlPlugin"; const DEFAULT_SCHEME = "virtual"; +/** @typedef {(loaderContext: LoaderContext) => Promise | string | Buffer} SourceFn */ +/** @typedef {() => string} VersionFn */ + /** * @typedef {object} VirtualModuleConfig - * @property {string=} type - The module type - * @property {(loaderContext: LoaderContext) => Promise | string} source - The source function - * @property {(() => string) | true | string=} version - Optional version function or value + * @property {string=} type the module type + * @property {SourceFn} source the source function + * @property {VersionFn | true | string=} version optional version function or value */ /** - * @typedef {string | ((loaderContext: LoaderContext) => Promise | string) | VirtualModuleConfig} VirtualModuleInput + * @typedef {string | SourceFn | VirtualModuleConfig} VirtualModuleInput */ -/** @typedef {{[key: string]: VirtualModuleInput}} VirtualModules */ +/** @typedef {{ [key: string]: VirtualModuleInput }} VirtualModules */ /** * Normalizes a virtual module definition into a standard format @@ -59,13 +62,13 @@ function normalizeModule(virtualConfig) { * Normalizes all virtual modules with the given scheme * @param {VirtualModules} virtualConfigs The virtual modules to normalize * @param {string} scheme The URL scheme to use - * @returns {{[key: string]: VirtualModuleConfig}} The normalized virtual modules + * @returns {{ [key: string]: VirtualModuleConfig }} The normalized virtual modules */ function normalizeModules(virtualConfigs, scheme) { return Object.keys(virtualConfigs).reduce((pre, id) => { pre[toVid(id, scheme)] = normalizeModule(virtualConfigs[id]); return pre; - }, /** @type {{[key: string]: VirtualModuleConfig}} */ ({})); + }, /** @type {{ [key: string]: VirtualModuleConfig }} */ ({})); } /** @@ -204,7 +207,7 @@ class VirtualUrlPlugin { /** * Get the cache version for a given version value - * @param {(() => string) | true | string} version The version value or function + * @param {VersionFn | true | string} version The version value or function * @returns {string | undefined} The cache version */ getCacheVersion(version) { diff --git a/lib/serialization/NullPrototypeObjectSerializer.js b/lib/serialization/NullPrototypeObjectSerializer.js index 32adaeaae..1416b4f23 100644 --- a/lib/serialization/NullPrototypeObjectSerializer.js +++ b/lib/serialization/NullPrototypeObjectSerializer.js @@ -7,6 +7,8 @@ /** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {string[]} Keys */ + class NullPrototypeObjectSerializer { /** * @template {object} T @@ -14,7 +16,7 @@ class NullPrototypeObjectSerializer { * @param {ObjectSerializerContext} context context */ serialize(obj, context) { - /** @type {string[]} */ + /** @type {Keys} */ const keys = Object.keys(obj); for (const key of keys) { context.write(key); @@ -33,9 +35,9 @@ class NullPrototypeObjectSerializer { deserialize(context) { /** @type {T} */ const obj = Object.create(null); - /** @type {string[]} */ + /** @type {Keys} */ const keys = []; - /** @type {string | null} */ + /** @type {Keys[number] | null} */ let key = context.read(); while (key !== null) { keys.push(key); diff --git a/lib/sharing/ConsumeSharedModule.js b/lib/sharing/ConsumeSharedModule.js index d307413bb..183a4b924 100644 --- a/lib/sharing/ConsumeSharedModule.js +++ b/lib/sharing/ConsumeSharedModule.js @@ -24,6 +24,7 @@ const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependen /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").LibIdent} LibIdent */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -101,7 +102,7 @@ class ConsumeSharedModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { const { shareKey, shareScope, import: request } = this.options; diff --git a/lib/sharing/ProvideSharedModule.js b/lib/sharing/ProvideSharedModule.js index 83ba653fd..fc1392388 100644 --- a/lib/sharing/ProvideSharedModule.js +++ b/lib/sharing/ProvideSharedModule.js @@ -19,6 +19,7 @@ const ProvideForSharedDependency = require("./ProvideForSharedDependency"); /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").LibIdent} LibIdent */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").SourceTypes} SourceTypes */ @@ -64,7 +65,7 @@ class ProvideSharedModule extends Module { /** * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @returns {LibIdent | null} an identifier for library inclusion */ libIdent(options) { return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${ diff --git a/lib/stats/DefaultStatsFactoryPlugin.js b/lib/stats/DefaultStatsFactoryPlugin.js index d605cd3c7..980e36222 100644 --- a/lib/stats/DefaultStatsFactoryPlugin.js +++ b/lib/stats/DefaultStatsFactoryPlugin.js @@ -44,10 +44,12 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").NameForCondition} NameForCondition */ /** @typedef {import("../Module").BuildInfo} BuildInfo */ /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ /** @typedef {import("../ModuleProfile")} ModuleProfile */ /** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ /** * @template T @@ -109,6 +111,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); */ /** @typedef {KnownStatsAsset & Record} StatsAsset */ +/** @typedef {string[]} ChunkIdHints */ /** * @typedef {object} KnownStatsAsset * @property {string} type @@ -121,10 +124,10 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {StatsAsset[]=} related * @property {ChunkId[]=} chunks * @property {ChunkName[]=} chunkNames - * @property {string[]=} chunkIdHints + * @property {ChunkIdHints=} chunkIdHints * @property {ChunkId[]=} auxiliaryChunks * @property {ChunkName[]=} auxiliaryChunkNames - * @property {string[]=} auxiliaryChunkIdHints + * @property {ChunkIdHints=} auxiliaryChunkIdHints * @property {number=} filteredRelated * @property {boolean=} isOverSizeLimit */ @@ -133,7 +136,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); /** * @typedef {object} KnownStatsChunkGroup * @property {ChunkName=} name - * @property {(string | number)[]=} chunks + * @property {ChunkId[]=} chunks * @property {({ name: string, size?: number })[]=} assets * @property {number=} filteredAssets * @property {number=} assetsSize @@ -154,7 +157,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {(string | null)=} layer * @property {string=} identifier * @property {string=} name - * @property {(string | null)=} nameForCondition + * @property {NameForCondition | null=} nameForCondition * @property {number=} index * @property {number=} preOrderIndex * @property {number=} index2 @@ -168,10 +171,10 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {boolean=} cached * @property {boolean=} optional * @property {boolean=} orphan - * @property {string | number=} id - * @property {string | number | null=} issuerId - * @property {(string | number)[]=} chunks - * @property {(string | number)[]=} assets + * @property {ModuleId=} id + * @property {ModuleId | null=} issuerId + * @property {ChunkId[]=} chunks + * @property {string[]=} assets * @property {boolean=} dependent * @property {(string | null)=} issuer * @property {(string | null)=} issuerName @@ -181,8 +184,8 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {number=} warnings * @property {StatsProfile=} profile * @property {StatsModuleReason[]=} reasons - * @property {(boolean | null | string[])=} usedExports - * @property {(string[] | null)=} providedExports + * @property {boolean | null | ExportInfoName[]=} usedExports + * @property {ExportInfoName[] | null=} providedExports * @property {string[]=} optimizationBailout * @property {(number | null)=} depth * @property {StatsModule[]=} modules @@ -265,7 +268,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {string} moduleName * @property {string} loc * @property {string} request - * @property {(string | number)=} moduleId + * @property {ModuleId=} moduleId */ /** @typedef {KnownStatsModuleTraceItem & Record} StatsModuleTraceItem */ @@ -550,6 +553,7 @@ const SIMPLE_EXTRACTORS = { ); } if (!context.cachedGetErrors) { + /** @type {WeakMap} */ const map = new WeakMap(); context.cachedGetErrors = (compilation) => map.get(compilation) || @@ -559,6 +563,7 @@ const SIMPLE_EXTRACTORS = { ); } if (!context.cachedGetWarnings) { + /** @type {WeakMap} */ const map = new WeakMap(); context.cachedGetWarnings = (compilation) => map.get(compilation) || @@ -905,7 +910,10 @@ const SIMPLE_EXTRACTORS = { let filtered = 0; if (options.errorDetails === "auto" && rawErrors.length >= 3) { filtered = rawErrors - .map((e) => typeof e !== "string" && e.details) + .map( + (e) => + typeof e !== "string" && /** @type {WebpackError} */ (e).details + ) .filter(Boolean).length; } if ( @@ -939,7 +947,10 @@ const SIMPLE_EXTRACTORS = { let filtered = 0; if (options.errorDetails === "auto") { filtered = cachedGetWarnings(compilation) - .map((e) => typeof e !== "string" && e.details) + .map( + (e) => + typeof e !== "string" && /** @type {WebpackError} */ (e).details + ) .filter(Boolean).length; } if ( @@ -1518,7 +1529,7 @@ const SIMPLE_EXTRACTORS = { object.id = /** @type {ChunkId} */ (chunk.id); }, chunkRelations: (object, chunk, _context) => { - /** @typedef {Set} ChunkRelations */ + /** @typedef {Set} ChunkRelations */ /** @type {ChunkRelations} */ const parents = new Set(); /** @type {ChunkRelations} */ diff --git a/lib/stats/DefaultStatsPresetPlugin.js b/lib/stats/DefaultStatsPresetPlugin.js index 016e7d506..4a8828e0f 100644 --- a/lib/stats/DefaultStatsPresetPlugin.js +++ b/lib/stats/DefaultStatsPresetPlugin.js @@ -284,10 +284,15 @@ const DEFAULTS = { colors: () => false }; +/** + * @template T + * @typedef {(value: T, ...args: EXPECTED_ANY[]) => boolean} NormalizeFunction + */ + /** * @template {string} T - * @param {string | ({ test: (value: T) => boolean }) | ((value: T, ...args: EXPECTED_ANY[]) => boolean) | boolean} item item to normalize - * @returns {(value: T, ...args: EXPECTED_ANY[]) => boolean} normalize fn + * @param {string | ({ test: (value: T) => boolean }) | NormalizeFunction | boolean} item item to normalize + * @returns {NormalizeFunction} normalize fn */ const normalizeFilter = (item) => { if (typeof item === "string") { @@ -303,12 +308,19 @@ const normalizeFilter = (item) => { return () => item; } - return /** @type {(value: T, ...args: EXPECTED_ANY[]) => boolean} */ (item); + return /** @type {NormalizeFunction} */ (item); }; /** @typedef {keyof (KnownNormalizedStatsOptions | StatsOptions)} NormalizerKeys */ /** @typedef {{ [Key in NormalizerKeys]?: (value: StatsOptions[Key]) => KnownNormalizedStatsOptions[Key] }} Normalizers */ +/** + * @callback WarningFilterFn + * @param {StatsError} warning warning + * @param {string} warningString warning string + * @returns {boolean} result + */ + /** @type {Normalizers} */ const NORMALIZER = { excludeModules: (value) => { @@ -329,12 +341,6 @@ const NORMALIZER = { if (!Array.isArray(value)) { value = value ? [value] : []; } - /** - * @callback WarningFilterFn - * @param {StatsError} warning warning - * @param {string} warningString warning string - * @returns {boolean} result - */ return value.map( /** * @param {StatsOptions["warningsFilter"]} filter a warning filter diff --git a/lib/stats/StatsFactory.js b/lib/stats/StatsFactory.js index be26c6a11..d74108e55 100644 --- a/lib/stats/StatsFactory.js +++ b/lib/stats/StatsFactory.js @@ -50,8 +50,8 @@ const smartGrouping = require("../util/smartGrouping"); * @property {Map} compilationFileToChunks * @property {Map} compilationAuxiliaryFileToChunks * @property {RuntimeSpec} runtime - * @property {(compilation: Compilation) => WebpackError[]} cachedGetErrors - * @property {(compilation: Compilation) => WebpackError[]} cachedGetWarnings + * @property {(compilation: Compilation) => Error[]} cachedGetErrors + * @property {(compilation: Compilation) => Error[]} cachedGetWarnings */ /** @typedef {KnownStatsFactoryContext & Record} StatsFactoryContext */ diff --git a/lib/util/chainedImports.js b/lib/util/chainedImports.js index 295233b7d..e7e30f4ca 100644 --- a/lib/util/chainedImports.js +++ b/lib/util/chainedImports.js @@ -10,6 +10,8 @@ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {Range[]} IdRanges */ + /** * @summary Get the subset of ids and their corresponding range in an id chain that should be re-rendered by webpack. * Only those in the chain that are actually referring to namespaces or imports should be re-rendered. @@ -18,7 +20,7 @@ * because minifiers treat quoted accessors differently. e.g. import { a } from "./module"; a["b"] vs a.b * @param {string[]} untrimmedIds chained ids * @param {Range} untrimmedRange range encompassing allIds - * @param {Range[] | undefined} ranges cumulative range of ids for each of allIds + * @param {IdRanges | undefined} ranges cumulative range of ids for each of allIds * @param {ModuleGraph} moduleGraph moduleGraph * @param {Dependency} dependency dependency * @returns {{trimmedIds: string[], trimmedRange: Range}} computed trimmed ids and cumulative range of those ids diff --git a/lib/util/compileBooleanMatcher.js b/lib/util/compileBooleanMatcher.js index 3b1bbe19b..4ca1b81ce 100644 --- a/lib/util/compileBooleanMatcher.js +++ b/lib/util/compileBooleanMatcher.js @@ -56,11 +56,13 @@ const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => { return (value) => `!/^${negativeRegexp}$/.test(${value})`; }; +/** @typedef {string[][]} ListOfCommonItems */ + /** * @param {Set} itemsSet items set * @param {(str: string) => string | false} getKey get key function * @param {(str: string[]) => boolean} condition condition - * @returns {string[][]} list of common items + * @returns {ListOfCommonItems} list of common items */ const popCommonItems = (itemsSet, getKey, condition) => { /** @type {Map} */ @@ -77,7 +79,7 @@ const popCommonItems = (itemsSet, getKey, condition) => { list.push(item); } } - /** @type {string[][]} */ + /** @type {ListOfCommonItems} */ const result = []; for (const list of map.values()) { if (condition(list)) { diff --git a/lib/util/deterministicGrouping.js b/lib/util/deterministicGrouping.js index 4331a3e47..a34357ce8 100644 --- a/lib/util/deterministicGrouping.js +++ b/lib/util/deterministicGrouping.js @@ -70,9 +70,11 @@ const getName = (a, b, usedNames) => { return a; }; +/** @typedef {Record} Sizes */ + /** - * @param {Record} total total size - * @param {Record} size single size + * @param {Sizes} total total size + * @param {Sizes} size single size * @returns {void} */ const addSizeTo = (total, size) => { @@ -82,8 +84,8 @@ const addSizeTo = (total, size) => { }; /** - * @param {Record} total total size - * @param {Record} size single size + * @param {Sizes} total total size + * @param {Sizes} size single size * @returns {void} */ const subtractSizeFrom = (total, size) => { @@ -95,7 +97,7 @@ const subtractSizeFrom = (total, size) => { /** * @template T * @param {Iterable>} nodes some nodes - * @returns {Record} total size + * @returns {Sizes} total size */ const sumSize = (nodes) => { const sum = Object.create(null); @@ -106,8 +108,8 @@ const sumSize = (nodes) => { }; /** - * @param {Record} size size - * @param {Record} maxSize minimum size + * @param {Sizes} size size + * @param {Sizes} maxSize minimum size * @returns {boolean} true, when size is too big */ const isTooBig = (size, maxSize) => { @@ -121,8 +123,8 @@ const isTooBig = (size, maxSize) => { }; /** - * @param {Record} size size - * @param {Record} minSize minimum size + * @param {Sizes} size size + * @param {Sizes} minSize minimum size * @returns {boolean} true, when size is too small */ const isTooSmall = (size, minSize) => { @@ -136,8 +138,8 @@ const isTooSmall = (size, minSize) => { }; /** - * @param {Record} size size - * @param {Record} minSize minimum size + * @param {Sizes} size size + * @param {Sizes} minSize minimum size * @returns {Set} set of types that are too small */ const getTooSmallTypes = (size, minSize) => { @@ -166,7 +168,7 @@ const getNumberOfMatchingSizeTypes = (size, types) => { }; /** - * @param {Record} size size + * @param {Sizes} size size * @param {Set} types types * @returns {number} selective size sum */ @@ -185,7 +187,7 @@ class Node { /** * @param {T} item item * @param {string} key key - * @param {Record} size size + * @param {Sizes} size size */ constructor(item, key, size) { this.item = item; @@ -194,14 +196,16 @@ class Node { } } +/** @typedef {number[]} Similarities */ + /** * @template T */ class Group { /** * @param {Node[]} nodes nodes - * @param {number[] | null} similarities similarities between the nodes (length = nodes.length - 1) - * @param {Record=} size size of the group + * @param {Similarities | null} similarities similarities between the nodes (length = nodes.length - 1) + * @param {Sizes=} size size of the group */ constructor(nodes, similarities, size) { this.nodes = nodes; @@ -228,7 +232,7 @@ class Group { if (newNodes.length > 0) { newSimilarities.push( lastNode === this.nodes[i - 1] - ? /** @type {number[]} */ (this.similarities)[i - 1] + ? /** @type {Similarities} */ (this.similarities)[i - 1] : similarity(/** @type {Node} */ (lastNode).key, node.key) ); } @@ -247,11 +251,11 @@ class Group { /** * @template T * @param {Iterable>} nodes nodes - * @returns {number[]} similarities + * @returns {Similarities} similarities */ const getSimilarities = (nodes) => { // calculate similarities between lexically adjacent nodes - /** @type {number[]} */ + /** @type {Similarities} */ const similarities = []; let last; for (const node of nodes) { @@ -268,16 +272,16 @@ const getSimilarities = (nodes) => { * @typedef {object} GroupedItems * @property {string} key * @property {T[]} items - * @property {Record} size + * @property {Sizes} size */ /** * @template T * @typedef {object} Options - * @property {Record} maxSize maximum size of a group - * @property {Record} minSize minimum size of a group (preferred over maximum size) + * @property {Sizes} maxSize maximum size of a group + * @property {Sizes} minSize minimum size of a group (preferred over maximum size) * @property {Iterable} items a list of items - * @property {(item: T) => Record} getSize function to get size of an item + * @property {(item: T) => Sizes} getSize function to get size of an item * @property {(item: T) => string} getKey function to get the key of an item */ @@ -320,7 +324,7 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { /** * @param {Group} group group - * @param {Record} consideredSize size of the group to consider + * @param {Sizes} consideredSize size of the group to consider * @returns {boolean} true, if the group was modified */ const removeProblematicNodes = (group, consideredSize = group.size) => { @@ -455,9 +459,9 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { // rightSize ^^^^^^^^^^^^^^^ while (pos <= right + 1) { - const similarity = /** @type {number[]} */ (group.similarities)[ - pos - 1 - ]; + const similarity = + /** @type {Similarities} */ + (group.similarities)[pos - 1]; if ( similarity < bestSimilarity && !isTooSmall(leftSize, minSize) && @@ -484,22 +488,22 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { // create two new groups for left and right area // and queue them up const rightNodes = [group.nodes[right + 1]]; - /** @type {number[]} */ + /** @type {Similarities} */ const rightSimilarities = []; for (let i = right + 2; i < group.nodes.length; i++) { rightSimilarities.push( - /** @type {number[]} */ (group.similarities)[i - 1] + /** @type {Similarities} */ (group.similarities)[i - 1] ); rightNodes.push(group.nodes[i]); } queue.push(new Group(rightNodes, rightSimilarities)); const leftNodes = [group.nodes[0]]; - /** @type {number[]} */ + /** @type {Similarities} */ const leftSimilarities = []; for (let i = 1; i < left; i++) { leftSimilarities.push( - /** @type {number[]} */ (group.similarities)[i - 1] + /** @type {Similarities} */ (group.similarities)[i - 1] ); leftNodes.push(group.nodes[i]); } diff --git a/lib/util/semver.js b/lib/util/semver.js index f64af49fa..c026651bf 100644 --- a/lib/util/semver.js +++ b/lib/util/semver.js @@ -6,7 +6,8 @@ "use strict"; /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {string | number | undefined} SemVerRangeItem */ +/** @typedef {string | number} VersionValue */ +/** @typedef {VersionValue | undefined} SemVerRangeItem */ /** @typedef {(SemVerRangeItem | SemVerRangeItem[])[]} SemVerRange */ /** @@ -16,12 +17,12 @@ const parseVersion = (str) => { /** * @param {str} str str - * @returns {(string | number)[]} result + * @returns {VersionValue[]} result */ var splitAndConvert = function (str) { return str.split(".").map(function (item) { // eslint-disable-next-line eqeqeq - return +item == /** @type {EXPECTED_ANY} */ (item) ? +item : item; + return +item == /** @type {string | number} */ (item) ? +item : item; }); }; @@ -29,7 +30,7 @@ const parseVersion = (str) => { /** @type {RegExpExecArray} */ (/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str)); - /** @type {(string | number | undefined | [])[]} */ + /** @type {(VersionValue | undefined | [])[]} */ var ver = match[1] ? splitAndConvert(match[1]) : []; if (match[2]) { @@ -103,7 +104,7 @@ module.exports.versionLt = versionLt; module.exports.parseRange = (str) => { /** * @param {string} str str - * @returns {(string | number)[]} result + * @returns {VersionValue[]} result */ const splitAndConvert = (str) => { return str @@ -429,7 +430,7 @@ const satisfy = (range, version) => { /** @type {"s" | "n" | "u" | ""} */ (j < range.length ? (typeof range[j])[0] : ""); - /** @type {number | string | undefined} */ + /** @type {VersionValue | undefined} */ var versionValue; /** @type {"n" | "s" | "u" | "o" | undefined} */ var versionType; @@ -470,8 +471,8 @@ const satisfy = (range, version) => { // Handles "cmp" cases if ( negated - ? versionValue > /** @type {(number | string)[]} */ (range)[j] - : versionValue < /** @type {(number | string)[]} */ (range)[j] + ? versionValue > /** @type {VersionValue[]} */ (range)[j] + : versionValue < /** @type {VersionValue[]} */ (range)[j] ) { return false; } diff --git a/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js b/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js index 20a65973e..4f683dbb4 100644 --- a/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +++ b/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js @@ -76,7 +76,11 @@ class AsyncWasmLoadingRuntimeModule extends RuntimeModule { )})` ]; const getStreaming = () => { - const concat = (/** @type {string[]} */ ...text) => text.join(""); + /** + * @param {string[]} text text + * @returns {string} merged text + */ + const concat = (...text) => text.join(""); return [ this.generateBeforeLoadBinaryCode ? this.generateBeforeLoadBinaryCode(wasmModuleSrcPath) diff --git a/lib/wasm-async/AsyncWebAssemblyParser.js b/lib/wasm-async/AsyncWebAssemblyParser.js index 26af5ba6d..1e88fc85c 100644 --- a/lib/wasm-async/AsyncWebAssemblyParser.js +++ b/lib/wasm-async/AsyncWebAssemblyParser.js @@ -62,6 +62,7 @@ class WebAssemblyParser extends Parser { const module = program.body[0]; /** @type {string[]} */ const exports = []; + t.traverse(module, { ModuleExport({ node }) { exports.push(node.name); diff --git a/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js b/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js index bcf765204..5e5eefd9b 100644 --- a/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +++ b/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js @@ -46,12 +46,14 @@ const getAllWasmModules = (moduleGraph, chunkGraph, chunk) => { return array; }; +/** @typedef {string[]} Declarations */ + /** * generates the import object function for a module * @param {ChunkGraph} chunkGraph the chunk graph * @param {Module} module the module * @param {boolean | undefined} mangle mangle imports - * @param {string[]} declarations array where declarations are pushed to + * @param {Declarations} declarations array where declarations are pushed to * @param {RuntimeSpec} runtime the runtime * @returns {string} source code */ @@ -253,7 +255,7 @@ class WasmChunkLoadingRuntimeModule extends RuntimeModule { const chunk = /** @type {Chunk} */ (this.chunk); const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk); const { mangleImports } = this; - /** @type {string[]} */ + /** @type {Declarations} */ const declarations = []; const importObjects = wasmModules.map((module) => generateImportObject( diff --git a/schemas/WebpackOptions.json b/schemas/WebpackOptions.json index e41da1014..688d87f7f 100644 --- a/schemas/WebpackOptions.json +++ b/schemas/WebpackOptions.json @@ -148,7 +148,7 @@ }, { "instanceof": "Function", - "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + "tsType": "(import(\"../lib/TemplatedPathPlugin\").TemplatePathFn)" } ] }, @@ -161,7 +161,7 @@ }, { "instanceof": "Function", - "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + "tsType": "(import(\"../lib/TemplatedPathPlugin\").TemplatePathFn)" } ] }, @@ -352,7 +352,7 @@ }, { "instanceof": "Function", - "tsType": "((filename: string) => boolean)" + "tsType": "(import(\"../lib/CleanPlugin\").KeepFn)" } ] } @@ -1502,7 +1502,7 @@ }, { "instanceof": "Function", - "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + "tsType": "(import(\"../lib/TemplatedPathPlugin\").TemplatePathFn)" } ] }, @@ -2064,7 +2064,7 @@ "parse": { "description": "Function to parser content and return JSON.", "instanceof": "Function", - "tsType": "((input: string) => Buffer | import('../lib/json/JsonParser').JsonValue)" + "tsType": "(import('../lib/json/JsonParser').ParseFn)" } } }, @@ -2136,7 +2136,7 @@ { "description": "A custom create server function.", "instanceof": "Function", - "tsType": "(() => import(\"../lib/hmr/lazyCompilationBackend\").Server)" + "tsType": "(import(\"../lib/hmr/lazyCompilationBackend\").CreateServerFunction)" } ] } @@ -2153,7 +2153,7 @@ { "description": "A custom backend.", "instanceof": "Function", - "tsType": "(((compiler: import('../lib/Compiler'), callback: (err: Error | null, api?: import(\"../lib/hmr/LazyCompilationPlugin\").BackendApi) => void) => void) | ((compiler: import('../lib/Compiler')) => Promise))" + "tsType": "(import(\"../lib/hmr/LazyCompilationPlugin\").BackEnd)" }, { "$ref": "#/definitions/LazyCompilationDefaultBackendOptions" @@ -2180,7 +2180,7 @@ }, { "instanceof": "Function", - "tsType": "((module: import('../lib/Module')) => boolean)" + "tsType": "(import('../lib/hmr/LazyCompilationPlugin').TestFn)" } ] } @@ -3063,7 +3063,7 @@ }, { "instanceof": "Function", - "tsType": "((chunk: import('../lib/Chunk')) => boolean)" + "tsType": "(import('../lib/optimize/SplitChunksPlugin').ChunkFilterFn)" } ] }, @@ -3089,7 +3089,7 @@ }, { "instanceof": "Function", - "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + "tsType": "(import(\"../lib/TemplatedPathPlugin\").TemplatePathFn)" } ] }, @@ -3187,7 +3187,7 @@ }, { "instanceof": "Function", - "tsType": "((module: import('../lib/Module'), chunks: import('../lib/Chunk')[], key: string) => string | undefined)" + "tsType": "(import('../lib/optimize/SplitChunksPlugin').GetNameFn)" } ] }, @@ -3312,7 +3312,7 @@ }, { "instanceof": "Function", - "tsType": "((chunk: import('../lib/Chunk')) => boolean)" + "tsType": "(import('../lib/optimize/SplitChunksPlugin').ChunkFilterFn)" } ] }, @@ -3355,7 +3355,7 @@ }, { "instanceof": "Function", - "tsType": "((chunk: import('../lib/Chunk')) => boolean)" + "tsType": "(import('../lib/optimize/SplitChunksPlugin').ChunkFilterFn)" } ] }, @@ -3411,7 +3411,7 @@ }, { "instanceof": "Function", - "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + "tsType": "(import(\"../lib/TemplatedPathPlugin\").TemplatePathFn)" } ] }, @@ -3493,7 +3493,7 @@ }, { "instanceof": "Function", - "tsType": "((module: import('../lib/Module'), chunks: import('../lib/Chunk')[], key: string) => string | undefined)" + "tsType": "(import('../lib/optimize/SplitChunksPlugin').GetNameFn)" } ] }, @@ -4074,7 +4074,7 @@ }, { "instanceof": "Function", - "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + "tsType": "(import(\"../lib/TemplatedPathPlugin\").TemplatePathFn)" } ] }, @@ -5693,7 +5693,7 @@ }, { "instanceof": "Function", - "tsType": "((warning: import('../lib/stats/DefaultStatsFactoryPlugin').StatsError, value: string) => boolean)" + "tsType": "(import(\"../lib/stats/DefaultStatsPresetPlugin\").WarningFilterFn)" } ] }, diff --git a/schemas/plugins/IgnorePlugin.json b/schemas/plugins/IgnorePlugin.json index 58c1d2c50..933c85acb 100644 --- a/schemas/plugins/IgnorePlugin.json +++ b/schemas/plugins/IgnorePlugin.json @@ -25,7 +25,7 @@ "checkResource": { "description": "A filter function for resource and context.", "instanceof": "Function", - "tsType": "((resource: string, context: string) => boolean)" + "tsType": "(import(\"../../lib/IgnorePlugin\").CheckResourceFn)" } }, "required": ["checkResource"] diff --git a/schemas/plugins/ProgressPlugin.json b/schemas/plugins/ProgressPlugin.json index 2867de45e..4b0376988 100644 --- a/schemas/plugins/ProgressPlugin.json +++ b/schemas/plugins/ProgressPlugin.json @@ -3,7 +3,7 @@ "HandlerFunction": { "description": "Function that executes for every progress step.", "instanceof": "Function", - "tsType": "((percentage: number, msg: string, ...args: string[]) => void)" + "tsType": "(import(\"../../lib/ProgressPlugin\").HandlerFn)" }, "ProgressPluginOptions": { "description": "Options object for the ProgressPlugin.", diff --git a/schemas/plugins/SourceMapDevToolPlugin.json b/schemas/plugins/SourceMapDevToolPlugin.json index 053dc8710..df5510f29 100644 --- a/schemas/plugins/SourceMapDevToolPlugin.json +++ b/schemas/plugins/SourceMapDevToolPlugin.json @@ -50,7 +50,7 @@ }, { "instanceof": "Function", - "tsType": "((pathData: import(\"../../lib/Compilation\").PathData, assetInfo?: import(\"../../lib/Compilation\").AssetInfo) => string)" + "tsType": "(import(\"../../lib/TemplatedPathPlugin\").TemplatePathFn)" } ] }, diff --git a/schemas/plugins/schemes/VirtualUrlPlugin.json b/schemas/plugins/schemes/VirtualUrlPlugin.json index 704135a97..34582abb3 100644 --- a/schemas/plugins/schemes/VirtualUrlPlugin.json +++ b/schemas/plugins/schemes/VirtualUrlPlugin.json @@ -8,7 +8,7 @@ "source": { "description": "The source function that provides the virtual content.", "instanceof": "Function", - "tsType": "((loaderContext: import('webpack').LoaderContext) => Promise | string)" + "tsType": "(import('../../../lib/schemes/VirtualUrlPlugin').SourceFn)" }, "type": { "description": "The module type.", @@ -26,7 +26,7 @@ }, { "instanceof": "Function", - "tsType": "(() => string | undefined)" + "tsType": "(import('../../../lib/schemes/VirtualUrlPlugin').VersionFn)" } ] } @@ -41,7 +41,7 @@ }, { "instanceof": "Function", - "tsType": "((loaderContext: import('webpack').LoaderContext) => Promise | string)" + "tsType": "(import('../../../lib/schemes/VirtualUrlPlugin').SourceFn)" }, { "$ref": "#/definitions/VirtualModule" diff --git a/types.d.ts b/types.d.ts index 93264a142..50cb4a96a 100644 --- a/types.d.ts +++ b/types.d.ts @@ -263,6 +263,10 @@ type AliasOptionNewRequest = string | false | string[]; declare interface AliasOptions { [index: string]: AliasOptionNewRequest; } +type AnyLoaderContext = NormalModuleLoaderContext & + LoaderRunnerLoaderContext & + LoaderPluginLoaderContext & + HotModuleReplacementPluginLoaderContext; declare interface Argument { description?: string; simpleType: SimpleType; @@ -1277,7 +1281,7 @@ declare class Chunk { ): boolean; } declare interface ChunkChildIdsByOrdersMap { - [index: string]: (string | number)[]; + [index: string]: ChunkId[]; } declare interface ChunkChildIdsByOrdersMapByData { [index: string]: ChunkChildIdsByOrdersMap; @@ -1339,7 +1343,7 @@ declare class ChunkGraph { chunk: Chunk, filterFn: (m: Module) => boolean, includeAllChunks?: boolean - ): ChunkModuleIdMap; + ): ChunkModuleIdMapEs5Alias_2; getChunkModuleRenderedHashMap( chunk: Chunk, filterFn: (m: Module) => boolean, @@ -1592,9 +1596,9 @@ declare interface ChunkHashes { } type ChunkId = string | number; declare interface ChunkMaps { - hash: Record; - contentHash: Record>; - name: Record; + hash: Record; + contentHash: Record>; + name: Record; } declare interface ChunkModuleHashMap { [index: number]: IdToHashMap; @@ -1603,7 +1607,11 @@ declare interface ChunkModuleHashMap { declare interface ChunkModuleHashes { [index: string]: string; } -declare interface ChunkModuleIdMap { +declare interface ChunkModuleIdMapEs5Alias_1 { + [index: number]: ChunkId[]; + [index: string]: ChunkId[]; +} +declare interface ChunkModuleIdMapEs5Alias_2 { [index: number]: ModuleId[]; [index: string]: ModuleId[]; } @@ -1642,8 +1650,8 @@ declare interface ChunkModuleIds { [index: string]: ModuleId[]; } declare interface ChunkModuleMaps { - id: Record; - hash: Record; + id: ChunkModuleIdMapEs5Alias_1; + hash: chunkModuleHashMap; } type ChunkName = null | string; declare interface ChunkPathData { @@ -1821,7 +1829,7 @@ declare interface CleanOptions { /** * Keep these assets. */ - keep?: string | RegExp | ((filename: string) => boolean); + keep?: string | RegExp | ((path: string) => undefined | boolean); } declare class CleanPlugin { constructor(options?: CleanOptions); @@ -1833,7 +1841,7 @@ declare class CleanPlugin { /** * Keep these assets. */ - keep?: string | RegExp | ((filename: string) => boolean); + keep?: string | RegExp | ((path: string) => undefined | boolean); }; /** @@ -2212,9 +2220,7 @@ declare class Compilation { >; statsFactory: SyncHook<[StatsFactory, NormalizedStatsOptions]>; statsPrinter: SyncHook<[StatsPrinter, NormalizedStatsOptions]>; - get normalModuleLoader(): SyncHook< - [LoaderContextObject, NormalModule] - >; + get normalModuleLoader(): SyncHook<[AnyLoaderContext, NormalModule]>; }>; name?: string; startTime?: number; @@ -2277,7 +2283,7 @@ declare class Compilation { dependencyFactories: Map; dependencyTemplates: DependencyTemplates; childrenCounters: Record; - usedChunkIds: null | Set; + usedChunkIds: null | Set; usedModuleIds: null | Set; needAdditionalPass: boolean; builtModules: WeakSet; @@ -5331,7 +5337,7 @@ declare interface ExternalItemObjectUnknown { type ExternalItemValue = string | boolean | string[] | { [index: string]: any }; declare class ExternalModule extends Module { constructor( - request: string | string[] | RequestRecord, + request: ExternalModuleRequest, type: string, userRequest: string, dependencyMeta?: @@ -5339,7 +5345,7 @@ declare class ExternalModule extends Module { | CssImportDependencyMeta | AssetDependencyMeta ); - request: string | string[] | Record; + request: ExternalModuleRequest; externalType: string; userRequest: string; dependencyMeta?: @@ -5420,6 +5426,7 @@ declare interface ExternalModuleInfo { */ interopDefaultAccessName?: string; } +type ExternalModuleRequest = string | string[] | RequestRecord; type Externals = | string | RegExp @@ -6585,6 +6592,7 @@ declare interface InterpolatedPathAndAssetInfo { path: string; info: AssetInfo; } +type Issuer = undefined | null | Module; type IssuerLayer = null | string; declare interface Item { [index: string]: string | string[] | T; @@ -7159,11 +7167,12 @@ declare class JavascriptParser extends ParserClass { Set >; currentTagData?: - | (TopLevelSymbol & Record) - | (HarmonySettings & Record) - | (ImportSettings & Record) - | (CommonJsImportSettings & Record) - | (CompatibilitySettings & Record); + | Record + | TopLevelSymbol + | HarmonySettings + | ImportSettings + | CommonJsImportSettings + | CompatibilitySettings; magicCommentContext: Context; destructuringAssignmentPropertiesFor( node: Expression @@ -7928,20 +7937,22 @@ declare class JavascriptParser extends ParserClass { tag: symbol ): | undefined - | (TopLevelSymbol & Record) - | (HarmonySettings & Record) - | (ImportSettings & Record) - | (CommonJsImportSettings & Record) - | (CompatibilitySettings & Record); + | Record + | TopLevelSymbol + | HarmonySettings + | ImportSettings + | CommonJsImportSettings + | CompatibilitySettings; tagVariable( name: string, tag: symbol, data?: - | (TopLevelSymbol & Record) - | (HarmonySettings & Record) - | (ImportSettings & Record) - | (CommonJsImportSettings & Record) - | (CompatibilitySettings & Record), + | Record + | TopLevelSymbol + | HarmonySettings + | ImportSettings + | CommonJsImportSettings + | CompatibilitySettings, flags?: 0 | 1 | 2 | 4 ): void; defineVariable(name: string): void; @@ -8736,7 +8747,7 @@ declare interface KnownStatsChunk { } declare interface KnownStatsChunkGroup { name?: null | string; - chunks?: (string | number)[]; + chunks?: ChunkId[]; assets?: { name: string; size?: number }[]; filteredAssets?: number; assetsSize?: number; @@ -8808,8 +8819,8 @@ declare interface KnownStatsFactoryContext { compilationFileToChunks: Map; compilationAuxiliaryFileToChunks: Map; runtime: RuntimeSpec; - cachedGetErrors: (compilation: Compilation) => WebpackError[]; - cachedGetWarnings: (compilation: Compilation) => WebpackError[]; + cachedGetErrors: (compilation: Compilation) => Error[]; + cachedGetWarnings: (compilation: Compilation) => Error[]; } declare interface KnownStatsLogging { entries: StatsLoggingEntry[]; @@ -8846,8 +8857,8 @@ declare interface KnownStatsModule { orphan?: boolean; id?: string | number; issuerId?: null | string | number; - chunks?: (string | number)[]; - assets?: (string | number)[]; + chunks?: ChunkId[]; + assets?: string[]; dependent?: boolean; issuer?: null | string; issuerName?: null | string; @@ -9071,7 +9082,7 @@ declare interface LazyCompilationOptions { backend?: | (( compiler: Compiler, - callback: (err: null | Error, api?: BackendApi) => void + callback: (err: null | Error, backendApi?: BackendApi) => void ) => void) | ((compiler: Compiler) => Promise) | LazyCompilationDefaultBackendOptions; @@ -9345,7 +9356,7 @@ type LoaderContextDeclarationsIndex = LoaderRunnerLoaderContext & LoaderPluginLoaderContext & HotModuleReplacementPluginLoaderContext; -type LoaderContextObject = NormalModuleLoaderContext & +type LoaderContextVirtualUrlPlugin = NormalModuleLoaderContext & LoaderRunnerLoaderContext & LoaderPluginLoaderContext & HotModuleReplacementPluginLoaderContext; @@ -10358,7 +10369,7 @@ declare class ModuleGraph { | ReadonlyMap>; getProfile(module: Module): undefined | ModuleProfile; setProfile(module: Module, profile?: ModuleProfile): void; - getIssuer(module: Module): undefined | null | Module; + getIssuer(module: Module): Issuer; setIssuer(module: Module, issuer: null | Module): void; setIssuerIfUnset(module: Module, issuer: null | Module): void; getOptimizationBailout( @@ -11087,7 +11098,7 @@ declare class NormalModule extends Module { associatedObjectForCache?: object ): Source; getCurrentLoader( - loaderContext: LoaderContextObject, + loaderContext: AnyLoaderContext, index?: number ): null | LoaderItem; createSource( @@ -11113,10 +11124,8 @@ declare class NormalModule extends Module { static deserialize(context: ObjectDeserializerContext): NormalModule; } declare interface NormalModuleCompilationHooks { - loader: SyncHook<[LoaderContextObject, NormalModule]>; - beforeLoaders: SyncHook< - [LoaderItem[], NormalModule, LoaderContextObject] - >; + loader: SyncHook<[AnyLoaderContext, NormalModule]>; + beforeLoaders: SyncHook<[LoaderItem[], NormalModule, AnyLoaderContext]>; beforeParse: SyncHook<[NormalModule]>; beforeSnapshot: SyncHook<[NormalModule]>; readResourceForScheme: HookMap< @@ -11125,7 +11134,7 @@ declare interface NormalModuleCompilationHooks { > >; readResource: HookMap< - AsyncSeriesBailHook<[LoaderContextObject], null | string | Buffer> + AsyncSeriesBailHook<[AnyLoaderContext], null | string | Buffer> >; processResult: SyncWaterfallHook< [ @@ -11881,7 +11890,12 @@ declare interface OptimizationSplitChunksCacheGroup { /** * Select chunks for determining cache group content (defaults to "initial", "initial" and "all" requires adding these chunks to the HTML). */ - chunks?: RegExp | "all" | "initial" | "async" | ((chunk: Chunk) => boolean); + chunks?: + | RegExp + | "all" + | "initial" + | "async" + | ((chunk: Chunk) => undefined | boolean); /** * Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group. @@ -12019,7 +12033,12 @@ declare interface OptimizationSplitChunksOptions { /** * Select chunks for determining shared modules (defaults to "async", "initial" and "all" requires adding these chunks to the HTML). */ - chunks?: RegExp | "all" | "initial" | "async" | ((chunk: Chunk) => boolean); + chunks?: + | RegExp + | "all" + | "initial" + | "async" + | ((chunk: Chunk) => undefined | boolean); /** * Sets the size types which are used when a number is used for sizes. @@ -12042,7 +12061,12 @@ declare interface OptimizationSplitChunksOptions { /** * Select chunks for determining shared modules (defaults to "async", "initial" and "all" requires adding these chunks to the HTML). */ - chunks?: RegExp | "all" | "initial" | "async" | ((chunk: Chunk) => boolean); + chunks?: + | RegExp + | "all" + | "initial" + | "async" + | ((chunk: Chunk) => undefined | boolean); /** * Maximal size hint for the on-demand chunks. */ @@ -16115,10 +16139,11 @@ declare class SideEffectsFlagPlugin { apply(compiler: Compiler): void; static moduleHasSideEffects( moduleName: string, - flagValue: undefined | string | boolean | string[], + flagValue: SideEffectsFlagValue, cache: Map ): undefined | boolean; } +type SideEffectsFlagValue = undefined | string | boolean | string[]; type SimpleType = "string" | "number" | "boolean"; declare class SizeOnlySource extends Source { constructor(size: number); @@ -17324,7 +17349,7 @@ declare interface StatsOptions { | string | RegExp | WarningFilterItemTypes[] - | ((warning: StatsError, value: string) => boolean); + | ((warning: StatsError, warningString: string) => boolean); /** * Space to display warnings (value is in number of lines). @@ -17442,11 +17467,12 @@ declare const TRANSITIVE_ONLY: unique symbol; declare interface TagInfo { tag: symbol; data?: - | (TopLevelSymbol & Record) - | (HarmonySettings & Record) - | (ImportSettings & Record) - | (CommonJsImportSettings & Record) - | (CompatibilitySettings & Record); + | Record + | TopLevelSymbol + | HarmonySettings + | ImportSettings + | CommonJsImportSettings + | CompatibilitySettings; next?: TagInfo; } declare interface TargetItemWithConnection { @@ -17560,23 +17586,27 @@ declare class VariableInfo { type VariableInfoFlagsType = 0 | 1 | 2 | 4; declare interface VirtualModuleConfig { /** - * - The module type + * the module type */ type?: string; /** - * - The source function + * the source function */ - source: (loaderContext: LoaderContextObject) => string | Promise; + source: ( + loaderContext: LoaderContextVirtualUrlPlugin + ) => string | Buffer | Promise; /** - * - Optional version function or value + * optional version function or value */ version?: string | true | (() => string); } type VirtualModuleInput = | string - | ((loaderContext: LoaderContextObject) => string | Promise) + | (( + loaderContext: LoaderContextVirtualUrlPlugin + ) => string | Buffer | Promise) | VirtualModuleConfig; declare interface VirtualModules { [index: string]: VirtualModuleInput; @@ -17601,7 +17631,7 @@ declare class VirtualUrlPlugin { type WarningFilterItemTypes = | string | RegExp - | ((warning: StatsError, value: string) => boolean); + | ((warning: StatsError, warningString: string) => boolean); declare interface WatchFileSystem { watch: ( files: Iterable, @@ -18198,6 +18228,10 @@ type WriteStreamOptions = StreamOptions & { fs?: null | CreateWriteStreamFSImplementation; flush?: boolean; }; +declare interface chunkModuleHashMap { + [index: number]: string; + [index: string]: string; +} declare function exports( options: Configuration, callback?: CallbackWebpackFunction_2