fix: no `Function` types

This commit is contained in:
alexander-akait 2025-03-13 19:34:04 +03:00
parent cb25853b58
commit 70bdb248e4
28 changed files with 273 additions and 222 deletions

33
declarations.d.ts vendored
View File

@ -1,3 +1,8 @@
type TODO = any;
type EXPECTED_ANY = any;
type EXPECTED_FUNCTION = Function;
type EXPECTED_OBJECT = object;
declare module "*.json"; declare module "*.json";
// Deprecated NodeJS API usages in webpack // Deprecated NodeJS API usages in webpack
@ -124,6 +129,7 @@ declare module "neo-async" {
// There are no typings for @webassemblyjs/ast // There are no typings for @webassemblyjs/ast
declare module "@webassemblyjs/ast" { declare module "@webassemblyjs/ast" {
export type AST = TODO;
export interface Visitor { export interface Visitor {
ModuleImport?: (p: NodePath<ModuleImport>) => void; ModuleImport?: (p: NodePath<ModuleImport>) => void;
ModuleExport?: (p: NodePath<ModuleExport>) => void; ModuleExport?: (p: NodePath<ModuleExport>) => void;
@ -131,20 +137,27 @@ declare module "@webassemblyjs/ast" {
Global?: (p: NodePath<Global>) => void; Global?: (p: NodePath<Global>) => void;
} }
export function traverse( export function traverse(
ast: any, ast: AST,
visitor: Visitor visitor: Visitor
): void; ): void;
export class NodePath<T> { export class NodePath<T> {
node: T; node: T;
remove(): void; remove(): void;
} }
export class Node {} export class Node {
type: string;
}
export class Identifier extends Node { export class Identifier extends Node {
value: string; value: string;
} }
export class Start extends Node { export class Start extends Node {
index: Identifier; index: Identifier;
} }
export class Module extends Node {
id: TODO;
fields: Node[];
metadata: TODO;
}
export class ModuleImportDescription { export class ModuleImportDescription {
type: string; type: string;
valtype?: string; valtype?: string;
@ -207,7 +220,7 @@ declare module "@webassemblyjs/ast" {
inf?: boolean, inf?: boolean,
raw?: string raw?: string
): FloatLiteral; ): FloatLiteral;
export function global(globalType: string, nodes: Node[]): Global; export function global(globalType: GlobalType, nodes: Node[]): Global;
export function identifier(identifier: string): Identifier; export function identifier(identifier: string): Identifier;
export function funcParam(valType: string, id: Identifier): FuncParam; export function funcParam(valType: string, id: Identifier): FuncParam;
export function instruction(inst: string, args?: Node[]): Instruction; export function instruction(inst: string, args?: Node[]): Instruction;
@ -233,12 +246,12 @@ declare module "@webassemblyjs/ast" {
index: Index index: Index
): ModuleExportDescr; ): ModuleExportDescr;
export function getSectionMetadata(ast: any, section: string): { vectorOfSize: { value: number } }; export function getSectionMetadata(ast: AST, section: string): { vectorOfSize: { value: number } };
export class FuncSignature { export class FuncSignature {
args: string[]; args: string[];
result: string[]; result: string[];
} }
export function moduleContextFromModuleAST(ast: any): any; export function moduleContextFromModuleAST(module: Module): TODO;
// Node matcher // Node matcher
export function isGlobalType(n: Node): boolean; export function isGlobalType(n: Node): boolean;
@ -248,12 +261,12 @@ declare module "@webassemblyjs/ast" {
} }
declare module "@webassemblyjs/wasm-parser" { declare module "@webassemblyjs/wasm-parser" {
export function decode(source: string | Buffer, options: { dump?: boolean, ignoreCodeSection?: boolean, ignoreDataSection?: boolean, ignoreCustomNameSection?: boolean }): any; export function decode(source: string | Buffer, options: { dump?: boolean, ignoreCodeSection?: boolean, ignoreDataSection?: boolean, ignoreCustomNameSection?: boolean }): import("@webassemblyjs/ast").AST;
} }
declare module "@webassemblyjs/wasm-edit" { declare module "@webassemblyjs/wasm-edit" {
export function addWithAST(ast: any, bin: any, newNodes: import("@webassemblyjs/ast").Node[]): ArrayBuffer; export function addWithAST(ast: import("@webassemblyjs/ast").AST, bin: any, newNodes: import("@webassemblyjs/ast").Node[]): ArrayBuffer;
export function editWithAST(ast: any, bin: any, visitors: import("@webassemblyjs/ast").Visitor): ArrayBuffer; export function editWithAST(ast: import("@webassemblyjs/ast").AST, bin: any, visitors: import("@webassemblyjs/ast").Visitor): ArrayBuffer;
} }
declare module "webpack-sources" { declare module "webpack-sources" {
@ -406,10 +419,6 @@ interface ImportAttributeNode {
value: import("estree").Literal; value: import("estree").Literal;
} }
type TODO = any;
type EXPECTED_ANY = any;
type EXPECTED_OBJECT = object;
type RecursiveArrayOrRecord<T> = type RecursiveArrayOrRecord<T> =
| { [index: string]: RecursiveArrayOrRecord<T> } | { [index: string]: RecursiveArrayOrRecord<T> }
| Array<RecursiveArrayOrRecord<T>> | Array<RecursiveArrayOrRecord<T>>

View File

@ -494,11 +494,15 @@ export type CssFilename = FilenameTemplate;
/** /**
* Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers. * Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.
*/ */
export type DevtoolFallbackModuleFilenameTemplate = string | Function; export type DevtoolFallbackModuleFilenameTemplate =
| string
| ((context: TODO) => string);
/** /**
* Filename template string of function for the sources array in a generated SourceMap. * Filename template string of function for the sources array in a generated SourceMap.
*/ */
export type DevtoolModuleFilenameTemplate = string | Function; export type DevtoolModuleFilenameTemplate =
| string
| ((context: TODO) => string);
/** /**
* Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries. * Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries.
*/ */
@ -1936,7 +1940,14 @@ export interface OptimizationSplitChunksOptions {
/** /**
* Give chunks created a name (chunks with equal name are merged). * Give chunks created a name (chunks with equal name are merged).
*/ */
name?: false | string | Function; name?:
| false
| string
| ((
module: import("../lib/Module"),
chunks: import("../lib/Chunk")[],
key: string
) => string | undefined);
/** /**
* Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal. * Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal.
*/ */
@ -1981,7 +1992,7 @@ export interface OptimizationSplitChunksCacheGroup {
/** /**
* Assign modules to a cache group by module layer. * Assign modules to a cache group by module layer.
*/ */
layer?: RegExp | string | Function; layer?: RegExp | string | ((layer: string | null) => boolean);
/** /**
* Maximum number of requests which are accepted for on-demand loading. * Maximum number of requests which are accepted for on-demand loading.
*/ */
@ -2021,7 +2032,14 @@ export interface OptimizationSplitChunksCacheGroup {
/** /**
* Give chunks for this cache group a name (chunks with equal name are merged). * Give chunks for this cache group a name (chunks with equal name are merged).
*/ */
name?: false | string | Function; name?:
| false
| string
| ((
module: import("../lib/Module"),
chunks: import("../lib/Chunk")[],
key: string
) => string | undefined);
/** /**
* Priority of this cache group. * Priority of this cache group.
*/ */
@ -2033,11 +2051,17 @@ export interface OptimizationSplitChunksCacheGroup {
/** /**
* Assign modules to a cache group by module name. * Assign modules to a cache group by module name.
*/ */
test?: RegExp | string | Function; test?:
| RegExp
| string
| ((
module: import("../lib/Module"),
context: import("../lib/optimize/SplitChunksPlugin").CacheGroupsContext
) => boolean);
/** /**
* Assign modules to a cache group by module type. * Assign modules to a cache group by module type.
*/ */
type?: RegExp | string | Function; type?: RegExp | string | ((type: string) => boolean);
/** /**
* Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal. * Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal.
*/ */

View File

@ -39,7 +39,7 @@ export interface SourceMapDevToolPluginOptions {
/** /**
* Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap used only if 'moduleFilenameTemplate' would result in a conflict. * Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap used only if 'moduleFilenameTemplate' would result in a conflict.
*/ */
fallbackModuleFilenameTemplate?: string | Function; fallbackModuleFilenameTemplate?: string | ((context: any) => string);
/** /**
* Path prefix to which the [file] placeholder is relative to. * Path prefix to which the [file] placeholder is relative to.
*/ */
@ -59,7 +59,7 @@ export interface SourceMapDevToolPluginOptions {
/** /**
* Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap. * Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap.
*/ */
moduleFilenameTemplate?: string | Function; moduleFilenameTemplate?: string | ((context: any) => string);
/** /**
* Namespace prefix to allow multiple webpack roots in the devtools. * Namespace prefix to allow multiple webpack roots in the devtools.
*/ */

View File

@ -324,22 +324,42 @@ export default [
"error", "error",
{ {
contexts: [ contexts: [
// No `@type {*}`
{
comment: "JsdocBlock:has(JsdocTypeAny)",
message: "Please use `any`."
},
// No `@type {?}`
{
comment: "JsdocBlock:has(JsdocTypeUnknown)",
message: "Please use `unknown` or `any`"
},
// Prefer TypeScript syntax for functions // Prefer TypeScript syntax for functions
{ {
comment: "JsdocBlock:has(JsdocTypeFunction[arrow=false])", comment: "JsdocBlock:has(JsdocTypeFunction[arrow=false])",
message: message:
"Please use TypeScript syntax - `(a: string, b: boolean) => number`" "Please use TypeScript syntax - `(a: string, b: boolean) => number`"
},
// No `*` type
{
comment: "JsdocBlock:has(JsdocTypeAny)",
message: "Please use `any`."
},
// No `?` type
{
comment: "JsdocBlock:has(JsdocTypeUnknown)",
message: "Please use `unknown` or `any`"
},
// No `Function` type
{
comment:
"JsdocBlock:has(JsdocTypeName[value=/^(function|Function)$/])",
message:
"Please use provide types for function - `(a: number, b: number) -> number` instead `Function`"
} }
// No `Object` type
// {
// comment:
// "JsdocBlock:has(JsdocTag[tag!=typedef]:has(JsdocTypeName[value=/^(object|Object)$/]))",
// message:
// "Please use provide types for object - `{ property: number:, result: () => number}` instead `Object`"
// },
// No `any` type
// {
// comment: "JsdocBlock:has(JsdocTypeName[value=/^any$/])",
// message:
// "Please use provide types instead `any`"
// },
] ]
} }
] ]

View File

@ -69,8 +69,6 @@ class ModuleHashInfo {
} }
} }
/** @template T @typedef {(set: SortableSet<T>) => T[]} SetToArrayFunction<T> */
/** /**
* @template T * @template T
* @param {SortableSet<T>} set the set * @param {SortableSet<T>} set the set
@ -121,19 +119,22 @@ const modulesBySourceType = sourceTypesByModule => set => {
}; };
const defaultModulesBySourceType = modulesBySourceType(undefined); const defaultModulesBySourceType = modulesBySourceType(undefined);
/**
* @typedef {(set: SortableSet<Module>) => Module[]} ModuleSetToArrayFunction
*/
/** /**
* @template T * @template T
* @type {WeakMap<Function, any>} * @type {WeakMap<ModuleComparator, ModuleSetToArrayFunction>}
*/ */
const createOrderedArrayFunctionMap = new WeakMap(); const createOrderedArrayFunctionMap = new WeakMap();
/** /**
* @template T * @template T
* @param {(a: T, b:T) => -1 | 0 | 1 } comparator comparator function * @param {ModuleComparator} comparator comparator function
* @returns {SetToArrayFunction<T>} set as ordered array * @returns {ModuleSetToArrayFunction} set as ordered array
*/ */
const createOrderedArrayFunction = comparator => { const createOrderedArrayFunction = comparator => {
/** @type {SetToArrayFunction<T>} */
let fn = createOrderedArrayFunctionMap.get(comparator); let fn = createOrderedArrayFunctionMap.get(comparator);
if (fn !== undefined) return fn; if (fn !== undefined) return fn;
fn = set => { fn = set => {

View File

@ -457,9 +457,6 @@ const byLocation = compareSelect(err => err.loc, compareLocations);
const compareErrors = concatComparators(byModule, byLocation, byMessage); const compareErrors = concatComparators(byModule, byLocation, byMessage);
/** @type {WeakMap<Dependency, Module & { restoreFromUnsafeCache: Function } | null>} */
const unsafeCacheDependencies = new WeakMap();
/** /**
* @typedef {object} KnownUnsafeCacheData * @typedef {object} KnownUnsafeCacheData
* @property {FactoryMeta} [factoryMeta] factory meta * @property {FactoryMeta} [factoryMeta] factory meta
@ -470,7 +467,14 @@ const unsafeCacheDependencies = new WeakMap();
/** @typedef {KnownUnsafeCacheData & Record<string, any>} UnsafeCacheData */ /** @typedef {KnownUnsafeCacheData & Record<string, any>} UnsafeCacheData */
/** @type {WeakMap<Module & { restoreFromUnsafeCache: Function }, UnsafeCacheData>} */ /**
* @typedef {Module & { restoreFromUnsafeCache?: (unsafeCacheData: UnsafeCacheData, moduleFactory: ModuleFactory, compilationParams: CompilationParams) => void }} ModuleWithRestoreFromUnsafeCache
*/
/** @type {WeakMap<Dependency, ModuleWithRestoreFromUnsafeCache | null>} */
const unsafeCacheDependencies = new WeakMap();
/** @type {WeakMap<ModuleWithRestoreFromUnsafeCache, UnsafeCacheData>} */
const unsafeCacheData = new WeakMap(); const unsafeCacheData = new WeakMap();
class Compilation { class Compilation {
@ -483,7 +487,7 @@ class Compilation {
this._backCompat = compiler._backCompat; this._backCompat = compiler._backCompat;
const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this); const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this);
/** @typedef {{ additionalAssets?: true | Function }} ProcessAssetsAdditionalOptions */ /** @typedef {{ additionalAssets?: true | TODO }} ProcessAssetsAdditionalOptions */
/** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */ /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */
const processAssetsHook = new AsyncSeriesHook(["assets"]); const processAssetsHook = new AsyncSeriesHook(["assets"]);
@ -1143,9 +1147,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.usedModuleIds = null; this.usedModuleIds = null;
/** @type {boolean} */ /** @type {boolean} */
this.needAdditionalPass = false; this.needAdditionalPass = false;
/** @type {Set<Module & { restoreFromUnsafeCache: Function }>} */ /** @type {Set<ModuleWithRestoreFromUnsafeCache>} */
this._restoredUnsafeCacheModuleEntries = new Set(); this._restoredUnsafeCacheModuleEntries = new Set();
/** @type {Map<string, Module & { restoreFromUnsafeCache: Function }>} */ /** @type {Map<string, ModuleWithRestoreFromUnsafeCache>} */
this._restoredUnsafeCacheEntries = new Map(); this._restoredUnsafeCacheEntries = new Map();
/** @type {WeakSet<Module>} */ /** @type {WeakSet<Module>} */
this.builtModules = new WeakSet(); this.builtModules = new WeakSet();
@ -1985,7 +1989,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
} }
const module = const module =
/** @type {Module & { restoreFromUnsafeCache?: Function }} */ /** @type {ModuleWithRestoreFromUnsafeCache} */
(_module); (_module);
if ( if (
@ -1996,7 +2000,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this._unsafeCachePredicate(module) this._unsafeCachePredicate(module)
) { ) {
const unsafeCacheableModule = const unsafeCacheableModule =
/** @type {Module & { restoreFromUnsafeCache: Function }} */ /** @type {ModuleWithRestoreFromUnsafeCache} */
(module); (module);
for (let i = 0; i < dependencies.length; i++) { for (let i = 0; i < dependencies.length; i++) {
const dependency = dependencies[i]; const dependency = dependencies[i];

View File

@ -33,8 +33,8 @@ const createHash = require("./util/createHash");
/** @typedef {import("./logging/Logger").Logger} Logger */ /** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/createHash").Algorithm} Algorithm */ /** @typedef {import("./util/createHash").Algorithm} Algorithm */
/** @typedef {null | undefined | RegExp | Function | string | number | boolean | bigint | undefined} CodeValuePrimitive */ /** @typedef {null | undefined | RegExp | EXPECTED_FUNCTION | string | number | boolean | bigint | undefined} CodeValuePrimitive */
/** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive|RuntimeValue>} CodeValue */ /** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive | RuntimeValue>} CodeValue */
/** /**
* @typedef {object} RuntimeValueOptions * @typedef {object} RuntimeValueOptions
@ -408,10 +408,10 @@ class DefinePlugin {
}; };
/** /**
* @template {Function} T * @template T
* @param {string} key key * @param {string} key key
* @param {T} fn fn * @param {(expression: Expression) => T} fn fn
* @returns {(expression: Expression) => TODO} result * @returns {(expression: Expression) => T} result
*/ */
const withValueDependency = const withValueDependency =
(key, fn) => (key, fn) =>

View File

@ -11,14 +11,14 @@ const createHash = require("./util/createHash");
/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ /** @typedef {import("./DependencyTemplate")} DependencyTemplate */
/** @typedef {typeof import("./util/Hash")} Hash */ /** @typedef {typeof import("./util/Hash")} Hash */
/** @typedef {new (...args: any[]) => Dependency} DependencyConstructor */ /** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DependencyConstructor */
class DependencyTemplates { class DependencyTemplates {
/** /**
* @param {string | Hash} hashFunction the hash function to use * @param {string | Hash} hashFunction the hash function to use
*/ */
constructor(hashFunction = "md4") { constructor(hashFunction = "md4") {
/** @type {Map<Function, DependencyTemplate>} */ /** @type {Map<DependencyConstructor, DependencyTemplate>} */
this._map = new Map(); this._map = new Map();
/** @type {string} */ /** @type {string} */
this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0"; this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0";

View File

@ -29,11 +29,6 @@ class IgnorePlugin {
constructor(options) { constructor(options) {
validate(options); validate(options);
this.options = options; this.options = options;
/**
* @private
* @type {Function}
*/
this.checkIgnore = this.checkIgnore.bind(this); this.checkIgnore = this.checkIgnore.bind(this);
} }

View File

@ -92,10 +92,10 @@ const getHash =
* Returns a lazy object. The object is lazy in the sense that the properties are * Returns a lazy object. The object is lazy in the sense that the properties are
* only evaluated when they are accessed. This is only obtained by setting a function as the value for each key. * only evaluated when they are accessed. This is only obtained by setting a function as the value for each key.
* @param {Record<string, () => T>} obj the object to convert to a lazy access object * @param {Record<string, () => T>} obj the object to convert to a lazy access object
* @returns {object} the lazy access object * @returns {T} the lazy access object
*/ */
const lazyObject = obj => { const lazyObject = obj => {
const newObj = {}; const newObj = /** @type {T} */ ({});
for (const key of Object.keys(obj)) { for (const key of Object.keys(obj)) {
const fn = obj[key]; const fn = obj[key];
Object.defineProperty(newObj, key, { Object.defineProperty(newObj, key, {
@ -118,11 +118,8 @@ const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
/** /**
* @param {Module | string} module the module * @param {Module | string} module the module
* @param {TODO} options options * @param {{ namespace?: string, moduleFilenameTemplate?: string | TODO }} options options
* @param {object} contextInfo context info * @param {{ requestShortener: RequestShortener, chunkGraph: ChunkGraph, hashFunction?: string | Hash }} contextInfo context info
* @param {RequestShortener} contextInfo.requestShortener requestShortener
* @param {ChunkGraph} contextInfo.chunkGraph chunk graph
* @param {string | Hash=} contextInfo.hashFunction the hash function to use
* @returns {string} the filename * @returns {string} the filename
*/ */
ModuleFilenameHelpers.createFilename = ( ModuleFilenameHelpers.createFilename = (
@ -141,6 +138,7 @@ ModuleFilenameHelpers.createFilename = (
}) })
}; };
/** @type {ReturnStringCallback} */
let absoluteResourcePath; let absoluteResourcePath;
let hash; let hash;
/** @type {ReturnStringCallback} */ /** @type {ReturnStringCallback} */
@ -155,7 +153,8 @@ ModuleFilenameHelpers.createFilename = (
(memoize(() => requestShortener.shorten(module))); (memoize(() => requestShortener.shorten(module)));
identifier = shortIdentifier; identifier = shortIdentifier;
moduleId = () => ""; moduleId = () => "";
absoluteResourcePath = () => module.split("!").pop(); absoluteResourcePath = () =>
/** @type {string} */ (module.split("!").pop());
hash = getHash(identifier, hashFunction); hash = getHash(identifier, hashFunction);
} else { } else {
shortIdentifier = memoize(() => shortIdentifier = memoize(() =>
@ -170,7 +169,7 @@ ModuleFilenameHelpers.createFilename = (
absoluteResourcePath = () => absoluteResourcePath = () =>
module instanceof NormalModule module instanceof NormalModule
? module.resource ? module.resource
: module.identifier().split("!").pop(); : /** @type {string} */ (module.identifier().split("!").pop());
hash = getHash(identifier, hashFunction); hash = getHash(identifier, hashFunction);
} }
const resource = const resource =

View File

@ -146,16 +146,12 @@ class SourceMapDevToolPlugin {
? false ? false
: // eslint-disable-next-line no-useless-concat : // eslint-disable-next-line no-useless-concat
options.append || "\n//# source" + "MappingURL=[url]"; options.append || "\n//# source" + "MappingURL=[url]";
/** @type {string | Function} */
this.moduleFilenameTemplate = this.moduleFilenameTemplate =
options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]";
/** @type {string | Function} */
this.fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate =
options.fallbackModuleFilenameTemplate || options.fallbackModuleFilenameTemplate ||
"webpack://[namespace]/[resourcePath]?[hash]"; "webpack://[namespace]/[resourcePath]?[hash]";
/** @type {string} */
this.namespace = options.namespace || ""; this.namespace = options.namespace || "";
/** @type {SourceMapDevToolPluginOptions} */
this.options = options; this.options = options;
} }
@ -196,10 +192,6 @@ class SourceMapDevToolPlugin {
const cache = compilation.getCache("SourceMapDevToolPlugin"); const cache = compilation.getCache("SourceMapDevToolPlugin");
/** @type {Map<string | Module, string>} */ /** @type {Map<string | Module, string>} */
const moduleToSourceNameMapping = new Map(); const moduleToSourceNameMapping = new Map();
/**
* @type {Function}
* @returns {void}
*/
const reportProgress = const reportProgress =
ProgressPlugin.getReporter(compilation.compiler) || (() => {}); ProgressPlugin.getReporter(compilation.compiler) || (() => {});

View File

@ -90,7 +90,8 @@ const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
class Template { class Template {
/** /**
* @param {Function} fn a runtime function (.runtime.js) "template" * @template {EXPECTED_FUNCTION} T
* @param {T} fn a runtime function (.runtime.js) "template"
* @returns {string} the updated and normalized function string * @returns {string} the updated and normalized function string
*/ */
static getFunctionContent(fn) { static getFunctionContent(fn) {

View File

@ -50,10 +50,10 @@ const prepareId = id => {
* @param {((arg0: number) => string) | undefined} handler handler * @param {((arg0: number) => string) | undefined} handler handler
* @param {AssetInfo | undefined} assetInfo asset info * @param {AssetInfo | undefined} assetInfo asset info
* @param {string} hashName hash name * @param {string} hashName hash name
* @returns {ReplacerFunction} hash replacer function * @returns {Replacer} hash replacer function
*/ */
const hashLength = (replacer, handler, assetInfo, hashName) => { const hashLength = (replacer, handler, assetInfo, hashName) => {
/** @type {ReplacerFunction} */ /** @type {Replacer} */
const fn = (match, arg, input) => { const fn = (match, arg, input) => {
let result; let result;
const length = arg && Number.parseInt(arg, 10); const length = arg && Number.parseInt(arg, 10);
@ -81,7 +81,7 @@ const hashLength = (replacer, handler, assetInfo, hashName) => {
return fn; return fn;
}; };
/** @typedef {(match: string, arg?: string, input?: string) => string} Replacer */ /** @typedef {(match: string, arg: string | undefined, input: string) => string} Replacer */
/** /**
* @param {string | number | null | undefined | (() => string | number | null | undefined)} value value * @param {string | number | null | undefined | (() => string | number | null | undefined)} value value
@ -113,10 +113,11 @@ const replacer = (value, allowEmpty) => {
const deprecationCache = new Map(); const deprecationCache = new Map();
const deprecatedFunction = (() => () => {})(); const deprecatedFunction = (() => () => {})();
/** /**
* @param {Function} fn function * @template {(...args: EXPECTED_ANY[]) => EXPECTED_ANY} T
* @param {T} fn function
* @param {string} message message * @param {string} message message
* @param {string} code code * @param {string} code code
* @returns {(...args: any[]) => void} function with deprecation output * @returns {T} function with deprecation output
*/ */
const deprecated = (fn, message, code) => { const deprecated = (fn, message, code) => {
let d = deprecationCache.get(message); let d = deprecationCache.get(message);
@ -124,10 +125,12 @@ const deprecated = (fn, message, code) => {
d = util.deprecate(deprecatedFunction, message, code); d = util.deprecate(deprecatedFunction, message, code);
deprecationCache.set(message, d); deprecationCache.set(message, d);
} }
return (...args) => { return /** @type {T} */ (
(...args) => {
d(); d();
return fn(...args); return fn(...args);
}; }
);
}; };
/** @typedef {string | ((pathData: PathData, assetInfo?: AssetInfo) => string)} TemplatePath */ /** @typedef {string | ((pathData: PathData, assetInfo?: AssetInfo) => string)} TemplatePath */
@ -141,7 +144,7 @@ const deprecated = (fn, message, code) => {
const replacePathVariables = (path, data, assetInfo) => { const replacePathVariables = (path, data, assetInfo) => {
const chunkGraph = data.chunkGraph; const chunkGraph = data.chunkGraph;
/** @type {Map<string, Function>} */ /** @type {Map<string, Replacer>} */
const replacements = new Map(); const replacements = new Map();
// Filename context // Filename context
@ -366,7 +369,7 @@ const replacePathVariables = (path, data, assetInfo) => {
const [, kind, arg] = contentMatch; const [, kind, arg] = contentMatch;
const replacer = replacements.get(kind); const replacer = replacements.get(kind);
if (replacer !== undefined) { if (replacer !== undefined) {
return replacer(match, arg, path); return replacer(match, arg, /** @type {string} */ (path));
} }
} else if (match.startsWith("[\\") && match.endsWith("\\]")) { } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
return `[${match.slice(2, -2)}]`; return `[${match.slice(2, -2)}]`;

View File

@ -152,7 +152,7 @@ class Profiler {
* @property {Tracer} trace instance of Tracer * @property {Tracer} trace instance of Tracer
* @property {number} counter Counter * @property {number} counter Counter
* @property {Profiler} profiler instance of Profiler * @property {Profiler} profiler instance of Profiler
* @property {Function} end the end function * @property {(callback: (err?: null | Error) => void) => void} end the end function
*/ */
/** /**
@ -208,9 +208,6 @@ const createTrace = (fs, outputPath) => {
trace, trace,
counter, counter,
profiler, profiler,
/**
* @param {() => void} callback callback
*/
end: callback => { end: callback => {
trace.push("]"); trace.push("]");
// Wait until the write stream finishes. // Wait until the write stream finishes.

View File

@ -56,7 +56,7 @@ const HMR_DEPENDENCY_TYPES = new Set([
]); ]);
/** /**
* @param {undefined|string|RegExp|Function} test test option * @param {Options["test"]} test test option
* @param {Module} module the module * @param {Module} module the module
* @returns {boolean | null | string} true, if the module should be selected * @returns {boolean | null | string} true, if the module should be selected
*/ */
@ -343,13 +343,19 @@ class LazyCompilationDependencyFactory extends ModuleFactory {
* @returns {Promise<BackendApi>} backend * @returns {Promise<BackendApi>} backend
*/ */
/** @typedef {BackendHandler | PromiseBackendHandler} BackEnd */
/**
* @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
*/
class LazyCompilationPlugin { class LazyCompilationPlugin {
/** /**
* @param {object} options options * @param {Options} options options
* @param {BackendHandler | PromiseBackendHandler} options.backend the backend
* @param {boolean} options.entries true, when entries are lazy compiled
* @param {boolean} options.imports true, when import() modules are lazy compiled
* @param {RegExp | string | ((module: Module) => boolean) | undefined} options.test additional filter for lazy compiled entrypoint modules
*/ */
constructor({ backend, entries, imports, test }) { constructor({ backend, entries, imports, test }) {
this.backend = backend; this.backend = backend;

View File

@ -64,7 +64,7 @@ const memoize = require("./util/memoize");
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
/** /**
* @template {Function} T * @template {EXPECTED_FUNCTION} T
* @param {() => T} factory factory function * @param {() => T} factory factory function
* @returns {T} function * @returns {T} function
*/ */

View File

@ -124,9 +124,9 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
/** /**
* @callback GetName * @callback GetName
* @param {Module=} module * @param {Module} module
* @param {Chunk[]=} chunks * @param {Chunk[]} chunks
* @param {string=} key * @param {string} key
* @returns {string=} * @returns {string=}
*/ */
@ -407,7 +407,7 @@ const totalSize = sizes => {
}; };
/** /**
* @param {false | string | Function | undefined} name the chunk name * @param {OptimizationSplitChunksCacheGroup["name"]} name the chunk name
* @returns {GetName | undefined} a function to get the name of the chunk * @returns {GetName | undefined} a function to get the name of the chunk
*/ */
const normalizeName = name => { const normalizeName = name => {
@ -519,7 +519,7 @@ const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => {
}; };
/** /**
* @param {undefined|boolean|string|RegExp|Function} test test option * @param {OptimizationSplitChunksCacheGroup["test"]} test test option
* @param {Module} module the module * @param {Module} module the module
* @param {CacheGroupsContext} context context object * @param {CacheGroupsContext} context context object
* @returns {boolean} true, if the module should be selected * @returns {boolean} true, if the module should be selected
@ -542,7 +542,7 @@ const checkTest = (test, module, context) => {
}; };
/** /**
* @param {undefined|string|RegExp|Function} test type option * @param {OptimizationSplitChunksCacheGroup["type"]} test type option
* @param {Module} module the module * @param {Module} module the module
* @returns {boolean} true, if the module should be selected * @returns {boolean} true, if the module should be selected
*/ */
@ -563,7 +563,7 @@ const checkModuleType = (test, module) => {
}; };
/** /**
* @param {undefined|string|RegExp|Function} test type option * @param {OptimizationSplitChunksCacheGroup["layer"]} test type option
* @param {Module} module the module * @param {Module} module the module
* @returns {boolean} true, if the module should be selected * @returns {boolean} true, if the module should be selected
*/ */

View File

@ -157,14 +157,14 @@ jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError));
jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError)); jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError));
jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError)); jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError));
// If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers // If in a sandboxed environment (e.g. jest), this escapes the sandbox and registers
// real Object and Array types to. These types may occur in the wild too, e. g. when // real Object and Array types to. These types may occur in the wild too, e.g. when
// using Structured Clone in postMessage. // using Structured Clone in postMessage.
// eslint-disable-next-line n/exports-style // eslint-disable-next-line n/exports-style
if (exports.constructor !== Object) { if (exports.constructor !== Object) {
// eslint-disable-next-line jsdoc/check-types, n/exports-style // eslint-disable-next-line n/exports-style
const Obj = /** @type {typeof Object} */ (exports.constructor); const Obj = /** @type {ObjectConstructor} */ (exports.constructor);
const Fn = /** @type {typeof Function} */ (Obj.constructor); const Fn = /** @type {FunctionConstructor} */ (Obj.constructor);
for (const [type, config] of Array.from(jsTypes)) { for (const [type, config] of Array.from(jsTypes)) {
if (type) { if (type) {
const Type = new Fn(`return ${type.name};`)(); const Type = new Fn(`return ${type.name};`)();

View File

@ -98,7 +98,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {string=} message * @property {string=} message
* @property {string[]=} trace * @property {string[]=} trace
* @property {StatsLoggingEntry[]=} children * @property {StatsLoggingEntry[]=} children
* @property {any[]=} args * @property {EXPECTED_ANY[]=} args
* @property {number=} time * @property {number=} time
*/ */
@ -374,8 +374,9 @@ const mapObject = (obj, fn) => {
}; };
/** /**
* @template T
* @param {Compilation} compilation the compilation * @param {Compilation} compilation the compilation
* @param {(compilation: Compilation, name: string) => any[]} getItems get items * @param {(compilation: Compilation, name: string) => T[]} getItems get items
* @returns {number} total number * @returns {number} total number
*/ */
const countWithChildren = (compilation, getItems) => { const countWithChildren = (compilation, getItems) => {
@ -1576,7 +1577,7 @@ const SIMPLE_EXTRACTORS = {
} }
}; };
/** @type {Record<string, Record<string, (thing: any, context: StatsFactoryContext, options: NormalizedStatsOptions) => boolean | undefined>>} */ /** @type {Record<string, Record<string, (thing: ModuleGraphConnection, context: StatsFactoryContext, options: NormalizedStatsOptions, idx: number, i: number) => boolean | undefined>>} */
const FILTER = { const FILTER = {
"module.reasons": { "module.reasons": {
"!orphanModules": (reason, { compilation: { chunkGraph } }) => { "!orphanModules": (reason, { compilation: { chunkGraph } }) => {
@ -1590,7 +1591,7 @@ const FILTER = {
} }
}; };
/** @type {Record<string, Record<string, (thing: KnownStatsError, context: StatsFactoryContext, options: NormalizedStatsOptions) => boolean | undefined>>} */ /** @type {Record<string, Record<string, (thing: KnownStatsError, context: StatsFactoryContext, options: NormalizedStatsOptions, idx: number, i: number) => boolean | undefined>>} */
const FILTER_RESULTS = { const FILTER_RESULTS = {
"compilation.warnings": { "compilation.warnings": {
warningsFilter: util.deprecate( warningsFilter: util.deprecate(
@ -1606,39 +1607,20 @@ const FILTER_RESULTS = {
} }
}; };
/** @type {Record<string, (comparators: Function[], context: StatsFactoryContext) => void>} */ /**
* @type {Record<string, (comparators: Comparator<Module>[], context: StatsFactoryContext) => void>}
*/
const MODULES_SORTER = { const MODULES_SORTER = {
_: (comparators, { compilation: { moduleGraph } }) => { _: (comparators, { compilation: { moduleGraph } }) => {
comparators.push( comparators.push(
compareSelect( compareSelect(m => moduleGraph.getDepth(m), compareNumbers),
/** compareSelect(m => moduleGraph.getPreOrderIndex(m), compareNumbers),
* @param {Module} m module compareSelect(m => m.identifier(), compareIds)
* @returns {number | null} depth
*/
m => moduleGraph.getDepth(m),
compareNumbers
),
compareSelect(
/**
* @param {Module} m module
* @returns {number | null} index
*/
m => moduleGraph.getPreOrderIndex(m),
compareNumbers
),
compareSelect(
/**
* @param {Module} m module
* @returns {string} identifier
*/
m => m.identifier(),
compareIds
)
); );
} }
}; };
/** @type {Record<string, Record<string, (comparators: Function[], context: StatsFactoryContext) => void>>} */ /** @type {Record<string, Record<string, (comparators: Comparator<any>[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>>} */
const SORTERS = { const SORTERS = {
"compilation.chunks": { "compilation.chunks": {
_: comparators => { _: comparators => {
@ -2434,9 +2416,10 @@ const RESULT_SORTERS = {
}; };
/** /**
* @param {Record<string, Record<string, Function>>} config the config see above * @template T
* @param {Record<string, Record<string, T>>} config the config see above
* @param {NormalizedStatsOptions} options stats options * @param {NormalizedStatsOptions} options stats options
* @param {(hookFor: string, fn: Function) => void} fn handler function called for every active line in config * @param {(hookFor: string, fn: T) => void} fn handler function called for every active line in config
* @returns {void} * @returns {void}
*/ */
const iterateConfig = (config, options, fn) => { const iterateConfig = (config, options, fn) => {
@ -2525,13 +2508,18 @@ class DefaultStatsFactoryPlugin {
* @param {NormalizedStatsOptions} options stats options * @param {NormalizedStatsOptions} options stats options
*/ */
(stats, options) => { (stats, options) => {
iterateConfig(SIMPLE_EXTRACTORS, options, (hookFor, fn) => { iterateConfig(
/** @type {TODO} */
(SIMPLE_EXTRACTORS),
options,
(hookFor, fn) => {
stats.hooks.extract stats.hooks.extract
.for(hookFor) .for(hookFor)
.tap("DefaultStatsFactoryPlugin", (obj, data, ctx) => .tap("DefaultStatsFactoryPlugin", (obj, data, ctx) =>
fn(obj, data, ctx, options, stats) fn(obj, data, ctx, options, stats)
); );
}); }
);
iterateConfig(FILTER, options, (hookFor, fn) => { iterateConfig(FILTER, options, (hookFor, fn) => {
stats.hooks.filter stats.hooks.filter
.for(hookFor) .for(hookFor)
@ -2560,13 +2548,18 @@ class DefaultStatsFactoryPlugin {
fn(comparators, ctx, options) fn(comparators, ctx, options)
); );
}); });
iterateConfig(RESULT_GROUPERS, options, (hookFor, fn) => { iterateConfig(
/** @type {TODO} */
(RESULT_GROUPERS),
options,
(hookFor, fn) => {
stats.hooks.groupResults stats.hooks.groupResults
.for(hookFor) .for(hookFor)
.tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) => .tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) =>
fn(groupConfigs, ctx, options) fn(groupConfigs, ctx, options)
); );
}); }
);
for (const key of Object.keys(ITEM_NAMES)) { for (const key of Object.keys(ITEM_NAMES)) {
const itemName = ITEM_NAMES[key]; const itemName = ITEM_NAMES[key];
stats.hooks.getItemName stats.hooks.getItemName

View File

@ -34,12 +34,12 @@ class SortableSet extends Set {
this._lastActiveSortFn = NONE; this._lastActiveSortFn = NONE;
/** /**
* @private * @private
* @type {Map<Function, any> | undefined} * @type {Map<(set: SortableSet<T>) => TODO, TODO> | undefined}
*/ */
this._cache = undefined; this._cache = undefined;
/** /**
* @private * @private
* @type {Map<Function, any> | undefined} * @type {Map<(set: SortableSet<T>) => TODO, TODO> | undefined}
*/ */
this._cacheOrderIndependent = undefined; this._cacheOrderIndependent = undefined;
} }

View File

@ -69,11 +69,12 @@ const compileSearch = (funcName, predicate, reversed, extraArgs, earlyOut) => {
* A(): Performs a binary search on an array using the comparison operator specified. * A(): Performs a binary search on an array using the comparison operator specified.
* P(): Performs a binary search on an array using a _custom comparison function_ * P(): Performs a binary search on an array using a _custom comparison function_
* `c(x,y)` **and** comparison operator specified by `predicate`. * `c(x,y)` **and** comparison operator specified by `predicate`.
* @template T
* @param {BinarySearchPredicate} predicate The predicate / comparison operator to be used in the binary search. * @param {BinarySearchPredicate} predicate The predicate / comparison operator to be used in the binary search.
* @param {boolean} reversed Whether the search should be reversed. * @param {boolean} reversed Whether the search should be reversed.
* @param {SearchPredicateSuffix} suffix The suffix to be used in the function name. * @param {SearchPredicateSuffix} suffix The suffix to be used in the function name.
* @param {boolean=} earlyOut Whether the search should return as soon as a match is found. * @param {boolean=} earlyOut Whether the search should return as soon as a match is found.
* @returns {Function} The compiled binary search function. * @returns {(items: T[], start: number, compareFn?: number | ((item: T, needle: number) => number), l?: number, h?: number) => number} The compiled binary search function.
*/ */
const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => { const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => {
const arg1 = compileSearch("A", `x${predicate}y`, reversed, ["y"], earlyOut); const arg1 = compileSearch("A", `x${predicate}y`, reversed, ["y"], earlyOut);

View File

@ -199,7 +199,7 @@ const parseObject = obj => {
/** /**
* @template {object} T * @template {object} T
* @param {Map<string, ObjectParsedPropertyEntry>} info static properties (key is property name) * @param {Map<string, ObjectParsedPropertyEntry>} info static properties (key is property name)
* @param {{ byProperty: string, fn: Function } | undefined} dynamicInfo dynamic part * @param {{ byProperty: string, fn: (...args: EXPECTED_ANY[]) => T } | undefined} dynamicInfo dynamic part
* @returns {T} the object * @returns {T} the object
*/ */
const serializeObject = (info, dynamicInfo) => { const serializeObject = (info, dynamicInfo) => {

View File

@ -7,7 +7,7 @@
const util = require("util"); const util = require("util");
/** @type {Map<string, Function>} */ /** @type {Map<string, () => void>} */
const deprecationCache = new Map(); const deprecationCache = new Map();
/** /**
@ -23,7 +23,7 @@ const deprecationCache = new Map();
/** /**
* @param {string} message deprecation message * @param {string} message deprecation message
* @param {string} code deprecation code * @param {string} code deprecation code
* @returns {Function} function to trigger deprecation * @returns {() => void} function to trigger deprecation
*/ */
const createDeprecation = (message, code) => { const createDeprecation = (message, code) => {
const cached = deprecationCache.get(message); const cached = deprecationCache.get(message);

View File

@ -30,6 +30,8 @@ const WebAssemblyExportImportedDependency = require("../dependencies/WebAssembly
/** @typedef {import("@webassemblyjs/ast").ModuleImport} ModuleImport */ /** @typedef {import("@webassemblyjs/ast").ModuleImport} ModuleImport */
/** @typedef {import("@webassemblyjs/ast").ModuleExport} ModuleExport */ /** @typedef {import("@webassemblyjs/ast").ModuleExport} ModuleExport */
/** @typedef {import("@webassemblyjs/ast").Global} Global */ /** @typedef {import("@webassemblyjs/ast").Global} Global */
/** @typedef {import("@webassemblyjs/ast").AST} AST */
/** @typedef {import("@webassemblyjs/ast").GlobalType} GlobalType */
/** /**
* @template T * @template T
* @typedef {import("@webassemblyjs/ast").NodePath<T>} NodePath * @typedef {import("@webassemblyjs/ast").NodePath<T>} NodePath
@ -42,7 +44,7 @@ const WebAssemblyExportImportedDependency = require("../dependencies/WebAssembly
/** /**
* @template T * @template T
* @param {((prev: ArrayBuffer) => ArrayBuffer)[]} fns transforms * @param {((prev: ArrayBuffer) => ArrayBuffer)[]} fns transforms
* @returns {Function} composed transform * @returns {ArrayBufferTransform} composed transform
*/ */
const compose = (...fns) => const compose = (...fns) =>
fns.reduce( fns.reduce(
@ -53,7 +55,7 @@ const compose = (...fns) =>
/** /**
* Removes the start instruction * Removes the start instruction
* @param {object} state state * @param {object} state state
* @param {object} state.ast Module's ast * @param {AST} state.ast Module's ast
* @returns {ArrayBufferTransform} transform * @returns {ArrayBufferTransform} transform
*/ */
const removeStartFunc = state => bin => const removeStartFunc = state => bin =>
@ -65,7 +67,7 @@ const removeStartFunc = state => bin =>
/** /**
* Get imported globals * Get imported globals
* @param {object} ast Module's AST * @param {AST} ast Module's AST
* @returns {t.ModuleImport[]} - nodes * @returns {t.ModuleImport[]} - nodes
*/ */
const getImportedGlobals = ast => { const getImportedGlobals = ast => {
@ -85,7 +87,7 @@ const getImportedGlobals = ast => {
/** /**
* Get the count for imported func * Get the count for imported func
* @param {object} ast Module's AST * @param {AST} ast Module's AST
* @returns {number} - count * @returns {number} - count
*/ */
const getCountImportedFunc = ast => { const getCountImportedFunc = ast => {
@ -104,7 +106,7 @@ const getCountImportedFunc = ast => {
/** /**
* Get next type index * Get next type index
* @param {object} ast Module's AST * @param {AST} ast Module's AST
* @returns {t.Index} - index * @returns {t.Index} - index
*/ */
const getNextTypeIndex = ast => { const getNextTypeIndex = ast => {
@ -122,7 +124,7 @@ const getNextTypeIndex = ast => {
* The Func section metadata provide information for implemented funcs * The Func section metadata provide information for implemented funcs
* in order to have the correct index we shift the index by number of external * in order to have the correct index we shift the index by number of external
* functions. * functions.
* @param {object} ast Module's AST * @param {AST} ast Module's AST
* @param {number} countImportedFunc number of imported funcs * @param {number} countImportedFunc number of imported funcs
* @returns {t.Index} - index * @returns {t.Index} - index
*/ */
@ -168,7 +170,7 @@ const createDefaultInitForGlobal = globalType => {
* *
* Note that globals will become mutable. * Note that globals will become mutable.
* @param {object} state transformation state * @param {object} state transformation state
* @param {object} state.ast Module's ast * @param {AST} state.ast Module's ast
* @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function
* @returns {ArrayBufferTransform} transform * @returns {ArrayBufferTransform} transform
*/ */
@ -180,7 +182,9 @@ const rewriteImportedGlobals = state => bin => {
bin = editWithAST(state.ast, bin, { bin = editWithAST(state.ast, bin, {
ModuleImport(path) { ModuleImport(path) {
if (t.isGlobalType(path.node.descr)) { if (t.isGlobalType(path.node.descr)) {
const globalType = /** @type {TODO} */ (path.node.descr); const globalType =
/** @type {GlobalType} */
(path.node.descr);
globalType.mutability = "var"; globalType.mutability = "var";
@ -238,7 +242,7 @@ const rewriteImportedGlobals = state => bin => {
/** /**
* Rewrite the export names * Rewrite the export names
* @param {object} state state * @param {object} state state
* @param {object} state.ast Module's ast * @param {AST} state.ast Module's ast
* @param {Module} state.module Module * @param {Module} state.module Module
* @param {ModuleGraph} state.moduleGraph module graph * @param {ModuleGraph} state.moduleGraph module graph
* @param {Set<string>} state.externalExports Module * @param {Set<string>} state.externalExports Module
@ -272,7 +276,7 @@ const rewriteExportNames =
/** /**
* Mangle import names and modules * Mangle import names and modules
* @param {object} state state * @param {object} state state
* @param {object} state.ast Module's ast * @param {AST} state.ast Module's ast
* @param {Map<string, UsedWasmDependency>} state.usedDependencyMap mappings to mangle names * @param {Map<string, UsedWasmDependency>} state.usedDependencyMap mappings to mangle names
* @returns {ArrayBufferTransform} transform * @returns {ArrayBufferTransform} transform
*/ */
@ -300,7 +304,7 @@ const rewriteImports =
* *
* The init function fills the globals given input arguments. * The init function fills the globals given input arguments.
* @param {object} state transformation state * @param {object} state transformation state
* @param {object} state.ast Module's ast * @param {AST} state.ast Module's ast
* @param {t.Identifier} state.initFuncId identifier of the init function * @param {t.Identifier} state.initFuncId identifier of the init function
* @param {t.Index} state.startAtFuncOffset index of the start function * @param {t.Index} state.startAtFuncOffset index of the start function
* @param {t.ModuleImport[]} state.importedGlobals list of imported globals * @param {t.ModuleImport[]} state.importedGlobals list of imported globals
@ -442,7 +446,9 @@ class WebAssemblyGenerator extends Generator {
* @returns {Source | null} generated code * @returns {Source | null} generated code
*/ */
generate(module, { moduleGraph, runtime }) { generate(module, { moduleGraph, runtime }) {
const bin = /** @type {Source} */ (module.originalSource()).source(); const bin =
/** @type {Buffer} */
(/** @type {Source} */ (module.originalSource()).source());
const initFuncId = t.identifier(""); const initFuncId = t.identifier("");

View File

@ -13,6 +13,8 @@ const StaticExportsDependency = require("../dependencies/StaticExportsDependency
const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency");
const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
/** @typedef {import("@webassemblyjs/ast").ModuleImport} ModuleImport */
/** @typedef {import("@webassemblyjs/ast").NumberLiteral} NumberLiteral */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").BuildInfo} BuildInfo */ /** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
@ -101,8 +103,9 @@ class WebAssemblyParser extends Parser {
/** @type {Record<string, string> | undefined} */ /** @type {Record<string, string> | undefined} */
let jsIncompatibleExports = (buildMeta.jsIncompatibleExports = undefined); let jsIncompatibleExports = (buildMeta.jsIncompatibleExports = undefined);
/** @type {TODO[]} */ /** @type {(ModuleImport | null)[]} */
const importedGlobals = []; const importedGlobals = [];
t.traverse(module, { t.traverse(module, {
ModuleExport({ node }) { ModuleExport({ node }) {
const descriptor = node.descr; const descriptor = node.descr;
@ -130,7 +133,7 @@ class WebAssemblyParser extends Parser {
if (node.descr && node.descr.exportType === "Global") { if (node.descr && node.descr.exportType === "Global") {
const refNode = const refNode =
importedGlobals[/** @type {TODO} */ (node.descr.id.value)]; importedGlobals[/** @type {NumberLiteral} */ (node.descr.id).value];
if (refNode) { if (refNode) {
const dep = new WebAssemblyExportImportedDependency( const dep = new WebAssemblyExportImportedDependency(
node.name, node.name,
@ -170,7 +173,8 @@ class WebAssemblyParser extends Parser {
onlyDirectImport = "Table"; onlyDirectImport = "Table";
} else if (t.isFuncImportDescr(node.descr) === true) { } else if (t.isFuncImportDescr(node.descr) === true) {
const incompatibleType = getJsIncompatibleType( const incompatibleType = getJsIncompatibleType(
/** @type {t.Signature} */ (node.descr.signature) /** @type {t.Signature} */
(node.descr.signature)
); );
if (incompatibleType) { if (incompatibleType) {
onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`; onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`;

View File

@ -604,7 +604,7 @@
}, },
{ {
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((context: TODO) => string)"
} }
] ]
}, },
@ -616,7 +616,7 @@
}, },
{ {
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((context: TODO) => string)"
} }
] ]
}, },
@ -2886,7 +2886,7 @@
}, },
{ {
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((layer: string | null) => boolean)"
} }
] ]
}, },
@ -2964,7 +2964,7 @@
}, },
{ {
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((module: import('../lib/Module'), chunks: import('../lib/Chunk')[], key: string) => string | undefined)"
} }
] ]
}, },
@ -2988,7 +2988,7 @@
}, },
{ {
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((module: import('../lib/Module'), context: import('../lib/optimize/SplitChunksPlugin').CacheGroupsContext) => boolean)"
} }
] ]
}, },
@ -3004,7 +3004,7 @@
}, },
{ {
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((type: string) => boolean)"
} }
] ]
}, },
@ -3272,7 +3272,7 @@
}, },
{ {
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((module: import('../lib/Module'), chunks: import('../lib/Chunk')[], key: string) => string | undefined)"
} }
] ]
}, },

View File

@ -80,7 +80,7 @@
{ {
"description": "Custom function generating the identifier.", "description": "Custom function generating the identifier.",
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((context: any) => string)"
} }
] ]
}, },
@ -124,7 +124,7 @@
{ {
"description": "Custom function generating the identifier.", "description": "Custom function generating the identifier.",
"instanceof": "Function", "instanceof": "Function",
"tsType": "Function" "tsType": "((context: any) => string)"
} }
] ]
}, },

68
types.d.ts vendored
View File

@ -970,9 +970,9 @@ declare interface CacheGroupSource {
key?: string; key?: string;
priority?: number; priority?: number;
getName?: ( getName?: (
module?: Module, module: Module,
chunks?: Chunk[], chunks: Chunk[],
key?: string key: string
) => undefined | string; ) => undefined | string;
chunksFilter?: (chunk: Chunk) => undefined | boolean; chunksFilter?: (chunk: Chunk) => undefined | boolean;
enforce?: boolean; enforce?: boolean;
@ -3653,7 +3653,7 @@ declare interface DeterministicModuleIdsPluginOptions {
*/ */
failOnConflict?: boolean; failOnConflict?: boolean;
} }
type DevtoolModuleFilenameTemplate = string | Function; type DevtoolModuleFilenameTemplate = string | ((context?: any) => string);
declare interface Dirent { declare interface Dirent {
isFile: () => boolean; isFile: () => boolean;
isDirectory: () => boolean; isDirectory: () => boolean;
@ -4296,12 +4296,12 @@ declare interface EvalDevToolModulePluginOptions {
/** /**
* module filename template * module filename template
*/ */
moduleFilenameTemplate?: string | Function; moduleFilenameTemplate?: string | ((context?: any) => string);
} }
declare class EvalSourceMapDevToolPlugin { declare class EvalSourceMapDevToolPlugin {
constructor(inputOptions: string | SourceMapDevToolPluginOptions); constructor(inputOptions: string | SourceMapDevToolPluginOptions);
sourceMapComment: string; sourceMapComment: string;
moduleFilenameTemplate: string | Function; moduleFilenameTemplate: string | ((context?: any) => string);
namespace: string; namespace: string;
options: SourceMapDevToolPluginOptions; options: SourceMapDevToolPluginOptions;
@ -10393,7 +10393,7 @@ declare interface OptimizationSplitChunksCacheGroup {
/** /**
* Assign modules to a cache group by module layer. * Assign modules to a cache group by module layer.
*/ */
layer?: string | Function | RegExp; layer?: string | RegExp | ((layer: null | string) => boolean);
/** /**
* Maximum number of requests which are accepted for on-demand loading. * Maximum number of requests which are accepted for on-demand loading.
@ -10443,7 +10443,10 @@ declare interface OptimizationSplitChunksCacheGroup {
/** /**
* Give chunks for this cache group a name (chunks with equal name are merged). * Give chunks for this cache group a name (chunks with equal name are merged).
*/ */
name?: string | false | Function; name?:
| string
| false
| ((module: Module, chunks: Chunk[], key: string) => undefined | string);
/** /**
* Priority of this cache group. * Priority of this cache group.
@ -10458,12 +10461,15 @@ declare interface OptimizationSplitChunksCacheGroup {
/** /**
* Assign modules to a cache group by module name. * Assign modules to a cache group by module name.
*/ */
test?: string | Function | RegExp; test?:
| string
| RegExp
| ((module: Module, context: CacheGroupsContext) => boolean);
/** /**
* Assign modules to a cache group by module type. * Assign modules to a cache group by module type.
*/ */
type?: string | Function | RegExp; type?: string | RegExp | ((type: string) => boolean);
/** /**
* Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal. * Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal.
@ -10599,7 +10605,10 @@ declare interface OptimizationSplitChunksOptions {
/** /**
* Give chunks created a name (chunks with equal name are merged). * Give chunks created a name (chunks with equal name are merged).
*/ */
name?: string | false | Function; name?:
| string
| false
| ((module: Module, chunks: Chunk[], key: string) => undefined | string);
/** /**
* Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal. * Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal.
@ -10748,12 +10757,12 @@ declare interface Output {
/** /**
* Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers. * Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.
*/ */
devtoolFallbackModuleFilenameTemplate?: string | Function; devtoolFallbackModuleFilenameTemplate?: string | ((context?: any) => string);
/** /**
* Filename template string of function for the sources array in a generated SourceMap. * Filename template string of function for the sources array in a generated SourceMap.
*/ */
devtoolModuleFilenameTemplate?: string | Function; devtoolModuleFilenameTemplate?: string | ((context?: any) => string);
/** /**
* Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries. * Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries.
@ -11042,12 +11051,12 @@ declare interface OutputNormalized {
/** /**
* Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers. * Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.
*/ */
devtoolFallbackModuleFilenameTemplate?: string | Function; devtoolFallbackModuleFilenameTemplate?: string | ((context?: any) => string);
/** /**
* Filename template string of function for the sources array in a generated SourceMap. * Filename template string of function for the sources array in a generated SourceMap.
*/ */
devtoolModuleFilenameTemplate?: string | Function; devtoolModuleFilenameTemplate?: string | ((context?: any) => string);
/** /**
* Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries. * Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries.
@ -11487,7 +11496,7 @@ type ProblemType =
| "multiple-values-unexpected" | "multiple-values-unexpected"
| "invalid-value"; | "invalid-value";
declare interface ProcessAssetsAdditionalOptions { declare interface ProcessAssetsAdditionalOptions {
additionalAssets?: true | Function; additionalAssets?: any;
} }
declare class Profiler { declare class Profiler {
constructor(inspector?: any); constructor(inspector?: any);
@ -14354,8 +14363,8 @@ declare class SourceMapDevToolPlugin {
| string | string
| false | false
| ((pathData: PathData, assetInfo?: AssetInfo) => string); | ((pathData: PathData, assetInfo?: AssetInfo) => string);
moduleFilenameTemplate: string | Function; moduleFilenameTemplate: string | ((context?: any) => string);
fallbackModuleFilenameTemplate: string | Function; fallbackModuleFilenameTemplate: string | ((context?: any) => string);
namespace: string; namespace: string;
options: SourceMapDevToolPluginOptions; options: SourceMapDevToolPluginOptions;
@ -14392,7 +14401,7 @@ declare interface SourceMapDevToolPluginOptions {
/** /**
* Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap used only if 'moduleFilenameTemplate' would result in a conflict. * Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap used only if 'moduleFilenameTemplate' would result in a conflict.
*/ */
fallbackModuleFilenameTemplate?: string | Function; fallbackModuleFilenameTemplate?: string | ((context?: any) => string);
/** /**
* Path prefix to which the [file] placeholder is relative to. * Path prefix to which the [file] placeholder is relative to.
@ -14417,7 +14426,7 @@ declare interface SourceMapDevToolPluginOptions {
/** /**
* Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap. * Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap.
*/ */
moduleFilenameTemplate?: string | Function; moduleFilenameTemplate?: string | ((context?: any) => string);
/** /**
* Namespace prefix to allow multiple webpack roots in the devtools. * Namespace prefix to allow multiple webpack roots in the devtools.
@ -14485,11 +14494,7 @@ declare interface SplitChunksOptions {
module: Module, module: Module,
context: CacheGroupsContext context: CacheGroupsContext
) => null | CacheGroupSource[]; ) => null | CacheGroupSource[];
getName: ( getName: (module: Module, chunks: Chunk[], key: string) => undefined | string;
module?: Module,
chunks?: Chunk[],
key?: string
) => undefined | string;
usedExports: boolean; usedExports: boolean;
fallbackCacheGroup: FallbackCacheGroup; fallbackCacheGroup: FallbackCacheGroup;
} }
@ -15285,7 +15290,7 @@ declare interface TargetItemWithoutConnection {
} }
declare class Template { declare class Template {
constructor(); constructor();
static getFunctionContent(fn: Function): string; static getFunctionContent<T extends Function>(fn: T): string;
static toIdentifier(str: string): string; static toIdentifier(str: string): string;
static toComment(str: string): string; static toComment(str: string): string;
static toNormalComment(str: string): string; static toNormalComment(str: string): string;
@ -16066,19 +16071,10 @@ declare namespace exports {
export let REGEXP_NAMESPACE: RegExp; export let REGEXP_NAMESPACE: RegExp;
export let createFilename: ( export let createFilename: (
module: string | Module, module: string | Module,
options: any, options: { namespace?: string; moduleFilenameTemplate?: any },
__2: { __2: {
/**
* requestShortener
*/
requestShortener: RequestShortener; requestShortener: RequestShortener;
/**
* chunk graph
*/
chunkGraph: ChunkGraph; chunkGraph: ChunkGraph;
/**
* the hash function to use
*/
hashFunction?: string | typeof Hash; hashFunction?: string | typeof Hash;
} }
) => string; ) => string;