feat: refactoring project

This commit is contained in:
Carlos
2024-11-23 14:56:07 -05:00
parent f0c2a50c18
commit 1c6db5818d
2351 changed files with 39323 additions and 60326 deletions

15
node_modules/webpack/README.md generated vendored
View File

@@ -8,9 +8,10 @@
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![builds1][builds1]][builds1-url]
[![builds2][builds2]][builds2-url]
[![dependency-review][dependency-review]][dependency-review-url]
[![coverage][cover]][cover-url]
[![licenses][licenses]][licenses-url]
[![PR's welcome][prs]][prs-url]
<br>
@@ -38,7 +39,7 @@
<a href="https://twitter.com/Webpack">
<img src="https://img.shields.io/twitter/follow/Webpack?style=social">
</a>
<a href="https://discord.gg/Tt5cKVwx">
<a href="https://discord.gg/5sxFZPdx2k">
<img src="https://img.shields.io/discord/1180618526436888586?label=discord&logo=discord&logoColor=white&style=flat">
</a>
<h1>webpack</h1>
@@ -716,9 +717,11 @@ src="https://static.monei.net/monei-logo.svg" height="30" alt="MONEI"></a>
[node-url]: https://nodejs.org
[prs]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg
[prs-url]: https://webpack.js.org/contribute/
[builds2]: https://dev.azure.com/webpack/webpack/_apis/build/status/webpack.webpack
[builds2-url]: https://dev.azure.com/webpack/webpack/_build/latest?definitionId=3
[licenses-url]: https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack?ref=badge_shield
[licenses]: https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack.svg?type=shield
[builds1]: https://github.com/webpack/webpack/actions/workflows/test.yml/badge.svg
[builds1-url]: https://github.com/webpack/webpack/actions/workflows/test.yml
[builds2]: https://dev.azure.com/webpack/webpack/_apis/build/status%2Fwebpack.webpack?branchName=main
[builds2-url]: https://dev.azure.com/webpack/webpack/_build/latest?definitionId=3&branchName=main
[dependency-review-url]: https://github.com/webpack/webpack/actions/workflows/dependency-review.yml
[dependency-review]: https://github.com/webpack/webpack/actions/workflows/dependency-review.yml/badge.svg
[cover]: https://codecov.io/gh/webpack/webpack/branch/master/graph/badge.svg?token=mDP3mQJNnn
[cover-url]: https://codecov.io/gh/webpack/webpack

13
node_modules/webpack/bin/webpack.js generated vendored
View File

@@ -80,8 +80,8 @@ const runCli = cli => {
if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
error => {
console.error(error);
err => {
console.error(err);
process.exitCode = 1;
}
);
@@ -113,8 +113,7 @@ if (!cli.installed) {
const fs = require("graceful-fs");
const readLine = require("readline");
const notify =
"CLI for webpack must be installed.\n" + ` ${cli.name} (${cli.url})\n`;
const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`;
console.error(notify);
@@ -137,7 +136,7 @@ if (!cli.installed) {
)} ${cli.package}".`
);
const question = `Do you want to install 'webpack-cli' (yes/no): `;
const question = "Do you want to install 'webpack-cli' (yes/no): ";
const questionInterface = readLine.createInterface({
input: process.stdin,
@@ -178,8 +177,8 @@ if (!cli.installed) {
.then(() => {
runCli(cli);
})
.catch(error => {
console.error(error);
.catch(err => {
console.error(err);
process.exitCode = 1;
});
});

3
node_modules/webpack/hot/log.js generated vendored
View File

@@ -73,7 +73,6 @@ module.exports.formatError = function (err) {
return message;
} else if (stack.indexOf(message) < 0) {
return message + "\n" + stack;
} else {
return stack;
}
return stack;
};

View File

@@ -2,7 +2,7 @@
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/*globals __webpack_hash__ */
/* globals __webpack_hash__ */
if (module.hot) {
/** @type {undefined|string} */
var lastHash;

2
node_modules/webpack/hot/poll.js generated vendored
View File

@@ -2,7 +2,7 @@
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/*globals __resourceQuery */
/* globals __resourceQuery */
if (module.hot) {
var hotPollInterval = +__resourceQuery.slice(1) || 10 * 60 * 1000;
var log = require("./log");

2
node_modules/webpack/hot/signal.js generated vendored
View File

@@ -2,7 +2,7 @@
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/*globals __resourceQuery */
/* globals __resourceQuery */
if (module.hot) {
var log = require("./log");

View File

@@ -144,6 +144,7 @@ class APIPlugin {
constructor(options = {}) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
@@ -213,7 +214,7 @@ class APIPlugin {
* @param {JavascriptParser} parser the parser
*/
const handler = parser => {
Object.keys(REPLACEMENTS).forEach(key => {
for (const key of Object.keys(REPLACEMENTS)) {
const info = REPLACEMENTS[key];
parser.hooks.expression.for(key).tap(PLUGIN_NAME, expression => {
const dep = toConstantDependency(parser, info.expr, info.req);
@@ -237,7 +238,7 @@ class APIPlugin {
.for(key)
.tap(PLUGIN_NAME, evaluateToString(info.type));
}
});
}
parser.hooks.expression
.for("__webpack_layer__")
@@ -277,7 +278,7 @@ class APIPlugin {
(parser.state.module.buildInfo).moduleConcatenationBailout =
"__webpack_module__.id";
const dep = new ConstDependency(
parser.state.module.moduleArgument + ".id",
`${parser.state.module.moduleArgument}.id`,
/** @type {Range} */ (expr.range),
[RuntimeGlobals.moduleId]
);

View File

@@ -13,18 +13,22 @@ const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
* @returns {string} message
*/
function createMessage(method) {
return `Abstract method${method ? " " + method : ""}. Must be overridden.`;
return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`;
}
/**
* @constructor
*/
function Message() {
/** @type {string} */
/** @type {string | undefined} */
this.stack = undefined;
Error.captureStackTrace(this);
/** @type {RegExpMatchArray} */
const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP);
/** @type {RegExpMatchArray | null} */
const match =
/** @type {string} */
(/** @type {unknown} */ (this.stack))
.split("\n")[3]
.match(CURRENT_METHOD_REGEXP);
this.message = match && match[1] ? createMessage(match[1]) : createMessage();
}
@@ -32,12 +36,13 @@ function Message() {
/**
* Error for abstract method
* @example
* ```js
* class FooClass {
* abstractMethod() {
* throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden.
* }
* }
*
* ```
*/
class AbstractMethodError extends WebpackError {
constructor() {

View File

@@ -39,7 +39,7 @@ class AsyncDependenciesBlock extends DependenciesBlock {
}
/**
* @returns {string | undefined} The name of the chunk
* @returns {string | null | undefined} The name of the chunk
*/
get chunkName() {
return this.groupOptions.name;

View File

@@ -45,7 +45,7 @@ class AutomaticPrefetchPlugin {
"AutomaticPrefetchPlugin",
(compilation, callback) => {
if (!lastModules) return callback();
asyncLib.forEach(
asyncLib.each(
lastModules,
(m, callback) => {
compilation.addModuleChain(

View File

@@ -14,10 +14,13 @@ const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerFunction} BannerFunction */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
const validate = createSchemaValidation(
require("../schemas/plugins/BannerPlugin.check.js"),
/** @type {(function(typeof import("../schemas/plugins/BannerPlugin.json")): boolean)} */
(require("../schemas/plugins/BannerPlugin.check.js")),
() => require("../schemas/plugins/BannerPlugin.json"),
{
name: "Banner Plugin",
@@ -59,6 +62,7 @@ class BannerPlugin {
const bannerOption = options.banner;
if (typeof bannerOption === "function") {
const getBanner = bannerOption;
/** @type {BannerFunction} */
this.banner = this.options.raw
? getBanner
: /** @type {BannerFunction} */ data => wrapComment(getBanner(data));
@@ -66,6 +70,7 @@ class BannerPlugin {
const banner = this.options.raw
? bannerOption
: wrapComment(bannerOption);
/** @type {BannerFunction} */
this.banner = () => banner;
}
}
@@ -103,15 +108,17 @@ class BannerPlugin {
continue;
}
const data = {
chunk,
filename: file
};
/** @type {PathData} */
const data = { chunk, filename: file };
const comment = compilation.getPath(banner, data);
const comment = compilation.getPath(
/** @type {TemplatePath} */
(banner),
data
);
compilation.updateAsset(file, old => {
let cached = cache.get(old);
const cached = cache.get(old);
if (!cached || cached.comment !== comment) {
const source = options.footer
? new ConcatSource(old, "\n", comment)

18
node_modules/webpack/lib/Cache.js generated vendored
View File

@@ -38,16 +38,14 @@ const {
* @param {function(Error=): void} callback callback
* @returns {function(Error=): void} callback
*/
const needCalls = (times, callback) => {
return err => {
if (--times === 0) {
return callback(err);
}
if (err && times > 0) {
times = 0;
return callback(err);
}
};
const needCalls = (times, callback) => err => {
if (--times === 0) {
return callback(err);
}
if (err && times > 0) {
times = 0;
return callback(err);
}
};
class Cache {

View File

@@ -38,6 +38,7 @@ class MultiItemCache {
*/
constructor(items) {
this._items = items;
// eslint-disable-next-line no-constructor-return
if (items.length === 1) return /** @type {any} */ (items[0]);
}
@@ -59,12 +60,11 @@ class MultiItemCache {
* @param {number} i index
* @returns {Promise<T>} promise with the data
*/
const next = i => {
return this._items[i].getPromise().then(result => {
const next = i =>
this._items[i].getPromise().then(result => {
if (result !== undefined) return result;
if (++i < this._items.length) return next(i);
});
};
return next(0);
}

View File

@@ -14,8 +14,8 @@ const WebpackError = require("./WebpackError");
* @param {Module[]} modules the modules to be sorted
* @returns {Module[]} sorted version of original modules
*/
const sortModules = modules => {
return modules.sort((a, b) => {
const sortModules = modules =>
modules.sort((a, b) => {
const aIdent = a.identifier();
const bIdent = b.identifier();
/* istanbul ignore next */
@@ -25,20 +25,19 @@ const sortModules = modules => {
/* istanbul ignore next */
return 0;
});
};
/**
* @param {Module[]} modules each module from throw
* @param {ModuleGraph} moduleGraph the module graph
* @returns {string} each message from provided modules
*/
const createModulesListMessage = (modules, moduleGraph) => {
return modules
const createModulesListMessage = (modules, moduleGraph) =>
modules
.map(m => {
let message = `* ${m.identifier()}`;
const validReasons = Array.from(
moduleGraph.getIncomingConnectionsByOriginModule(m).keys()
).filter(x => x);
).filter(Boolean);
if (validReasons.length > 0) {
message += `\n Used by ${validReasons.length} module(s), i. e.`;
@@ -49,7 +48,6 @@ const createModulesListMessage = (modules, moduleGraph) => {
return message;
})
.join("\n");
};
class CaseSensitiveModulesWarning extends WebpackError {
/**

55
node_modules/webpack/lib/Chunk.js generated vendored
View File

@@ -22,14 +22,15 @@ const { mergeRuntime } = require("./util/runtime");
/** @typedef {import("./ChunkGraph").ChunkFilterPredicate} ChunkFilterPredicate */
/** @typedef {import("./ChunkGraph").ChunkSizeOptions} ChunkSizeOptions */
/** @typedef {import("./ChunkGraph").ModuleFilterPredicate} ModuleFilterPredicate */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
@@ -81,9 +82,9 @@ class Chunk {
this.idNameHints = new SortableSet();
/** @type {boolean} */
this.preventIntegration = false;
/** @type {(string | function(PathData, AssetInfo=): string) | undefined} */
/** @type {TemplatePath | undefined} */
this.filenameTemplate = undefined;
/** @type {(string | function(PathData, AssetInfo=): string) | undefined} */
/** @type {TemplatePath | undefined} */
this.cssFilenameTemplate = undefined;
/**
* @private
@@ -124,11 +125,11 @@ class Chunk {
return undefined;
} else if (entryModules.length === 1) {
return entryModules[0];
} else {
throw new Error(
"Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API)"
);
}
throw new Error(
"Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API)"
);
}
/**
@@ -271,9 +272,9 @@ class Chunk {
if (chunkGraph.canChunksBeIntegrated(this, otherChunk)) {
chunkGraph.integrateChunks(this, otherChunk);
return true;
} else {
return false;
}
return false;
}
/**
@@ -367,7 +368,9 @@ class Chunk {
array = [];
chunkModuleIdMap[/** @type {ChunkId} */ (asyncChunk.id)] = array;
}
const moduleId = chunkGraph.getModuleId(module);
const moduleId =
/** @type {ModuleId} */
(chunkGraph.getModuleId(module));
array.push(moduleId);
chunkModuleHashMap[moduleId] = chunkGraph.getRenderedModuleHash(
module,
@@ -766,7 +769,7 @@ class Chunk {
});
}
}
if (list.length === 0) return undefined;
if (list.length === 0) return;
list.sort((a, b) => {
const cmp =
/** @type {number} */ (b.order) - /** @type {number} */ (a.order);
@@ -836,6 +839,36 @@ class Chunk {
return chunkMaps;
}
/**
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {string} type option name
* @param {boolean=} includeDirectChildren include direct children (by default only children of async children are included)
* @param {ChunkFilterPredicate=} filterFn function used to filter chunks
* @returns {boolean} true when the child is of type order, otherwise false
*/
hasChildByOrder(chunkGraph, type, includeDirectChildren, filterFn) {
if (includeDirectChildren) {
/** @type {Set<Chunk>} */
const chunks = new Set();
for (const chunkGroup of this.groupsIterable) {
for (const chunk of chunkGroup.chunks) {
chunks.add(chunk);
}
}
for (const chunk of chunks) {
const data = chunk.getChildIdsByOrders(chunkGraph, filterFn);
if (data[type] !== undefined) return true;
}
}
for (const chunk of this.getAllAsyncChunks()) {
const data = chunk.getChildIdsByOrders(chunkGraph, filterFn);
if (data[type] !== undefined) return true;
}
return false;
}
}
module.exports = Chunk;

View File

@@ -30,8 +30,11 @@ const {
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./RuntimeModule")} RuntimeModule */
@@ -73,9 +76,7 @@ class ModuleHashInfo {
* @param {SortableSet<T>} set the set
* @returns {T[]} set as array
*/
const getArray = set => {
return Array.from(set);
};
const getArray = set => Array.from(set);
/**
* @param {SortableSet<Chunk>} chunks the chunks
@@ -120,7 +121,10 @@ const modulesBySourceType = sourceTypesByModule => set => {
};
const defaultModulesBySourceType = modulesBySourceType(undefined);
/** @type {WeakMap<Function, any>} */
/**
* @template T
* @type {WeakMap<Function, any>}
*/
const createOrderedArrayFunctionMap = new WeakMap();
/**
@@ -159,7 +163,7 @@ const getModulesSize = modules => {
* @returns {Record<string, number>} the sizes of the modules
*/
const getModulesSizes = modules => {
let sizes = Object.create(null);
const sizes = Object.create(null);
for (const module of modules) {
for (const type of module.getSourceTypes()) {
sizes[type] = (sizes[type] || 0) + module.size(type);
@@ -199,7 +203,7 @@ class ChunkGraphModule {
this.runtimeInChunks = undefined;
/** @type {RuntimeSpecMap<ModuleHashInfo> | undefined} */
this.hashes = undefined;
/** @type {string | number} */
/** @type {ModuleId | null} */
this.id = null;
/** @type {RuntimeSpecMap<Set<string>> | undefined} */
this.runtimeRequirements = undefined;
@@ -625,7 +629,7 @@ class ChunkGraph {
/**
* @param {Chunk} chunk chunk
* @param {Module} module chunk module
* @returns {Set<string>} source types
* @returns {SourceTypes} source types
*/
getChunkModuleSourceTypes(chunk, module) {
const cgc = this._getChunkGraphChunk(chunk);
@@ -637,7 +641,7 @@ class ChunkGraph {
/**
* @param {Module} module module
* @returns {Set<string>} source types
* @returns {SourceTypes} source types
*/
getModuleSourceTypes(module) {
return (
@@ -702,7 +706,7 @@ class ChunkGraph {
const modulesWithSourceType = cgc.modules
.getFromUnorderedCache(cgc._modulesBySourceType)
.get(sourceType);
if (modulesWithSourceType === undefined) return undefined;
if (modulesWithSourceType === undefined) return;
modulesWithSourceType.sortWith(comparator);
return modulesWithSourceType;
}
@@ -749,9 +753,9 @@ class ChunkGraph {
if (filterFn(module)) {
if (array === undefined) {
array = [];
chunkModuleIdMap[asyncChunk.id] = array;
chunkModuleIdMap[/** @type {ChunkId} */ (asyncChunk.id)] = array;
}
const moduleId = this.getModuleId(module);
const moduleId = /** @type {ModuleId} */ (this.getModuleId(module));
array.push(moduleId);
}
}
@@ -773,13 +777,15 @@ class ChunkGraph {
hashLength = 0,
includeAllChunks = false
) {
/** @type {Record<string|number, Record<string|number, string>>} */
/** @type {Record<ChunkId, Record<string|number, string>>} */
const chunkModuleHashMap = Object.create(null);
/** @typedef {Record<string|number, string>} IdToHashMap */
for (const asyncChunk of includeAllChunks
? chunk.getAllReferencedChunks()
: chunk.getAllAsyncChunks()) {
/** @type {Record<string|number, string> | undefined} */
/** @type {IdToHashMap | undefined} */
let idToHashMap;
for (const module of this.getOrderedChunkModulesIterable(
asyncChunk,
@@ -788,11 +794,15 @@ class ChunkGraph {
if (filterFn(module)) {
if (idToHashMap === undefined) {
idToHashMap = Object.create(null);
chunkModuleHashMap[asyncChunk.id] = idToHashMap;
chunkModuleHashMap[/** @type {ChunkId} */ (asyncChunk.id)] =
/** @type {IdToHashMap} */ (idToHashMap);
}
const moduleId = this.getModuleId(module);
const hash = this.getRenderedModuleHash(module, asyncChunk.runtime);
idToHashMap[moduleId] = hashLength ? hash.slice(0, hashLength) : hash;
/** @type {IdToHashMap} */
(idToHashMap)[/** @type {ModuleId} */ (moduleId)] = hashLength
? hash.slice(0, hashLength)
: hash;
}
}
}
@@ -808,7 +818,7 @@ class ChunkGraph {
getChunkConditionMap(chunk, filterFn) {
const map = Object.create(null);
for (const c of chunk.getAllReferencedChunks()) {
map[c.id] = filterFn(c, this);
map[/** @type {ChunkId} */ (c.id)] = filterFn(c, this);
}
return map;
}
@@ -916,7 +926,7 @@ class ChunkGraph {
const cgcB = this._getChunkGraphChunk(chunkB);
const allModules = new Set(cgcA.modules);
for (const m of cgcB.modules) allModules.add(m);
let modulesSize = getModulesSize(allModules);
const modulesSize = getModulesSize(allModules);
const chunkOverhead =
typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000;
const entryChunkMultiplicator =
@@ -950,9 +960,9 @@ class ChunkGraph {
return isAvailableChunk(chunkA, chunkB);
} else if (hasRuntimeB) {
return isAvailableChunk(chunkB, chunkA);
} else {
return false;
}
return false;
}
if (
@@ -1011,7 +1021,12 @@ class ChunkGraph {
this.getChunkEntryModulesWithChunkGroupIterable(chunkB)
)) {
this.disconnectChunkAndEntryModule(chunkB, module);
this.connectChunkAndEntryModule(chunkA, module, chunkGroup);
this.connectChunkAndEntryModule(
chunkA,
module,
/** @type {Entrypoint} */
(chunkGroup)
);
}
for (const chunkGroup of chunkB.groupsIterable) {
@@ -1052,7 +1067,7 @@ class ChunkGraph {
/**
* @param {Chunk} chunk the new chunk
* @param {Module} module the entry module
* @param {Entrypoint=} entrypoint the chunk group which must be loaded before the module is executed
* @param {Entrypoint} entrypoint the chunk group which must be loaded before the module is executed
* @returns {void}
*/
connectChunkAndEntryModule(chunk, module, entrypoint) {
@@ -1111,8 +1126,9 @@ class ChunkGraph {
disconnectChunkAndEntryModule(chunk, module) {
const cgm = this._getChunkGraphModule(module);
const cgc = this._getChunkGraphChunk(chunk);
cgm.entryInChunks.delete(chunk);
if (cgm.entryInChunks.size === 0) {
/** @type {EntryInChunks} */
(cgm.entryInChunks).delete(chunk);
if (/** @type {EntryInChunks} */ (cgm.entryInChunks).size === 0) {
cgm.entryInChunks = undefined;
}
cgc.entryModules.delete(module);
@@ -1126,8 +1142,9 @@ class ChunkGraph {
disconnectChunkAndRuntimeModule(chunk, module) {
const cgm = this._getChunkGraphModule(module);
const cgc = this._getChunkGraphChunk(chunk);
cgm.runtimeInChunks.delete(chunk);
if (cgm.runtimeInChunks.size === 0) {
/** @type {RuntimeInChunks} */
(cgm.runtimeInChunks).delete(chunk);
if (/** @type {RuntimeInChunks} */ (cgm.runtimeInChunks).size === 0) {
cgm.runtimeInChunks = undefined;
}
cgc.runtimeModules.delete(module);
@@ -1154,8 +1171,9 @@ class ChunkGraph {
const cgc = this._getChunkGraphChunk(chunk);
for (const module of cgc.entryModules.keys()) {
const cgm = this._getChunkGraphModule(module);
cgm.entryInChunks.delete(chunk);
if (cgm.entryInChunks.size === 0) {
/** @type {EntryInChunks} */
(cgm.entryInChunks).delete(chunk);
if (/** @type {EntryInChunks} */ (cgm.entryInChunks).size === 0) {
cgm.entryInChunks = undefined;
}
}
@@ -1322,7 +1340,7 @@ class ChunkGraph {
/**
* @param {Module} module the module
* @returns {ModuleId} the id of the module
* @returns {ModuleId | null} the id of the module
*/
getModuleId(module) {
const cgm = this._getChunkGraphModule(module);
@@ -1344,7 +1362,7 @@ class ChunkGraph {
* @returns {string | number} the id of the runtime
*/
getRuntimeId(runtime) {
return this._runtimeIds.get(runtime);
return /** @type {string | number} */ (this._runtimeIds.get(runtime));
}
/**
@@ -1474,10 +1492,10 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
} else if (!transferOwnership || runtimeRequirements.size >= items.size) {
for (const item of items) runtimeRequirements.add(item);
return runtimeRequirements;
} else {
for (const item of runtimeRequirements) items.add(item);
return items;
}
for (const item of runtimeRequirements) items.add(item);
return items;
});
}
@@ -1513,7 +1531,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime the runtime
* @returns {ReadonlySet<string>} runtime requirements
* @returns {ReadOnlyRuntimeRequirements} runtime requirements
*/
getModuleRuntimeRequirements(module, runtime) {
const cgm = this._getChunkGraphModule(module);
@@ -1524,7 +1542,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Chunk} chunk the chunk
* @returns {ReadonlySet<string>} runtime requirements
* @returns {ReadOnlyRuntimeRequirements} runtime requirements
*/
getChunkRuntimeRequirements(chunk) {
const cgc = this._getChunkGraphChunk(chunk);
@@ -1593,6 +1611,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
if (cgm.graphHashesWithConnections === undefined) {
cgm.graphHashesWithConnections = new RuntimeSpecMap();
}
/**
* @param {ConnectionState} state state
* @returns {"F" | "T" | "O"} result
@@ -1615,6 +1634,10 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
const activeNamespaceModules = new Set();
/** @type {Map<string, Module | Set<Module>>} */
const connectedModules = new Map();
/**
* @param {ModuleGraphConnection} connection connection
* @param {string} stateInfo state info
*/
const processConnection = (connection, stateInfo) => {
const module = connection.module;
stateInfo += module.getExportsType(this.moduleGraph, strict);
@@ -1696,7 +1719,9 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
hash.update(xor.toString(16));
};
if (activeNamespaceModules.size === 1)
addModuleToHash(activeNamespaceModules.values().next().value);
addModuleToHash(
/** @type {Module} */ (activeNamespaceModules.values().next().value)
);
else if (activeNamespaceModules.size > 1)
addModulesToHash(activeNamespaceModules);
for (const [stateInfo, modules] of connectedModulesInOrder) {
@@ -1714,7 +1739,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Chunk} chunk the chunk
* @returns {ReadonlySet<string>} runtime requirements
* @returns {ReadOnlyRuntimeRequirements} runtime requirements
*/
getTreeRuntimeRequirements(chunk) {
const cgc = this._getChunkGraphChunk(chunk);
@@ -1740,12 +1765,13 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
const chunkGraph = chunkGraphForModuleMap.get(module);
if (!chunkGraph)
throw new Error(
deprecateMessage +
": There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)"
`${
deprecateMessage
}: There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)`
);
return chunkGraph;
},
deprecateMessage + ": Use new ChunkGraph API",
`${deprecateMessage}: Use new ChunkGraph API`,
deprecationCode
);
deprecateGetChunkGraphForModuleMap.set(deprecateMessage, newFn);
@@ -1790,12 +1816,13 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
const chunkGraph = chunkGraphForChunkMap.get(chunk);
if (!chunkGraph)
throw new Error(
deprecateMessage +
"There was no ChunkGraph assigned to the Chunk for backward-compat (Use the new API)"
`${
deprecateMessage
}There was no ChunkGraph assigned to the Chunk for backward-compat (Use the new API)`
);
return chunkGraph;
},
deprecateMessage + ": Use new ChunkGraph API",
`${deprecateMessage}: Use new ChunkGraph API`,
deprecationCode
);
deprecateGetChunkGraphForChunkMap.set(deprecateMessage, newFn);

View File

@@ -22,7 +22,7 @@ const {
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {{id: number}} HasId */
/** @typedef {{module: Module, loc: DependencyLocation, request: string}} OriginRecord */
/** @typedef {{module: Module | null, loc: DependencyLocation, request: string}} OriginRecord */
/**
* @typedef {object} RawChunkGroupOptions
@@ -31,7 +31,7 @@ const {
* @property {("low" | "high" | "auto")=} fetchPriority
*/
/** @typedef {RawChunkGroupOptions & { name?: string }} ChunkGroupOptions */
/** @typedef {RawChunkGroupOptions & { name?: string | null }} ChunkGroupOptions */
let debugId = 5000;
@@ -137,7 +137,7 @@ class ChunkGroup {
/**
* returns the name of current ChunkGroup
* @returns {string | undefined} returns the ChunkGroup name
* @returns {string | null | undefined} returns the ChunkGroup name
*/
get name() {
return this.options.name;
@@ -404,7 +404,7 @@ class ChunkGroup {
}
/**
* @param {Module} module origin module
* @param {Module | null} module origin module
* @param {DependencyLocation} loc location of the reference in the origin module
* @param {string} request request name of the reference
* @returns {void}
@@ -478,7 +478,6 @@ class ChunkGroup {
/**
* Sorting predicate which allows current ChunkGroup to be compared against another.
* Sorting values are based off of number of chunks in ChunkGroup.
*
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {ChunkGroup} otherGroup the chunkGroup to compare this against
* @returns {-1|0|1} sort position for comparison

View File

@@ -8,8 +8,21 @@
const util = require("util");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").ChunkHashContext} ChunkHashContext */
/** @typedef {import("./Compilation").Hash} Hash */
/** @typedef {import("./Compilation").RenderManifestEntry} RenderManifestEntry */
/** @typedef {import("./Compilation").RenderManifestOptions} RenderManifestOptions */
/** @typedef {import("./Compilation").Source} Source */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
/**
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
@@ -26,6 +39,11 @@ class ChunkTemplate {
this.hooks = Object.freeze({
renderManifest: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(RenderManifestEntry[], RenderManifestOptions): RenderManifestEntry[]} fn function
*/
(options, fn) => {
compilation.hooks.renderManifest.tap(
options,
@@ -41,6 +59,11 @@ class ChunkTemplate {
},
modules: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, ModuleTemplate, RenderContext): Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -58,6 +81,11 @@ class ChunkTemplate {
},
render: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, ModuleTemplate, RenderContext): Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -75,6 +103,11 @@ class ChunkTemplate {
},
renderWithEntry: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Chunk): Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -96,6 +129,11 @@ class ChunkTemplate {
},
hash: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash): void} fn function
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
@@ -105,6 +143,11 @@ class ChunkTemplate {
},
hashForChunk: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash, Chunk, ChunkHashContext): void} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)

View File

@@ -7,7 +7,7 @@
const asyncLib = require("neo-async");
const { SyncBailHook } = require("tapable");
const Compilation = require("../lib/Compilation");
const Compilation = require("./Compilation");
const createSchemaValidation = require("./util/create-schema-validation");
const { join } = require("./util/fs");
const processAsyncTree = require("./util/processAsyncTree");
@@ -25,7 +25,13 @@ const processAsyncTree = require("./util/processAsyncTree");
/**
* @typedef {object} CleanPluginCompilationHooks
* @property {SyncBailHook<[string], boolean>} keep when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config
* @property {SyncBailHook<[string], boolean | void>} keep when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config
*/
/**
* @callback KeepFn
* @param {string} path path
* @returns {boolean | void} true, if the path should be kept
*/
const validate = createSchemaValidation(
@@ -143,7 +149,7 @@ const doStat = (fs, filename, callback) => {
* @param {boolean} dry only log instead of fs modification
* @param {Logger} logger logger
* @param {Set<string>} diff filenames of the assets that shouldn't be there
* @param {function(string): boolean} isKept check if the entry is ignored
* @param {function(string): boolean | void} isKept check if the entry is ignored
* @param {function(Error=, Assets=): void} callback callback
* @returns {void}
*/
@@ -304,7 +310,6 @@ class CleanPlugin {
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
/** @type {SyncBailHook<[string], boolean>} */
keep: new SyncBailHook(["ignore"])
};
compilationHooksMap.set(compilation, hooks);
@@ -326,21 +331,14 @@ class CleanPlugin {
apply(compiler) {
const { dry, keep } = this.options;
/** @type {KeepFn} */
const keepFn =
typeof keep === "function"
? keep
: typeof keep === "string"
? /**
* @param {string} path path
* @returns {boolean} true, if the path should be kept
*/
path => path.startsWith(keep)
? path => path.startsWith(keep)
: typeof keep === "object" && keep.test
? /**
* @param {string} path path
* @returns {boolean} true, if the path should be kept
*/
path => keep.test(path)
? path => keep.test(path)
: () => false;
// We assume that no external modification happens while the compiler is active
@@ -394,7 +392,7 @@ class CleanPlugin {
/**
* @param {string} path path
* @returns {boolean} true, if needs to be kept
* @returns {boolean | void} true, if needs to be kept
*/
const isKept = path => {
const result = hooks.keep.call(path);

View File

@@ -13,6 +13,7 @@ const { runtimeToString, RuntimeSpecMap } = require("./util/runtime");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {typeof import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
@@ -53,9 +54,9 @@ class CodeGenerationResults {
Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").`
);
}
return first(results);
return /** @type {CodeGenerationResult} */ (first(results));
}
return entry.values().next().value;
return /** @type {CodeGenerationResult} */ (entry.values().next().value);
}
const result = entry.get(runtime);
if (result === undefined) {
@@ -86,9 +87,8 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
} else if (entry.size > 1) {
const results = new Set(entry.values());
return results.size === 1;
} else {
return entry.size === 1;
}
return entry.size === 1;
}
/**
@@ -98,13 +98,15 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
* @returns {Source} a source
*/
getSource(module, runtime, sourceType) {
return this.get(module, runtime).sources.get(sourceType);
return /** @type {Source} */ (
this.get(module, runtime).sources.get(sourceType)
);
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {ReadonlySet<string>} runtime requirements
* @returns {ReadOnlyRuntimeRequirements | null} runtime requirements
*/
getRuntimeRequirements(module, runtime) {
return this.get(module, runtime).runtimeRequirements;

View File

@@ -12,7 +12,6 @@ const makeSerializable = require("./util/makeSerializable");
class CommentCompilationWarning extends WebpackError {
/**
*
* @param {string} message warning message
* @param {DependencyLocation} loc affected lines of code
*/

File diff suppressed because it is too large Load Diff

171
node_modules/webpack/lib/Compiler.js generated vendored
View File

@@ -14,7 +14,7 @@ const {
AsyncSeriesHook
} = require("tapable");
const { SizeOnlySource } = require("webpack-sources");
const webpack = require("./");
const webpack = require(".");
const Cache = require("./Cache");
const CacheFacade = require("./CacheFacade");
const ChunkGraph = require("./ChunkGraph");
@@ -47,13 +47,18 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./config/target").PlatformTargetProperties} PlatformTargetProperties */
/** @typedef {import("./logging/createConsoleLogger").LoggingFunction} LoggingFunction */
/** @typedef {import("./util/WeakTupleMap")} WeakTupleMap */
/** @typedef {import("./util/fs").IStats} IStats */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
/**
* @template {any[]} T
* @template V
* @typedef {import("./util/WeakTupleMap")<T, V>} WeakTupleMap
*/
/**
* @typedef {object} CompilationParams
* @property {NormalModuleFactory} normalModuleFactory
@@ -93,6 +98,8 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {{ sizeOnlySource: SizeOnlySource | undefined, writtenTo: Map<string, number> }} CacheEntry */
/** @typedef {{ path: string, source: Source, size: number | undefined, waiting: ({ cacheEntry: any, file: string }[] | undefined) }} SimilarEntry */
/** @typedef {{ buildInfo: BuildInfo, references: References | undefined, memCache: WeakTupleMap<any, any> }} ModuleMemCachesItem */
/**
* @param {string[]} array an array
* @returns {boolean} true, if the array is sorted
@@ -127,9 +134,8 @@ const includesHash = (filename, hashes) => {
if (!hashes) return false;
if (Array.isArray(hashes)) {
return hashes.some(hash => filename.includes(hash));
} else {
return filename.includes(hashes);
}
return filename.includes(hashes);
};
class Compiler {
@@ -142,7 +148,7 @@ class Compiler {
/** @type {SyncHook<[]>} */
initialize: new SyncHook([]),
/** @type {SyncBailHook<[Compilation], boolean | undefined>} */
/** @type {SyncBailHook<[Compilation], boolean | void>} */
shouldEmit: new SyncBailHook(["compilation"]),
/** @type {AsyncSeriesHook<[Stats]>} */
done: new AsyncSeriesHook(["stats"]),
@@ -197,7 +203,7 @@ class Compiler {
/** @type {AsyncSeriesHook<[]>} */
shutdown: new AsyncSeriesHook([]),
/** @type {SyncBailHook<[string, string, any[]], true>} */
/** @type {SyncBailHook<[string, string, any[] | undefined], true | void>} */
infrastructureLog: new SyncBailHook(["origin", "type", "args"]),
// TODO the following hooks are weirdly located here
@@ -210,7 +216,7 @@ class Compiler {
afterPlugins: new SyncHook(["compiler"]),
/** @type {SyncHook<[Compiler]>} */
afterResolvers: new SyncHook(["compiler"]),
/** @type {SyncBailHook<[string, Entry], boolean>} */
/** @type {SyncBailHook<[string, Entry], boolean | void>} */
entryOption: new SyncBailHook(["context", "entry"])
});
@@ -284,7 +290,7 @@ class Compiler {
this.cache = new Cache();
/** @type {Map<Module, { buildInfo: BuildInfo, references: References | undefined, memCache: WeakTupleMap }> | undefined} */
/** @type {Map<Module, ModuleMemCachesItem> | undefined} */
this.moduleMemCaches = undefined;
this.compilerPath = "";
@@ -354,10 +360,11 @@ class Compiler {
);
}
}
if (this.hooks.infrastructureLog.call(name, type, args) === undefined) {
if (this.infrastructureLogger !== undefined) {
this.infrastructureLogger(name, type, args);
}
if (
this.hooks.infrastructureLog.call(name, type, args) === undefined &&
this.infrastructureLogger !== undefined
) {
this.infrastructureLogger(name, type, args);
}
},
childName => {
@@ -382,36 +389,33 @@ class Compiler {
}
return `${name}/${childName}`;
});
} else {
return this.getInfrastructureLogger(() => {
if (typeof name === "function") {
name = name();
if (!name) {
throw new TypeError(
"Compiler.getInfrastructureLogger(name) called with a function not returning a name"
);
}
}
return `${name}/${childName}`;
});
}
} else {
if (typeof childName === "function") {
return this.getInfrastructureLogger(() => {
if (typeof childName === "function") {
childName = childName();
if (!childName) {
throw new TypeError(
"Logger.getChildLogger(name) called with a function not returning a name"
);
}
return this.getInfrastructureLogger(() => {
if (typeof name === "function") {
name = name();
if (!name) {
throw new TypeError(
"Compiler.getInfrastructureLogger(name) called with a function not returning a name"
);
}
return `${name}/${childName}`;
});
} else {
return this.getInfrastructureLogger(`${name}/${childName}`);
}
}
return `${name}/${childName}`;
});
}
if (typeof childName === "function") {
return this.getInfrastructureLogger(() => {
if (typeof childName === "function") {
childName = childName();
if (!childName) {
throw new TypeError(
"Logger.getChildLogger(name) called with a function not returning a name"
);
}
}
return `${name}/${childName}`;
});
}
return this.getInfrastructureLogger(`${name}/${childName}`);
}
);
}
@@ -623,11 +627,11 @@ class Compiler {
const finalCallback = (err, entries, compilation) => {
try {
callback(err, entries, compilation);
} catch (e) {
} catch (runAsChildErr) {
const err = new WebpackError(
`compiler.runAsChild callback error: ${e}`
`compiler.runAsChild callback error: ${runAsChildErr}`
);
err.details = /** @type {Error} */ (e).stack;
err.details = /** @type {Error} */ (runAsChildErr).stack;
/** @type {Compilation} */
(this.parentCompilation).errors.push(err);
}
@@ -765,18 +769,17 @@ ${other}`);
callback(err);
}
return true;
} else {
caseInsensitiveMap.set(
caseInsensitiveTargetPath,
(similarEntry = /** @type {SimilarEntry} */ ({
path: targetPath,
source,
size: undefined,
waiting: undefined
}))
);
return false;
}
caseInsensitiveMap.set(
caseInsensitiveTargetPath,
(similarEntry = /** @type {SimilarEntry} */ ({
path: targetPath,
source,
size: undefined,
waiting: undefined
}))
);
return false;
};
/**
@@ -786,14 +789,12 @@ ${other}`);
const getContent = () => {
if (typeof source.buffer === "function") {
return source.buffer();
} else {
const bufferOrString = source.source();
if (Buffer.isBuffer(bufferOrString)) {
return bufferOrString;
} else {
return Buffer.from(bufferOrString, "utf8");
}
}
const bufferOrString = source.source();
if (Buffer.isBuffer(bufferOrString)) {
return bufferOrString;
}
return Buffer.from(bufferOrString, "utf8");
};
const alreadyWritten = () => {
@@ -917,9 +918,8 @@ ${other}`);
!content.equals(/** @type {Buffer} */ (existingContent))
) {
return doWrite(content);
} else {
return alreadyWritten();
}
return alreadyWritten();
});
}
@@ -956,10 +956,9 @@ ${other}`);
});
return callback();
} else {
// Settings immutable will make it accept file content without comparing when file exist
immutable = true;
}
// Settings immutable will make it accept file content without comparing when file exist
immutable = true;
} else if (!immutable) {
if (checkSimilarFile()) return;
// We wrote to this file before which has very likely a different content
@@ -986,7 +985,7 @@ ${other}`);
}
};
if (targetFile.match(/\/|\\/)) {
if (/\/|\\/.test(targetFile)) {
const fs = /** @type {OutputFileSystem} */ (this.outputFileSystem);
const dir = dirname(fs, join(fs, outputPath, targetFile));
mkdirp(fs, dir, writeOut);
@@ -1041,12 +1040,10 @@ ${other}`);
} else {
this.hooks.emitRecords.callAsync(callback);
}
} else if (this.recordsOutputPath) {
this._emitRecords(callback);
} else {
if (this.recordsOutputPath) {
this._emitRecords(callback);
} else {
callback();
}
callback();
}
}
@@ -1115,13 +1112,11 @@ ${other}`);
this.records = {};
this.hooks.readRecords.callAsync(callback);
}
} else if (this.recordsInputPath) {
this._readRecords(callback);
} else {
if (this.recordsInputPath) {
this._readRecords(callback);
} else {
this.records = {};
callback();
}
this.records = {};
callback();
}
}
@@ -1150,10 +1145,10 @@ ${other}`);
this.records = parseJson(
/** @type {Buffer} */ (content).toString("utf-8")
);
} catch (e) {
} catch (parseErr) {
return callback(
new Error(
`Cannot parse records: ${/** @type {Error} */ (e).message}`
`Cannot parse records: ${/** @type {Error} */ (parseErr).message}`
)
);
}
@@ -1168,7 +1163,7 @@ ${other}`);
* @param {Compilation} compilation the compilation
* @param {string} compilerName the compiler's name
* @param {number} compilerIndex the compiler's index
* @param {OutputOptions=} outputOptions the output options
* @param {Partial<OutputOptions>=} outputOptions the output options
* @param {WebpackPluginInstance[]=} plugins the plugins to apply
* @returns {Compiler} a child compiler
*/
@@ -1233,11 +1228,17 @@ ${other}`);
"invalid",
"done",
"thisCompilation"
].includes(name)
].includes(name) &&
childCompiler.hooks[/** @type {keyof Compiler["hooks"]} */ (name)]
) {
if (childCompiler.hooks[name]) {
childCompiler.hooks[name].taps = this.hooks[name].taps.slice();
}
childCompiler.hooks[
/** @type {keyof Compiler["hooks"]} */
(name)
].taps =
this.hooks[
/** @type {keyof Compiler["hooks"]} */
(name)
].taps.slice();
}
}
@@ -1251,7 +1252,7 @@ ${other}`);
}
isChild() {
return !!this.parentCompilation;
return Boolean(this.parentCompilation);
}
/**

View File

@@ -5,31 +5,18 @@
"use strict";
const {
DEFAULT_EXPORT,
NAMESPACE_OBJECT_EXPORT
} = require("./util/concatenate");
/** @typedef {import("./Module")} Module */
/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */
/** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */
const MODULE_REFERENCE_REGEXP =
/^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(?:_asiSafe(\d))?__$/;
const DEFAULT_EXPORT = "__WEBPACK_DEFAULT_EXPORT__";
const NAMESPACE_OBJECT_EXPORT = "__WEBPACK_NAMESPACE_OBJECT__";
/**
* @typedef {object} ExternalModuleInfo
* @property {number} index
* @property {Module} module
*/
/**
* @typedef {object} ConcatenatedModuleInfo
* @property {number} index
* @property {Module} module
* @property {Map<string, string>} exportMap mapping from export name to symbol
* @property {Map<string, string>} rawExportMap mapping from export name to symbol
* @property {string=} namespaceExportSymbol
*/
/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */
/**
* @typedef {object} ModuleReferenceOptions
* @property {string[]} ids the properties/exports of the module
@@ -64,7 +51,6 @@ class ConcatenationScope {
}
/**
*
* @param {string} exportName name of the export
* @param {string} symbol identifier of the export in source code
*/
@@ -78,7 +64,6 @@ class ConcatenationScope {
}
/**
*
* @param {string} exportName name of the export
* @param {string} expression expression to be used
*/
@@ -99,7 +84,6 @@ class ConcatenationScope {
}
/**
*
* @param {Module} module the referenced module
* @param {Partial<ModuleReferenceOptions>} options options
* @returns {string} the reference as identifier
@@ -138,7 +122,7 @@ class ConcatenationScope {
static matchModuleReference(name) {
const match = MODULE_REFERENCE_REGEXP.exec(name);
if (!match) return null;
const index = +match[1];
const index = Number(match[1]);
const asiSafe = match[5];
return {
index,
@@ -146,8 +130,8 @@ class ConcatenationScope {
match[2] === "ns"
? []
: JSON.parse(Buffer.from(match[2], "hex").toString("utf-8")),
call: !!match[3],
directImport: !!match[4],
call: Boolean(match[3]),
directImport: Boolean(match[4]),
asiSafe: asiSafe ? asiSafe === "1" : undefined
};
}

View File

@@ -27,13 +27,12 @@ const wrapInCondition = (condition, source) => {
"}",
""
]);
} else {
return new ConcatSource(
`if (${condition}) {\n`,
new PrefixSource("\t", source),
"}\n"
);
}
return new ConcatSource(
`if (${condition}) {\n`,
new PrefixSource("\t", source),
"}\n"
);
};
/**
@@ -54,7 +53,7 @@ class ConditionalInitFragment extends InitFragment {
position,
key,
runtimeCondition = true,
endContent
endContent = undefined
) {
super(content, stage, position, key, endContent);
this.runtimeCondition = runtimeCondition;

View File

@@ -207,21 +207,13 @@ class ConstPlugin {
// NOTE: When code runs in strict mode, `var` declarations
// are hoisted but `function` declarations don't.
//
let declarations;
if (parser.scope.isStrict) {
// If the code runs in strict mode, variable declarations
// using `var` must be hoisted.
declarations = getHoistedDeclarations(branchToRemove, false);
} else {
// Otherwise, collect all hoisted declaration.
declarations = getHoistedDeclarations(branchToRemove, true);
}
let replacement;
if (declarations.length > 0) {
replacement = `{ var ${declarations.join(", ")}; }`;
} else {
replacement = "{}";
}
const declarations = parser.scope.isStrict
? getHoistedDeclarations(branchToRemove, false)
: getHoistedDeclarations(branchToRemove, true);
const replacement =
declarations.length > 0
? `{ var ${declarations.join(", ")}; }`
: "{}";
const dep = new ConstDependency(
replacement,
/** @type {Range} */ (branchToRemove.range)

View File

@@ -22,9 +22,9 @@ class ContextExclusionPlugin {
*/
apply(compiler) {
compiler.hooks.contextModuleFactory.tap("ContextExclusionPlugin", cmf => {
cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files => {
return files.filter(filePath => !this.negativeMatcher.test(filePath));
});
cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files =>
files.filter(filePath => !this.negativeMatcher.test(filePath))
);
});
}
}

View File

@@ -9,6 +9,7 @@ const { OriginalSource, RawSource } = require("webpack-sources");
const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
const { makeWebpackError } = require("./HookWebpackError");
const Module = require("./Module");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const Template = require("./Template");
@@ -30,19 +31,20 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
@@ -61,11 +63,11 @@ const makeSerializable = require("./util/makeSerializable");
* @property {ContextMode} mode
* @property {boolean} recursive
* @property {RegExp} regExp
* @property {"strict"|boolean=} namespaceObject
* @property {("strict" | boolean)=} namespaceObject
* @property {string=} addon
* @property {string=} chunkName
* @property {RegExp=} include
* @property {RegExp=} exclude
* @property {(string | null)=} chunkName
* @property {(RegExp | null)=} include
* @property {(RegExp | null)=} exclude
* @property {RawChunkGroupOptions=} groupOptions
* @property {string=} typePrefix
* @property {string=} category
@@ -86,7 +88,7 @@ const makeSerializable = require("./util/makeSerializable");
/**
* @callback ResolveDependenciesCallback
* @param {(Error | null)=} err
* @param {Error | null} err
* @param {ContextElementDependency[]=} dependencies
*/
@@ -99,12 +101,10 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {1 | 3 | 7 | 9} FakeMapType */
/** @typedef {Map<string, string | number> | FakeMapType} FakeMap */
/** @typedef {Record<ModuleId, FakeMapType>} FakeMap */
const SNAPSHOT_OPTIONS = { timestamp: true };
const TYPES = new Set(["javascript"]);
class ContextModule extends Module {
/**
* @param {ResolveDependencies} resolveDependencies function to get dependencies in this context
@@ -159,7 +159,7 @@ class ContextModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
return JS_TYPES;
}
/**
@@ -192,7 +192,7 @@ class ContextModule extends Module {
_prettyRegExp(regexString, stripSlash = true) {
const str = stripSlash
? regexString.source + regexString.flags
: regexString + "";
: `${regexString}`;
return str.replace(/!/g, "%21").replace(/\|/g, "%7C");
}
@@ -272,15 +272,15 @@ class ContextModule extends Module {
readableIdentifier(requestShortener) {
let identifier;
if (this.context) {
identifier = requestShortener.shorten(this.context) + "/";
identifier = `${requestShortener.shorten(this.context)}/`;
} else if (
typeof this.options.resource === "string" ||
this.options.resource === false
) {
identifier = requestShortener.shorten(`${this.options.resource}`) + "/";
identifier = `${requestShortener.shorten(`${this.options.resource}`)}/`;
} else {
identifier = this.options.resource
.map(r => requestShortener.shorten(r) + "/")
.map(r => `${requestShortener.shorten(r)}/`)
.join(" ");
}
if (this.options.resourceQuery) {
@@ -565,7 +565,7 @@ class ContextModule extends Module {
} else if (typeof this.options.resource === "string") {
contextDependencies.add(this.options.resource);
} else if (this.options.resource === false) {
return;
// Do nothing
} else {
for (const res of this.options.resource) contextDependencies.add(res);
}
@@ -602,7 +602,7 @@ class ContextModule extends Module {
/**
* @param {Dependency[]} dependencies all dependencies
* @param {ChunkGraph} chunkGraph chunk graph
* @returns {FakeMap} fake map
* @returns {FakeMap | FakeMapType} fake map
*/
getFakeMap(dependencies, chunkGraph) {
if (!this.options.namespaceObject) {
@@ -621,13 +621,14 @@ class ContextModule extends Module {
)
.filter(Boolean)
.sort(comparator);
/** @type {FakeMap} */
const fakeMap = Object.create(null);
for (const module of sortedModules) {
const exportsType = module.getExportsType(
moduleGraph,
this.options.namespaceObject === "strict"
);
const id = chunkGraph.getModuleId(module);
const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
switch (exportsType) {
case "namespace":
fakeMap[id] = 9;
@@ -668,7 +669,7 @@ class ContextModule extends Module {
}
/**
* @param {FakeMap} fakeMap fake map
* @param {FakeMap | FakeMapType} fakeMap fake map
* @returns {string} fake map init statement
*/
getFakeMapInitStatement(fakeMap) {
@@ -692,7 +693,7 @@ class ContextModule extends Module {
}
/**
* @param {FakeMap} fakeMap fake map
* @param {FakeMap | FakeMapType} fakeMap fake map
* @param {boolean=} asyncModule us async module
* @param {string=} fakeMapDataExpression fake map data expression
* @returns {string} module object source
@@ -944,15 +945,19 @@ module.exports = webpackAsyncContext;`;
chunkGraph
);
const hasFakeMap = typeof fakeMap === "object";
/** @typedef {{userRequest: string, dependency: ContextElementDependency, chunks: undefined | Chunk[], module: Module, block: AsyncDependenciesBlock}} Item */
/**
* @type {Item[]}
*/
const items = blocks
.map(block => {
const dependency =
/** @type {ContextElementDependency} */
(block.dependencies[0]);
return {
dependency: dependency,
dependency,
module: /** @type {Module} */ (moduleGraph.getModule(dependency)),
block: block,
block,
userRequest: dependency.userRequest,
chunks: undefined
};
@@ -974,18 +979,23 @@ module.exports = webpackAsyncContext;`;
if (a.userRequest === b.userRequest) return 0;
return a.userRequest < b.userRequest ? -1 : 1;
});
/** @type {Record<string, ModuleId | (ModuleId[] | ChunkId[])>} */
const map = Object.create(null);
for (const item of sortedItems) {
const moduleId = chunkGraph.getModuleId(item.module);
const moduleId =
/** @type {ModuleId} */
(chunkGraph.getModuleId(item.module));
if (shortMode) {
map[item.userRequest] = moduleId;
} else {
/** @type {(ModuleId | ChunkId)[]} */
const arrayStart = [moduleId];
if (hasFakeMap) {
arrayStart.push(fakeMap[moduleId]);
}
map[item.userRequest] = arrayStart.concat(
item.chunks.map(chunk => chunk.id)
/** @type {Chunk[]} */
(item.chunks).map(chunk => /** @type {ChunkId} */ (chunk.id))
);
}
}
@@ -1086,7 +1096,7 @@ module.exports = webpackEmptyAsyncContext;`;
* @returns {string} the source code
*/
getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) {
const id = chunkGraph.getModuleId(this);
const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this));
if (asyncMode === "lazy") {
if (this.blocks && this.blocks.length > 0) {
return this.getLazySource(this.blocks, id, {
@@ -1124,10 +1134,12 @@ module.exports = webpackEmptyAsyncContext;`;
}
return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
}
if (asyncMode === "weak") {
if (this.dependencies && this.dependencies.length > 0) {
return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
}
if (
asyncMode === "weak" &&
this.dependencies &&
this.dependencies.length > 0
) {
return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
}
if (this.dependencies && this.dependencies.length > 0) {
return this.getSyncSource(this.dependencies, id, chunkGraph);

View File

@@ -22,8 +22,14 @@ const { join } = require("./util/fs");
/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./ResolverFactory")} ResolverFactory */
/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
/** @template T @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T> */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/**
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
*/
/** @typedef {import("./util/fs").IStats} IStats */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {{ context: string, request: string }} ContextAlternativeRequest */
const EMPTY_RESOLVE_OPTIONS = {};
@@ -33,7 +39,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
*/
constructor(resolverFactory) {
super();
/** @type {AsyncSeriesWaterfallHook<[TODO[], ContextModuleOptions]>} */
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[], ContextModuleOptions]>} */
const alternativeRequests = new AsyncSeriesWaterfallHook([
"modules",
"options"
@@ -45,27 +51,27 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
afterResolve: new AsyncSeriesWaterfallHook(["data"]),
/** @type {SyncWaterfallHook<[string[]]>} */
contextModuleFiles: new SyncWaterfallHook(["files"]),
/** @type {FakeHook<Pick<AsyncSeriesWaterfallHook<[TODO[]]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
/** @type {FakeHook<Pick<AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
alternatives: createFakeHook(
{
name: "alternatives",
/** @type {AsyncSeriesWaterfallHook<[TODO[]]>["intercept"]} */
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["intercept"]} */
intercept: interceptor => {
throw new Error(
"Intercepting fake hook ContextModuleFactory.hooks.alternatives is not possible, use ContextModuleFactory.hooks.alternativeRequests instead"
);
},
/** @type {AsyncSeriesWaterfallHook<[TODO[]]>["tap"]} */
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tap"]} */
tap: (options, fn) => {
alternativeRequests.tap(options, fn);
},
/** @type {AsyncSeriesWaterfallHook<[TODO[]]>["tapAsync"]} */
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapAsync"]} */
tapAsync: (options, fn) => {
alternativeRequests.tapAsync(options, (items, _options, callback) =>
fn(items, callback)
);
},
/** @type {AsyncSeriesWaterfallHook<[TODO[]]>["tapPromise"]} */
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapPromise"]} */
tapPromise: (options, fn) => {
alternativeRequests.tapPromise(options, fn);
}
@@ -93,8 +99,8 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
const contextDependencies = new LazySet();
this.hooks.beforeResolve.callAsync(
{
context: context,
dependencies: dependencies,
context,
dependencies,
layer: data.contextInfo.issuerLayer,
resolveOptions,
fileDependencies,
@@ -124,9 +130,9 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
const request = beforeResolveResult.request;
const resolveOptions = beforeResolveResult.resolveOptions;
let loaders,
resource,
loadersPrefix = "";
let loaders;
let resource;
let loadersPrefix = "";
const idx = request.lastIndexOf("!");
if (idx >= 0) {
let loadersRequest = request.slice(0, idx + 1);
@@ -142,11 +148,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
.slice(i)
.replace(/!+$/, "")
.replace(/!!+/g, "!");
if (loadersRequest === "") {
loaders = [];
} else {
loaders = loadersRequest.split("!");
}
loaders = loadersRequest === "" ? [] : loadersRequest.split("!");
resource = request.slice(idx + 1);
} else {
loaders = [];
@@ -168,8 +170,14 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
asyncLib.parallel(
[
callback => {
const results = [];
const yield_ = obj => results.push(obj);
const results = /** @type ResolveRequest[] */ ([]);
/**
* @param {ResolveRequest} obj obj
* @returns {void}
*/
const yield_ = obj => {
results.push(obj);
};
contextResolver.resolve(
{},
@@ -202,7 +210,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
},
(err, result) => {
if (err) return callback(err);
callback(null, result);
callback(null, /** @type {string} */ (result));
}
);
},
@@ -218,7 +226,8 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
contextDependencies
});
}
let [contextResult, loaderResult] = result;
let [contextResult, loaderResult] =
/** @type {[ResolveRequest[], string[]]} */ (result);
if (contextResult.length > 1) {
const first = contextResult[0];
contextResult = contextResult.filter(r => r.path);
@@ -294,10 +303,19 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
} = options;
if (!regExp || !resource) return callback(null, []);
/**
* @param {string} ctx context
* @param {string} directory directory
* @param {Set<string>} visited visited
* @param {ResolveDependenciesCallback} callback callback
*/
const addDirectoryChecked = (ctx, directory, visited, callback) => {
fs.realpath(directory, (err, realPath) => {
/** @type {NonNullable<InputFileSystem["realpath"]>} */
(fs.realpath)(directory, (err, _realPath) => {
if (err) return callback(err);
const realPath = /** @type {string} */ (_realPath);
if (visited.has(realPath)) return callback(null, []);
/** @type {Set<string> | undefined} */
let recursionStack;
addDirectory(
ctx,
@@ -314,6 +332,12 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
});
};
/**
* @param {string} ctx context
* @param {string} directory directory
* @param {function(string, string, function(): void): void} addSubDirectory addSubDirectoryFn
* @param {ResolveDependenciesCallback} callback callback
*/
const addDirectory = (ctx, directory, addSubDirectory, callback) => {
fs.readdir(directory, (err, files) => {
if (err) return callback(err);
@@ -328,17 +352,18 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
const subResource = join(fs, directory, segment);
if (!exclude || !subResource.match(exclude)) {
fs.stat(subResource, (err, stat) => {
fs.stat(subResource, (err, _stat) => {
if (err) {
if (err.code === "ENOENT") {
// ENOENT is ok here because the file may have been deleted between
// the readdir and stat calls.
return callback();
} else {
return callback(err);
}
return callback(err);
}
const stat = /** @type {IStats} */ (_stat);
if (stat.isDirectory()) {
if (!recursive) return callback();
addSubDirectory(ctx, subResource, callback);
@@ -346,10 +371,10 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
stat.isFile() &&
(!include || subResource.match(include))
) {
/** @type {{ context: string, request: string }} */
const obj = {
context: ctx,
request:
"." + subResource.slice(ctx.length).replace(/\\/g, "/")
request: `.${subResource.slice(ctx.length).replace(/\\/g, "/")}`
};
this.hooks.alternativeRequests.callAsync(
@@ -357,22 +382,29 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
options,
(err, alternatives) => {
if (err) return callback(err);
alternatives = alternatives
.filter(obj => regExp.test(obj.request))
.map(obj => {
const dep = new ContextElementDependency(
`${obj.request}${resourceQuery}${resourceFragment}`,
obj.request,
typePrefix,
category,
referencedExports,
obj.context,
attributes
);
dep.optional = true;
return dep;
});
callback(null, alternatives);
callback(
null,
/** @type {ContextAlternativeRequest[]} */
(alternatives)
.filter(obj =>
regExp.test(/** @type {string} */ (obj.request))
)
.map(obj => {
const dep = new ContextElementDependency(
`${obj.request}${resourceQuery}${resourceFragment}`,
obj.request,
typePrefix,
/** @type {string} */
(category),
referencedExports,
/** @type {TODO} */
(obj.context),
attributes
);
dep.optional = true;
return dep;
})
);
}
);
} else {
@@ -400,9 +432,19 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
});
};
/**
* @param {string} ctx context
* @param {string} dir dir
* @param {ResolveDependenciesCallback} callback callback
* @returns {void}
*/
const addSubDirectory = (ctx, dir, callback) =>
addDirectory(ctx, dir, addSubDirectory, callback);
/**
* @param {string} resource resource
* @param {ResolveDependenciesCallback} callback callback
*/
const visitResource = (resource, callback) => {
if (typeof fs.realpath === "function") {
addDirectoryChecked(resource, resource, new Set(), callback);
@@ -414,12 +456,15 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
if (typeof resource === "string") {
visitResource(resource, callback);
} else {
asyncLib.map(resource, visitResource, (err, result) => {
asyncLib.map(resource, visitResource, (err, _result) => {
if (err) return callback(err);
const result = /** @type {ContextElementDependency[][]} */ (_result);
// result dependencies should have unique userRequest
// ordered by resolve result
/** @type {Set<string>} */
const temp = new Set();
/** @type {ContextElementDependency[]} */
const res = [];
for (let i = 0; i < result.length; i++) {
const inner = result[i];

View File

@@ -16,7 +16,7 @@ class ContextReplacementPlugin {
* @param {RegExp} resourceRegExp A regular expression that determines which files will be selected
* @param {TODO=} newContentResource A new resource to replace the match
* @param {TODO=} newContentRecursive If true, all subdirectories are searched for matches
* @param {TODO=} newContentRegExp A regular expression that determines which files will be selected
* @param {RegExp=} newContentRegExp A regular expression that determines which files will be selected
*/
constructor(
resourceRegExp,
@@ -154,14 +154,15 @@ const createResolveDependenciesFromContextMap = createContextMap => {
const resolveDependenciesFromContextMap = (fs, options, callback) => {
createContextMap(fs, (err, map) => {
if (err) return callback(err);
const dependencies = Object.keys(map).map(key => {
return new ContextElementDependency(
map[key] + options.resourceQuery + options.resourceFragment,
key,
options.category,
options.referencedExports
);
});
const dependencies = Object.keys(map).map(
key =>
new ContextElementDependency(
map[key] + options.resourceQuery + options.resourceFragment,
key,
options.category,
options.referencedExports
)
);
callback(null, dependencies);
});
};

View File

@@ -1,6 +1,6 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Krasnoyarov @alexander-akait
Author Alexander Akait @alexander-akait
*/
"use strict";
@@ -14,13 +14,13 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {string|undefined} CssLayer */
/** @typedef {string|undefined} Supports */
/** @typedef {string|undefined} Media */
/** @typedef {[CssLayer?, Supports?, Media?]} InheritanceItem */
/** @typedef {string | undefined} CssLayer */
/** @typedef {string | undefined} Supports */
/** @typedef {string | undefined} Media */
/** @typedef {[CssLayer, Supports, Media]} InheritanceItem */
/** @typedef {Array<InheritanceItem>} Inheritance */
/** @typedef {NormalModuleCreateData & { cssLayer: CssLayer|null, supports: Supports|null, media: Media|null, inheritance: Inheritance|null }} CSSModuleCreateData */
/** @typedef {NormalModuleCreateData & { cssLayer: CssLayer, supports: Supports, media: Media, inheritance: Inheritance }} CSSModuleCreateData */
class CssModule extends NormalModule {
/**
@@ -127,30 +127,34 @@ class CssModule extends NormalModule {
static deserialize(context) {
const obj = new CssModule({
// will be deserialized by Module
layer: null,
layer: /** @type {EXPECTED_ANY} */ (null),
type: "",
// will be filled by updateCacheModule
resource: "",
context: "",
request: null,
userRequest: null,
rawRequest: null,
loaders: null,
matchResource: null,
parser: null,
parserOptions: null,
generator: null,
generatorOptions: null,
resolveOptions: null,
cssLayer: null,
supports: null,
media: null,
inheritance: null
request: /** @type {EXPECTED_ANY} */ (null),
userRequest: /** @type {EXPECTED_ANY} */ (null),
rawRequest: /** @type {EXPECTED_ANY} */ (null),
loaders: /** @type {EXPECTED_ANY} */ (null),
matchResource: /** @type {EXPECTED_ANY} */ (null),
parser: /** @type {EXPECTED_ANY} */ (null),
parserOptions: /** @type {EXPECTED_ANY} */ (null),
generator: /** @type {EXPECTED_ANY} */ (null),
generatorOptions: /** @type {EXPECTED_ANY} */ (null),
resolveOptions: /** @type {EXPECTED_ANY} */ (null),
cssLayer: /** @type {EXPECTED_ANY} */ (null),
supports: /** @type {EXPECTED_ANY} */ (null),
media: /** @type {EXPECTED_ANY} */ (null),
inheritance: /** @type {EXPECTED_ANY} */ (null)
});
obj.deserialize(context);
return obj;
}
/**
* @param {ObjectDeserializerContext} context context
* @returns {TODO} Module
*/
deserialize(context) {
const { read } = context;
this.cssLayer = read();

View File

@@ -24,12 +24,14 @@ const createHash = require("./util/createHash");
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/createHash").Algorithm} Algorithm */
/** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */
/** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive|RuntimeValue>} CodeValue */
@@ -43,9 +45,12 @@ const createHash = require("./util/createHash");
* @property {string|function(): string=} version
*/
/** @typedef {string | Set<string>} ValueCacheVersion */
/** @typedef {function({ module: NormalModule, key: string, readonly version: ValueCacheVersion }): CodeValuePrimitive} GeneratorFn */
class RuntimeValue {
/**
* @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function
* @param {GeneratorFn} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
*/
constructor(fn, options) {
@@ -64,7 +69,7 @@ class RuntimeValue {
/**
* @param {JavascriptParser} parser the parser
* @param {Map<string, string | Set<string>>} valueCacheVersions valueCacheVersions
* @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @returns {CodeValuePrimitive} code
*/
@@ -75,22 +80,26 @@ class RuntimeValue {
} else {
if (this.options.fileDependencies) {
for (const dep of this.options.fileDependencies) {
buildInfo.fileDependencies.add(dep);
/** @type {NonNullable<BuildInfo["fileDependencies"]>} */
(buildInfo.fileDependencies).add(dep);
}
}
if (this.options.contextDependencies) {
for (const dep of this.options.contextDependencies) {
buildInfo.contextDependencies.add(dep);
/** @type {NonNullable<BuildInfo["contextDependencies"]>} */
(buildInfo.contextDependencies).add(dep);
}
}
if (this.options.missingDependencies) {
for (const dep of this.options.missingDependencies) {
buildInfo.missingDependencies.add(dep);
/** @type {NonNullable<BuildInfo["missingDependencies"]>} */
(buildInfo.missingDependencies).add(dep);
}
}
if (this.options.buildDependencies) {
for (const dep of this.options.buildDependencies) {
buildInfo.buildDependencies.add(dep);
/** @type {NonNullable<BuildInfo["buildDependencies"]>} */
(buildInfo.buildDependencies).add(dep);
}
}
}
@@ -99,7 +108,7 @@ class RuntimeValue {
module: parser.state.module,
key,
get version() {
return /** @type {string} */ (
return /** @type {ValueCacheVersion} */ (
valueCacheVersions.get(VALUE_DEP_PREFIX + key)
);
}
@@ -120,19 +129,22 @@ class RuntimeValue {
* @returns {Set<string> | undefined} used keys
*/
function getObjKeys(properties) {
if (!properties) return undefined;
if (!properties) return;
return new Set([...properties].map(p => p.id));
}
/** @typedef {Set<string> | null} ObjKeys */
/** @typedef {boolean | undefined | null} AsiSafe */
/**
* @param {any[]|{[k: string]: any}} obj obj
* @param {JavascriptParser} parser Parser
* @param {Map<string, string | Set<string>>} valueCacheVersions valueCacheVersions
* @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Logger} logger the logger object
* @param {boolean|undefined|null=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {Set<string>|undefined=} objKeys used keys
* @param {AsiSafe=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {ObjKeys=} objKeys used keys
* @returns {string} code converted to string that evaluates
*/
const stringifyObj = (
@@ -146,7 +158,7 @@ const stringifyObj = (
objKeys
) => {
let code;
let arr = Array.isArray(obj);
const arr = Array.isArray(obj);
if (arr) {
code = `[${
/** @type {any[]} */ (obj)
@@ -166,25 +178,20 @@ const stringifyObj = (
} else {
let keys = Object.keys(obj);
if (objKeys) {
if (objKeys.size === 0) keys = [];
else keys = keys.filter(k => objKeys.has(k));
keys = objKeys.size === 0 ? [] : keys.filter(k => objKeys.has(k));
}
code = `{${keys
.map(key => {
const code = /** @type {{[k: string]: any}} */ (obj)[key];
return (
JSON.stringify(key) +
":" +
toCode(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)
);
return `${JSON.stringify(key)}:${toCode(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)}`;
})
.join(",")}}`;
}
@@ -205,12 +212,12 @@ const stringifyObj = (
* Convert code to a string that evaluates
* @param {CodeValue} code Code to evaluate
* @param {JavascriptParser} parser Parser
* @param {Map<string, string | Set<string>>} valueCacheVersions valueCacheVersions
* @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Logger} logger the logger object
* @param {boolean|undefined|null=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {Set<string>|undefined=} objKeys used keys
* @param {boolean | undefined | null=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {ObjKeys=} objKeys used keys
* @returns {string} code converted to string that evaluates
*/
const toCode = (
@@ -248,7 +255,7 @@ const toCode = (
return code.toString();
}
if (typeof code === "function" && code.toString) {
return "(" + code.toString() + ")";
return `(${code.toString()})`;
}
if (typeof code === "object") {
return stringifyObj(
@@ -267,7 +274,7 @@ const toCode = (
? `${code}n`
: `BigInt("${code}")`;
}
return code + "";
return `${code}`;
};
const strCode = transformToCode();
@@ -298,20 +305,20 @@ const toCacheVersion = code => {
return code.toString();
}
if (typeof code === "function" && code.toString) {
return "(" + code.toString() + ")";
return `(${code.toString()})`;
}
if (typeof code === "object") {
const items = Object.keys(code).map(key => ({
key,
value: toCacheVersion(/** @type {Record<string, any>} */ (code)[key])
}));
if (items.some(({ value }) => value === undefined)) return undefined;
if (items.some(({ value }) => value === undefined)) return;
return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
}
if (typeof code === "bigint") {
return `${code}n`;
}
return code + "";
return `${code}`;
};
const PLUGIN_NAME = "DefinePlugin";
@@ -333,7 +340,7 @@ class DefinePlugin {
}
/**
* @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function
* @param {GeneratorFn} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
* @returns {RuntimeValue} runtime value
*/
@@ -358,11 +365,13 @@ class DefinePlugin {
);
const { runtimeTemplate } = compilation;
const mainHash = createHash(compilation.outputOptions.hashFunction);
const mainHash = createHash(
/** @type {Algorithm} */
(compilation.outputOptions.hashFunction)
);
mainHash.update(
/** @type {string} */ (
compilation.valueCacheVersions.get(VALUE_DEP_MAIN)
) || ""
/** @type {string} */
(compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
);
/**
@@ -371,7 +380,9 @@ class DefinePlugin {
* @returns {void}
*/
const handler = parser => {
const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN);
const mainValue =
/** @type {ValueCacheVersion} */
(compilation.valueCacheVersions.get(VALUE_DEP_MAIN));
parser.hooks.program.tap(PLUGIN_NAME, () => {
const buildInfo = /** @type {BuildInfo} */ (
parser.state.module.buildInfo
@@ -385,15 +396,23 @@ class DefinePlugin {
* @param {string} key key
*/
const addValueDependency = key => {
const buildInfo = /** @type {BuildInfo} */ (
parser.state.module.buildInfo
);
buildInfo.valueDependencies.set(
const buildInfo =
/** @type {BuildInfo} */
(parser.state.module.buildInfo);
/** @type {NonNullable<BuildInfo["valueDependencies"]>} */
(buildInfo.valueDependencies).set(
VALUE_DEP_PREFIX + key,
compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
/** @type {ValueCacheVersion} */
(compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key))
);
};
/**
* @template {Function} T
* @param {string} key key
* @param {T} fn fn
* @returns {function(TODO): TODO} result
*/
const withValueDependency =
(key, fn) =>
(...args) => {
@@ -408,7 +427,7 @@ class DefinePlugin {
* @returns {void}
*/
const walkDefinitions = (definitions, prefix) => {
Object.keys(definitions).forEach(key => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
if (
code &&
@@ -418,14 +437,14 @@ class DefinePlugin {
) {
walkDefinitions(
/** @type {Record<string, CodeValue>} */ (code),
prefix + key + "."
`${prefix + key}.`
);
applyObjectDefine(prefix + key, code);
return;
continue;
}
applyDefineKey(prefix, key);
applyDefine(prefix + key, code);
});
}
};
/**
@@ -436,13 +455,13 @@ class DefinePlugin {
*/
const applyDefineKey = (prefix, key) => {
const splittedKey = key.split(".");
splittedKey.slice(1).forEach((_, i) => {
for (const [i, _] of splittedKey.slice(1).entries()) {
const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
addValueDependency(key);
return true;
});
});
}
};
/**
@@ -505,7 +524,7 @@ class DefinePlugin {
);
if (parser.scope.inShorthand) {
strCode = parser.scope.inShorthand + ":" + strCode;
strCode = `${parser.scope.inShorthand}:${strCode}`;
}
if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
@@ -516,9 +535,8 @@ class DefinePlugin {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
} else {
return toConstantDependency(parser, strCode)(expr);
}
return toConstantDependency(parser, strCode)(expr);
});
}
parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, expr => {
@@ -542,9 +560,7 @@ class DefinePlugin {
logger,
null
);
const typeofCode = isTypeof
? codeCode
: "typeof (" + codeCode + ")";
const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
const res = parser.evaluate(typeofCode);
recurseTypeof = false;
res.setRange(/** @type {Range} */ (expr.range));
@@ -561,9 +577,7 @@ class DefinePlugin {
logger,
null
);
const typeofCode = isTypeof
? codeCode
: "typeof (" + codeCode + ")";
const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
const res = parser.evaluate(typeofCode);
if (!res.isString()) return;
return toConstantDependency(
@@ -611,7 +625,7 @@ class DefinePlugin {
);
if (parser.scope.inShorthand) {
strCode = parser.scope.inShorthand + ":" + strCode;
strCode = `${parser.scope.inShorthand}:${strCode}`;
}
if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
@@ -622,9 +636,8 @@ class DefinePlugin {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
} else {
return toConstantDependency(parser, strCode)(expr);
}
return toConstantDependency(parser, strCode)(expr);
});
parser.hooks.typeof
.for(key)
@@ -657,11 +670,11 @@ class DefinePlugin {
* @returns {void}
*/
const walkDefinitionsForValues = (definitions, prefix) => {
Object.keys(definitions).forEach(key => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
const version = toCacheVersion(code);
const version = /** @type {string} */ (toCacheVersion(code));
const name = VALUE_DEP_PREFIX + prefix + key;
mainHash.update("|" + prefix + key);
mainHash.update(`|${prefix}${key}`);
const oldVersion = compilation.valueCacheVersions.get(name);
if (oldVersion === undefined) {
compilation.valueCacheVersions.set(name, version);
@@ -681,10 +694,10 @@ class DefinePlugin {
) {
walkDefinitionsForValues(
/** @type {Record<string, CodeValue>} */ (code),
prefix + key + "."
`${prefix + key}.`
);
}
});
}
};
walkDefinitionsForValues(definitions, "");

View File

@@ -7,6 +7,7 @@
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
@@ -19,13 +20,13 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceContext} SourceContext */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
@@ -36,7 +37,10 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const TYPES = new Set(["javascript"]);
/** @typedef {string} SourceRequest */
/** @typedef {"require" | "object"} Type */
/** @typedef {TODO} Data */
const RUNTIME_REQUIREMENTS = new Set([
RuntimeGlobals.module,
RuntimeGlobals.require
@@ -44,9 +48,9 @@ const RUNTIME_REQUIREMENTS = new Set([
class DelegatedModule extends Module {
/**
* @param {string} sourceRequest source request
* @param {TODO} data data
* @param {"require" | "object"} type type
* @param {SourceRequest} sourceRequest source request
* @param {Data} data data
* @param {Type} type type
* @param {string} userRequest user request
* @param {string | Module} originalRequest original request
*/
@@ -70,7 +74,7 @@ class DelegatedModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
return JS_TYPES;
}
/**

View File

@@ -7,15 +7,28 @@
const DelegatedModule = require("./DelegatedModule");
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */
/** @typedef {import("./DelegatedModule").Data} Data */
/** @typedef {import("./DelegatedModule").SourceRequest} SourceRequest */
/** @typedef {import("./DelegatedModule").Type} Type */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
// options.source
// options.type
// options.context
// options.scope
// options.content
// options.associatedObjectForCache
/**
* @typedef {object} Options
* @property {SourceRequest} source source
* @property {NonNullable<DllReferencePluginOptions["context"]>} context absolute context path to which lib ident is relative to
* @property {DllReferencePluginOptionsContent} content content
* @property {DllReferencePluginOptions["type"]} type type
* @property {DllReferencePluginOptions["extensions"]} extensions extensions
* @property {DllReferencePluginOptions["scope"]} scope scope
* @property {object=} associatedObjectForCache object for caching
*/
class DelegatedModuleFactoryPlugin {
/**
* @param {Options} options options
*/
constructor(options) {
this.options = options;
options.type = options.type || "require";
@@ -35,7 +48,7 @@ class DelegatedModuleFactoryPlugin {
const [dependency] = data.dependencies;
const { request } = dependency;
if (request && request.startsWith(`${scope}/`)) {
const innerRequest = "." + request.slice(scope.length);
const innerRequest = `.${request.slice(scope.length)}`;
let resolved;
if (innerRequest in this.options.content) {
resolved = this.options.content[innerRequest];
@@ -44,14 +57,17 @@ class DelegatedModuleFactoryPlugin {
new DelegatedModule(
this.options.source,
resolved,
this.options.type,
/** @type {Type} */ (this.options.type),
innerRequest,
request
)
);
}
for (let i = 0; i < this.options.extensions.length; i++) {
const extension = this.options.extensions[i];
const extensions =
/** @type {string[]} */
(this.options.extensions);
for (let i = 0; i < extensions.length; i++) {
const extension = extensions[i];
const requestPlusExt = innerRequest + extension;
if (requestPlusExt in this.options.content) {
resolved = this.options.content[requestPlusExt];
@@ -60,7 +76,7 @@ class DelegatedModuleFactoryPlugin {
new DelegatedModule(
this.options.source,
resolved,
this.options.type,
/** @type {Type} */ (this.options.type),
requestPlusExt,
request + extension
)
@@ -76,17 +92,15 @@ class DelegatedModuleFactoryPlugin {
"DelegatedModuleFactoryPlugin",
module => {
const request = module.libIdent(this.options);
if (request) {
if (request in this.options.content) {
const resolved = this.options.content[request];
return new DelegatedModule(
this.options.source,
resolved,
this.options.type,
request,
module
);
}
if (request && request in this.options.content) {
const resolved = this.options.content[request];
return new DelegatedModule(
this.options.source,
resolved,
/** @type {Type} */ (this.options.type),
request,
module
);
}
return module;
}

View File

@@ -9,8 +9,12 @@ const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DelegatedModuleFactoryPlugin").Options} Options */
class DelegatedPlugin {
/**
* @param {Options} options options
*/
constructor(options) {
this.options = options;
}

View File

@@ -46,7 +46,6 @@ class DependenciesBlock {
/**
* Adds a DependencyBlock to DependencyBlock relationship.
* This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting)
*
* @param {AsyncDependenciesBlock} block block being added
* @returns {void}
*/

View File

@@ -67,7 +67,7 @@ const memoize = require("./util/memoize");
* @typedef {object} ExportsSpec
* @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports
* @property {Set<string>=} excludeExports when exports = true, list of unaffected exports
* @property {Set<string>=} hideExports list of maybe prior exposed, but now hidden exports
* @property {(Set<string> | null)=} hideExports list of maybe prior exposed, but now hidden exports
* @property {ModuleGraphConnection=} from when reexported: from which module
* @property {number=} priority when reexported: with which priority
* @property {boolean=} canMangle can the export be renamed (defaults to true)
@@ -85,9 +85,9 @@ const memoize = require("./util/memoize");
const TRANSITIVE = Symbol("transitive");
const getIgnoredModule = memoize(() => {
return new RawModule("/* (ignored) */", `ignored`, `(ignored)`);
});
const getIgnoredModule = memoize(
() => new RawModule("/* (ignored) */", "ignored", "(ignored)")
);
class Dependency {
constructor() {
@@ -163,16 +163,8 @@ class Dependency {
this._locEL = 0;
this._locEC = 0;
}
if ("index" in loc) {
this._locI = loc.index;
} else {
this._locI = undefined;
}
if ("name" in loc) {
this._locN = loc.name;
} else {
this._locN = undefined;
}
this._locI = "index" in loc ? loc.index : undefined;
this._locN = "name" in loc ? loc.name : undefined;
this._loc = loc;
}
@@ -336,6 +328,8 @@ Dependency.NO_EXPORTS_REFERENCED = [];
/** @type {string[][]} */
Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
// eslint-disable-next-line no-warning-comments
// @ts-ignore https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Dependency.prototype, "module", {
/**
* @deprecated
@@ -358,6 +352,8 @@ Object.defineProperty(Dependency.prototype, "module", {
}
});
// eslint-disable-next-line no-warning-comments
// @ts-ignore https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Dependency.prototype, "disconnect", {
get() {
throw new Error(

View File

@@ -10,12 +10,14 @@ const DllEntryDependency = require("./dependencies/DllEntryDependency");
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {string[]} Entries */
/** @typedef {{ name: string, filename: TODO }} Options */
class DllEntryPlugin {
/**
* @param {string} context context
* @param {string[]} entries entry names
* @param {TODO} options options
* @param {Entries} entries entry names
* @param {Options} options options
*/
constructor(context, entries, options) {
this.context = context;

View File

@@ -7,6 +7,7 @@
const { RawSource } = require("webpack-sources");
const Module = require("./Module");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const makeSerializable = require("./util/makeSerializable");
@@ -18,11 +19,11 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceContext} SourceContext */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
@@ -32,7 +33,6 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const TYPES = new Set(["javascript"]);
const RUNTIME_REQUIREMENTS = new Set([
RuntimeGlobals.require,
RuntimeGlobals.module
@@ -57,7 +57,7 @@ class DllModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
return JS_TYPES;
}
/**
@@ -165,7 +165,7 @@ class DllModule extends Module {
*/
cleanupForCache() {
super.cleanupForCache();
this.dependencies = undefined;
this.dependencies = /** @type {EXPECTED_ANY} */ (undefined);
}
}

View File

@@ -17,6 +17,7 @@ class DllModuleFactory extends ModuleFactory {
super();
this.hooks = Object.freeze({});
}
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback

View File

@@ -12,6 +12,8 @@ const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DllEntryPlugin").Entries} Entries */
/** @typedef {import("./DllEntryPlugin").Options} Options */
const validate = createSchemaValidation(
require("../schemas/plugins/DllPlugin.check.js"),
@@ -43,13 +45,13 @@ class DllPlugin {
compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => {
if (typeof entry !== "function") {
for (const name of Object.keys(entry)) {
const options = {
name,
filename: entry.filename
};
new DllEntryPlugin(context, entry[name].import, options).apply(
compiler
);
/** @type {Options} */
const options = { name, filename: entry.filename };
new DllEntryPlugin(
context,
/** @type {Entries} */ (entry[name].import),
options
).apply(compiler);
}
} else {
throw new Error(

View File

@@ -15,6 +15,7 @@ const makePathsRelative = require("./util/identifier").makePathsRelative;
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
@@ -28,6 +29,8 @@ const validate = createSchemaValidation(
}
);
/** @typedef {{ path: string, data: DllReferencePluginOptionsManifest | undefined, error: Error | undefined }} CompilationDataItem */
class DllReferencePlugin {
/**
* @param {DllReferencePluginOptions} options options object
@@ -35,7 +38,7 @@ class DllReferencePlugin {
constructor(options) {
validate(options);
this.options = options;
/** @type {WeakMap<object, {path: string, data: DllReferencePluginOptionsManifest?, error: Error?}>} */
/** @type {WeakMap<object, CompilationDataItem>} */
this._compilationData = new WeakMap();
}
@@ -64,6 +67,7 @@ class DllReferencePlugin {
/** @type {InputFileSystem} */
(compiler.inputFileSystem).readFile(manifest, (err, result) => {
if (err) return callback(err);
/** @type {CompilationDataItem} */
const data = {
path: manifest,
data: undefined,
@@ -75,15 +79,18 @@ class DllReferencePlugin {
data.data = parseJson(
/** @type {Buffer} */ (result).toString("utf-8")
);
} catch (e) {
} catch (parseErr) {
// Store the error in the params so that it can
// be added as a compilation error later on.
const manifestPath = makePathsRelative(
compiler.options.context,
/** @type {string} */ (compiler.options.context),
manifest,
compiler.root
);
data.error = new DllManifestError(manifestPath, e.message);
data.error = new DllManifestError(
manifestPath,
/** @type {Error} */ (parseErr).message
);
}
this._compilationData.set(params, data);
return callback();
@@ -98,13 +105,15 @@ class DllReferencePlugin {
compiler.hooks.compile.tap("DllReferencePlugin", params => {
let name = this.options.name;
let sourceType = this.options.sourceType;
let content =
let resolvedContent =
"content" in this.options ? this.options.content : undefined;
if ("manifest" in this.options) {
let manifestParameter = this.options.manifest;
const manifestParameter = this.options.manifest;
let manifest;
if (typeof manifestParameter === "string") {
const data = this._compilationData.get(params);
const data =
/** @type {CompilationDataItem} */
(this._compilationData.get(params));
// If there was an error parsing the manifest
// file, exit now because the error will be added
// as a compilation error in the "compilation" hook.
@@ -118,23 +127,27 @@ class DllReferencePlugin {
if (manifest) {
if (!name) name = manifest.name;
if (!sourceType) sourceType = manifest.type;
if (!content) content = manifest.content;
if (!resolvedContent) resolvedContent = manifest.content;
}
}
/** @type {Externals} */
const externals = {};
const source = "dll-reference " + name;
externals[source] = name;
const source = `dll-reference ${name}`;
externals[source] = /** @type {string} */ (name);
const normalModuleFactory = params.normalModuleFactory;
new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply(
normalModuleFactory
);
new DelegatedModuleFactoryPlugin({
source: source,
source,
type: this.options.type,
scope: this.options.scope,
context: this.options.context || compiler.options.context,
content,
context:
/** @type {string} */
(this.options.context || compiler.options.context),
content:
/** @type {DllReferencePluginOptionsContent} */
(resolvedContent),
extensions: this.options.extensions,
associatedObjectForCache: compiler.root
}).apply(normalModuleFactory);
@@ -144,9 +157,11 @@ class DllReferencePlugin {
"DllReferencePlugin",
(compilation, params) => {
if ("manifest" in this.options) {
let manifest = this.options.manifest;
const manifest = this.options.manifest;
if (typeof manifest === "string") {
const data = this._compilationData.get(params);
const data = /** @type {CompilationDataItem} */ (
this._compilationData.get(params)
);
// If there was an error parsing the manifest file, add the
// error as a compilation error to make the compilation fail.
if (data.error) {

View File

@@ -9,6 +9,7 @@ const EntryOptionPlugin = require("./EntryOptionPlugin");
const EntryPlugin = require("./EntryPlugin");
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */
/** @typedef {import("../declarations/WebpackOptions").EntryDynamicNormalized} EntryDynamic */
/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */
/** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStatic */
@@ -40,22 +41,27 @@ class DynamicEntryPlugin {
}
);
compiler.hooks.make.tapPromise(
"DynamicEntryPlugin",
(compilation, callback) =>
Promise.resolve(this.entry())
.then(entry => {
const promises = [];
for (const name of Object.keys(entry)) {
const desc = entry[name];
const options = EntryOptionPlugin.entryDescriptionToOptions(
compiler,
name,
desc
);
for (const entry of desc.import) {
promises.push(
new Promise((resolve, reject) => {
compiler.hooks.make.tapPromise("DynamicEntryPlugin", compilation =>
Promise.resolve(this.entry())
.then(entry => {
const promises = [];
for (const name of Object.keys(entry)) {
const desc = entry[name];
const options = EntryOptionPlugin.entryDescriptionToOptions(
compiler,
name,
desc
);
for (const entry of /** @type {NonNullable<EntryDescriptionNormalized["import"]>} */ (
desc.import
)) {
promises.push(
new Promise(
/**
* @param {(value?: any) => void} resolve resolve
* @param {(reason?: Error) => void} reject reject
*/
(resolve, reject) => {
compilation.addEntry(
this.context,
EntryPlugin.createDependency(entry, options),
@@ -65,13 +71,14 @@ class DynamicEntryPlugin {
resolve();
}
);
})
);
}
}
)
);
}
return Promise.all(promises);
})
.then(x => {})
}
return Promise.all(promises);
})
.then(x => {})
);
}
}

View File

@@ -12,9 +12,7 @@ const EntryDependency = require("./dependencies/EntryDependency");
class EntryPlugin {
/**
* An entry plugin which will handle
* creation of the EntryDependency
*
* An entry plugin which will handle creation of the EntryDependency
* @param {string} context context path
* @param {string} entry entry path
* @param {EntryOptions | string=} options entry options (passing a string is deprecated)

View File

@@ -12,15 +12,19 @@ const WebpackError = require("./WebpackError");
/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */
class EnvironmentPlugin {
/**
* @param {(string | string[] | Record<string, any>)[]} keys keys
*/
constructor(...keys) {
if (keys.length === 1 && Array.isArray(keys[0])) {
/** @type {string[]} */
this.keys = keys[0];
this.defaultValues = {};
} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
this.keys = Object.keys(keys[0]);
this.defaultValues = keys[0];
this.defaultValues = /** @type {Record<string, any>} */ (keys[0]);
} else {
this.keys = keys;
this.keys = /** @type {string[]} */ (keys);
this.defaultValues = {};
}
}

View File

@@ -48,9 +48,9 @@ const cutOffMultilineMessage = (stack, message) => {
/** @type {string[]} */
const result = [];
stackSplitByLines.forEach((line, idx) => {
for (const [idx, line] of stackSplitByLines.entries()) {
if (!line.includes(messageSplitByLines[idx])) result.push(line);
});
}
return result.join("\n");
};
@@ -64,10 +64,9 @@ const cutOffMessage = (stack, message) => {
const nextLine = stack.indexOf("\n");
if (nextLine === -1) {
return stack === message ? "" : stack;
} else {
const firstLine = stack.slice(0, nextLine);
return firstLine === message ? stack.slice(nextLine + 1) : stack;
}
const firstLine = stack.slice(0, nextLine);
return firstLine === message ? stack.slice(nextLine + 1) : stack;
};
/**
@@ -92,10 +91,10 @@ const cleanUpWebpackOptions = (stack, message) => {
return stack;
};
exports.cutOffByFlag = cutOffByFlag;
exports.cutOffLoaderExecution = cutOffLoaderExecution;
exports.cutOffWebpackOptions = cutOffWebpackOptions;
exports.cutOffMultilineMessage = cutOffMultilineMessage;
exports.cutOffMessage = cutOffMessage;
exports.cleanUp = cleanUp;
exports.cleanUpWebpackOptions = cleanUpWebpackOptions;
module.exports.cutOffByFlag = cutOffByFlag;
module.exports.cutOffLoaderExecution = cutOffLoaderExecution;
module.exports.cutOffWebpackOptions = cutOffWebpackOptions;
module.exports.cutOffMultilineMessage = cutOffMultilineMessage;
module.exports.cutOffMessage = cutOffMessage;
module.exports.cleanUp = cleanUp;
module.exports.cleanUpWebpackOptions = cleanUpWebpackOptions;

View File

@@ -39,7 +39,7 @@ class EvalDevToolModulePlugin {
/**
* @param {EvalDevToolModulePluginOptions=} options options
*/
constructor(options) {
constructor(options = {}) {
this.namespace = options.namespace || "";
this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]";
this.moduleFilenameTemplate =
@@ -57,7 +57,7 @@ class EvalDevToolModulePlugin {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModuleContent.tap(
"EvalDevToolModulePlugin",
(source, module, { runtimeTemplate, chunkGraph }) => {
(source, module, { chunk, runtimeTemplate, chunkGraph }) => {
const cacheEntry = cache.get(source);
if (cacheEntry !== undefined) return cacheEntry;
if (module instanceof ExternalModule) {
@@ -65,11 +65,14 @@ class EvalDevToolModulePlugin {
return source;
}
const content = source.source();
const namespace = compilation.getPath(this.namespace, {
chunk
});
const str = ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: this.moduleFilenameTemplate,
namespace: this.namespace
namespace
},
{
requestShortener: runtimeTemplate.requestShortener,
@@ -77,17 +80,15 @@ class EvalDevToolModulePlugin {
hashFunction: compilation.outputOptions.hashFunction
}
);
const footer =
"\n" +
this.sourceUrlComment.replace(
/\[url\]/g,
encodeURI(str)
.replace(/%2F/g, "/")
.replace(/%20/g, "_")
.replace(/%5E/g, "^")
.replace(/%5C/g, "\\")
.replace(/^\//, "")
);
const footer = `\n${this.sourceUrlComment.replace(
/\[url\]/g,
encodeURI(str)
.replace(/%2F/g, "/")
.replace(/%20/g, "_")
.replace(/%5E/g, "^")
.replace(/%5C/g, "\\")
.replace(/^\//, "")
)}`;
const result = new RawSource(
`eval(${
compilation.outputOptions.trustedTypes

View File

@@ -17,6 +17,7 @@ const { makePathsAbsolute } = require("./util/identifier");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").DevTool} DevToolOptions */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./NormalModule").SourceMap} SourceMap */
@@ -76,7 +77,7 @@ class EvalSourceMapDevToolPlugin {
);
hooks.renderModuleContent.tap(
"EvalSourceMapDevToolPlugin",
(source, m, { runtimeTemplate, chunkGraph }) => {
(source, m, { chunk, runtimeTemplate, chunkGraph }) => {
const cachedSource = cache.get(source);
if (cachedSource !== undefined) {
return cachedSource;
@@ -112,6 +113,9 @@ class EvalSourceMapDevToolPlugin {
return result(source);
}
const namespace = compilation.getPath(this.namespace, {
chunk
});
/** @type {SourceMap} */
let sourceMap;
let content;
@@ -137,20 +141,20 @@ class EvalSourceMapDevToolPlugin {
const module = compilation.findModule(source);
return module || source;
});
let moduleFilenames = modules.map(module => {
return ModuleFilenameHelpers.createFilename(
let moduleFilenames = modules.map(module =>
ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: this.moduleFilenameTemplate,
namespace: this.namespace
namespace
},
{
requestShortener: runtimeTemplate.requestShortener,
chunkGraph,
hashFunction: compilation.outputOptions.hashFunction
}
);
});
)
);
moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(
moduleFilenames,
(filename, i, n) => {
@@ -163,18 +167,19 @@ class EvalSourceMapDevToolPlugin {
sourceMap.sourcesContent = undefined;
}
sourceMap.sourceRoot = options.sourceRoot || "";
const moduleId = chunkGraph.getModuleId(m);
const moduleId =
/** @type {ModuleId} */
(chunkGraph.getModuleId(m));
sourceMap.file =
typeof moduleId === "number" ? `${moduleId}.js` : moduleId;
const footer =
this.sourceMapComment.replace(
/\[url\]/g,
`data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(sourceMap),
"utf8"
).toString("base64")}`
) + `\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug
const footer = `${this.sourceMapComment.replace(
/\[url\]/g,
`data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(sourceMap),
"utf8"
).toString("base64")}`
)}\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug
return result(
new RawSource(

View File

@@ -71,9 +71,12 @@ makeSerializable(
"RestoreProvidedData"
);
/** @typedef {Map<string, ExportInfo>} Exports */
/** @typedef {string | string[] | false} UsedName */
class ExportsInfo {
constructor() {
/** @type {Map<string, ExportInfo>} */
/** @type {Exports} */
this._exports = new Map();
this._otherExportsInfo = new ExportInfo(null);
this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*");
@@ -144,6 +147,10 @@ class ExportsInfo {
return this._otherExportsInfo;
}
/**
* @param {Exports} exports exports
* @private
*/
_sortExportsMap(exports) {
if (exports.size > 1) {
const namesInOrder = [];
@@ -159,7 +166,7 @@ class ExportsInfo {
}
for (; i < namesInOrder.length; i++) {
const name = namesInOrder[i];
const correctEntry = exports.get(name);
const correctEntry = /** @type {ExportInfo} */ (exports.get(name));
exports.delete(name);
exports.set(name, correctEntry);
}
@@ -261,7 +268,7 @@ class ExportsInfo {
getReadOnlyExportInfoRecursive(name) {
const exportInfo = this.getReadOnlyExportInfo(name[0]);
if (name.length === 1) return exportInfo;
if (!exportInfo.exportsInfo) return undefined;
if (!exportInfo.exportsInfo) return;
return exportInfo.exportsInfo.getReadOnlyExportInfoRecursive(name.slice(1));
}
@@ -272,7 +279,7 @@ class ExportsInfo {
getNestedExportsInfo(name) {
if (Array.isArray(name) && name.length > 0) {
const info = this.getReadOnlyExportInfo(name[0]);
if (!info.exportsInfo) return undefined;
if (!info.exportsInfo) return;
return info.exportsInfo.getNestedExportsInfo(name.slice(1));
}
return this;
@@ -451,10 +458,8 @@ class ExportsInfo {
if (this._redirectTo.isUsed(runtime)) {
return true;
}
} else {
if (this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused) {
return true;
}
} else if (this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused) {
return true;
}
for (const exportInfo of this._exports.values()) {
if (exportInfo.getUsed(runtime) !== UsageState.Unused) {
@@ -522,7 +527,7 @@ class ExportsInfo {
return false;
}
}
return new SortableSet(array);
return /** @type {SortableSet<string>} */ (new SortableSet(array));
}
/**
@@ -633,13 +638,11 @@ class ExportsInfo {
isEquallyUsed(runtimeA, runtimeB) {
if (this._redirectTo !== undefined) {
if (!this._redirectTo.isEquallyUsed(runtimeA, runtimeB)) return false;
} else {
if (
this._otherExportsInfo.getUsed(runtimeA) !==
this._otherExportsInfo.getUsed(runtimeB)
) {
return false;
}
} else if (
this._otherExportsInfo.getUsed(runtimeA) !==
this._otherExportsInfo.getUsed(runtimeB)
) {
return false;
}
if (
this._sideEffectsOnlyInfo.getUsed(runtimeA) !==
@@ -662,20 +665,20 @@ class ExportsInfo {
getUsed(name, runtime) {
if (Array.isArray(name)) {
if (name.length === 0) return this.otherExportsInfo.getUsed(runtime);
let info = this.getReadOnlyExportInfo(name[0]);
const info = this.getReadOnlyExportInfo(name[0]);
if (info.exportsInfo && name.length > 1) {
return info.exportsInfo.getUsed(name.slice(1), runtime);
}
return info.getUsed(runtime);
}
let info = this.getReadOnlyExportInfo(name);
const info = this.getReadOnlyExportInfo(name);
return info.getUsed(runtime);
}
/**
* @param {string | string[] | undefined} name the export name
* @param {string | string[]} name the export name
* @param {RuntimeSpec} runtime check usage for this runtime only
* @returns {string | string[] | false} the used name
* @returns {UsedName} the used name
*/
getUsedName(name, runtime) {
if (Array.isArray(name)) {
@@ -684,10 +687,12 @@ class ExportsInfo {
if (!this.isUsed(runtime)) return false;
return name;
}
let info = this.getReadOnlyExportInfo(name[0]);
const info = this.getReadOnlyExportInfo(name[0]);
const x = info.getUsedName(name[0], runtime);
if (x === false) return false;
const arr = x === name[0] && name.length === 1 ? name : [x];
const arr =
/** @type {string[]} */
(x === name[0] && name.length === 1 ? name : [x]);
if (name.length === 1) {
return arr;
}
@@ -698,14 +703,12 @@ class ExportsInfo {
const nested = info.exportsInfo.getUsedName(name.slice(1), runtime);
if (!nested) return false;
return arr.concat(nested);
} else {
return arr.concat(name.slice(1));
}
} else {
let info = this.getReadOnlyExportInfo(name);
const usedName = info.getUsedName(name, runtime);
return usedName;
return arr.concat(name.slice(1));
}
const info = this.getReadOnlyExportInfo(name);
const usedName = info.getUsedName(name, runtime);
return usedName;
}
/**
@@ -738,6 +741,9 @@ class ExportsInfo {
}
}
/**
* @returns {RestoreProvidedData} restore provided data
*/
getRestoreProvidedData() {
const otherProvided = this._otherExportsInfo.provided;
const otherCanMangleProvide = this._otherExportsInfo.canMangleProvide;
@@ -756,7 +762,8 @@ class ExportsInfo {
canMangleProvide: exportInfo.canMangleProvide,
terminalBinding: exportInfo.terminalBinding,
exportsInfo: exportInfo.exportsInfoOwned
? exportInfo.exportsInfo.getRestoreProvidedData()
? /** @type {NonNullable<ExportInfo["exportsInfo"]>} */
(exportInfo.exportsInfo).getRestoreProvidedData()
: undefined
});
}
@@ -802,6 +809,10 @@ class ExportsInfo {
}
}
/** @typedef {{ module: Module, export: string[] }} TargetItemWithoutConnection */
/** @typedef {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} TargetItem */
/** @typedef {Map<any, { connection: ModuleGraphConnection | null, export: string[], priority: number }>} Target */
class ExportInfo {
/**
* @param {string} name the original name of the export
@@ -817,7 +828,7 @@ class ExportInfo {
this._usedName = initFrom ? initFrom._usedName : null;
/**
* @private
* @type {UsageStateType}
* @type {UsageStateType | undefined}
*/
this._globalUsed = initFrom ? initFrom._globalUsed : undefined;
/**
@@ -864,9 +875,9 @@ class ExportInfo {
this.canMangleUse = initFrom ? initFrom.canMangleUse : undefined;
/** @type {boolean} */
this.exportsInfoOwned = false;
/** @type {ExportsInfo=} */
/** @type {ExportsInfo | undefined} */
this.exportsInfo = undefined;
/** @type {Map<any, { connection: ModuleGraphConnection | null, export: string[], priority: number }>=} */
/** @type {Target | undefined} */
this._target = undefined;
if (initFrom && initFrom._target) {
this._target = new Map();
@@ -878,19 +889,11 @@ class ExportInfo {
});
}
}
/** @type {Map<any, { connection: ModuleGraphConnection | null, export: string[], priority: number }>=} */
/** @type {Target | undefined} */
this._maxTarget = undefined;
}
// TODO webpack 5 remove
/** @private */
get used() {
throw new Error("REMOVED");
}
/** @private */
get usedName() {
throw new Error("REMOVED");
}
/**
* @private
* @param {*} v v
@@ -898,6 +901,14 @@ class ExportInfo {
set used(v) {
throw new Error("REMOVED");
}
// TODO webpack 5 remove
/** @private */
get used() {
throw new Error("REMOVED");
}
// TODO webpack 5 remove
/**
* @private
* @param {*} v v
@@ -906,6 +917,12 @@ class ExportInfo {
throw new Error("REMOVED");
}
// TODO webpack 5 remove
/** @private */
get usedName() {
throw new Error("REMOVED");
}
get canMangle() {
switch (this.canMangleProvide) {
case undefined:
@@ -973,7 +990,8 @@ class ExportInfo {
this.canMangleUse = true;
}
if (this.exportsInfoOwned) {
this.exportsInfo.setHasUseInfo();
/** @type {ExportsInfo} */
(this.exportsInfo).setHasUseInfo();
}
}
@@ -988,25 +1006,26 @@ class ExportInfo {
if (this._globalUsed === undefined) {
this._globalUsed = newValue;
return true;
} else {
if (this._globalUsed !== newValue && condition(this._globalUsed)) {
this._globalUsed = newValue;
return true;
}
}
if (this._globalUsed !== newValue && condition(this._globalUsed)) {
this._globalUsed = newValue;
return true;
}
} else if (this._usedInRuntime === undefined) {
if (newValue !== UsageState.Unused && condition(UsageState.Unused)) {
this._usedInRuntime = new Map();
forEachRuntime(runtime, runtime =>
this._usedInRuntime.set(runtime, newValue)
this._usedInRuntime.set(/** @type {string} */ (runtime), newValue)
);
return true;
}
} else {
let changed = false;
forEachRuntime(runtime, runtime => {
/** @type {UsageStateType} */
let oldValue = this._usedInRuntime.get(runtime);
forEachRuntime(runtime, _runtime => {
const runtime = /** @type {string} */ (_runtime);
let oldValue =
/** @type {UsageStateType} */
(this._usedInRuntime.get(runtime));
if (oldValue === undefined) oldValue = UsageState.Unused;
if (newValue !== oldValue && condition(oldValue)) {
if (newValue === UsageState.Unused) {
@@ -1040,15 +1059,17 @@ class ExportInfo {
if (newValue !== UsageState.Unused) {
this._usedInRuntime = new Map();
forEachRuntime(runtime, runtime =>
this._usedInRuntime.set(runtime, newValue)
this._usedInRuntime.set(/** @type {string} */ (runtime), newValue)
);
return true;
}
} else {
let changed = false;
forEachRuntime(runtime, runtime => {
/** @type {UsageStateType} */
let oldValue = this._usedInRuntime.get(runtime);
forEachRuntime(runtime, _runtime => {
const runtime = /** @type {string} */ (_runtime);
let oldValue =
/** @type {UsageStateType} */
(this._usedInRuntime.get(runtime));
if (oldValue === undefined) oldValue = UsageState.Unused;
if (newValue !== oldValue) {
if (newValue === UsageState.Unused) {
@@ -1083,7 +1104,7 @@ class ExportInfo {
/**
* @param {any} key the key
* @param {ModuleGraphConnection} connection the target module if a single one
* @param {string[]=} exportName the exported name
* @param {(string[] | null)=} exportName the exported name
* @param {number=} priority priority
* @returns {boolean} true, if something has changed
*/
@@ -1091,13 +1112,21 @@ class ExportInfo {
if (exportName) exportName = [...exportName];
if (!this._target) {
this._target = new Map();
this._target.set(key, { connection, export: exportName, priority });
this._target.set(key, {
connection,
export: /** @type {string[]} */ (exportName),
priority
});
return true;
}
const oldTarget = this._target.get(key);
if (!oldTarget) {
if (oldTarget === null && !connection) return false;
this._target.set(key, { connection, export: exportName, priority });
this._target.set(key, {
connection,
export: /** @type {string[]} */ (exportName),
priority
});
this._maxTarget = undefined;
return true;
}
@@ -1109,7 +1138,7 @@ class ExportInfo {
: oldTarget.export)
) {
oldTarget.connection = connection;
oldTarget.export = exportName;
oldTarget.export = /** @type {string[]} */ (exportName);
oldTarget.priority = priority;
this._maxTarget = undefined;
return true;
@@ -1139,20 +1168,20 @@ class ExportInfo {
if (max < value) max = value;
}
return max;
} else {
/** @type {UsageStateType} */
let max = UsageState.Unused;
for (const item of runtime) {
const value = this._usedInRuntime.get(item);
if (value !== undefined) {
if (value === UsageState.Used) {
return UsageState.Used;
}
if (max < value) max = value;
}
}
return max;
}
/** @type {UsageStateType} */
let max = UsageState.Unused;
for (const item of runtime) {
const value = this._usedInRuntime.get(item);
if (value !== undefined) {
if (value === UsageState.Used) {
return UsageState.Used;
}
if (max < value) max = value;
}
}
return max;
}
/**
@@ -1171,19 +1200,18 @@ class ExportInfo {
if (!this._usedInRuntime.has(runtime)) {
return false;
}
} else if (runtime !== undefined) {
if (
Array.from(runtime).every(
runtime => !this._usedInRuntime.has(runtime)
)
) {
return false;
}
} else if (
runtime !== undefined &&
Array.from(runtime).every(
runtime => !this._usedInRuntime.has(runtime)
)
) {
return false;
}
}
}
if (this._usedName !== null) return this._usedName;
return this.name || fallbackName;
return /** @type {string | false} */ (this.name || fallbackName);
}
/**
@@ -1204,13 +1232,13 @@ class ExportInfo {
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target
* @param {function(TargetItem): boolean} resolveTargetFilter filter function to further resolve target
* @returns {ExportInfo | ExportsInfo | undefined} the terminal binding export(s) info if known
*/
getTerminalBinding(moduleGraph, resolveTargetFilter = RETURNS_TRUE) {
if (this.terminalBinding) return this;
const target = this.getTarget(moduleGraph, resolveTargetFilter);
if (!target) return undefined;
if (!target) return;
const exportsInfo = moduleGraph.getExportsInfo(target.module);
if (!target.export) return exportsInfo;
return exportsInfo.getReadOnlyExportInfoRecursive(target.export);
@@ -1222,10 +1250,11 @@ class ExportInfo {
_getMaxTarget() {
if (this._maxTarget !== undefined) return this._maxTarget;
if (this._target.size <= 1) return (this._maxTarget = this._target);
if (/** @type {Target} */ (this._target).size <= 1)
return (this._maxTarget = this._target);
let maxPriority = -Infinity;
let minPriority = Infinity;
for (const { priority } of this._target.values()) {
for (const { priority } of /** @type {Target} */ (this._target).values()) {
if (maxPriority < priority) maxPriority = priority;
if (minPriority > priority) minPriority = priority;
}
@@ -1234,7 +1263,7 @@ class ExportInfo {
// This is an edge case
const map = new Map();
for (const [key, value] of this._target) {
for (const [key, value] of /** @type {Target} */ (this._target)) {
if (maxPriority === value.priority) {
map.set(key, value);
}
@@ -1246,7 +1275,7 @@ class ExportInfo {
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {function(Module): boolean} validTargetModuleFilter a valid target module
* @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid
* @returns {TargetItemWithoutConnection | null | undefined | false} the target, undefined when there is no target, false when no target is valid
*/
findTarget(moduleGraph, validTargetModuleFilter) {
return this._findTarget(moduleGraph, validTargetModuleFilter, new Set());
@@ -1256,13 +1285,15 @@ class ExportInfo {
* @param {ModuleGraph} moduleGraph the module graph
* @param {function(Module): boolean} validTargetModuleFilter a valid target module
* @param {Set<ExportInfo>} alreadyVisited set of already visited export info to avoid circular references
* @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid
* @returns {TargetItemWithoutConnection | null | undefined | false} the target, undefined when there is no target, false when no target is valid
*/
_findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) {
if (!this._target || this._target.size === 0) return undefined;
let rawTarget = this._getMaxTarget().values().next().value;
if (!rawTarget) return undefined;
/** @type {{ module: Module, export: string[] | undefined }} */
if (!this._target || this._target.size === 0) return;
const rawTarget =
/** @type {Target} */
(this._getMaxTarget()).values().next().value;
if (!rawTarget) return;
/** @type {TargetItemWithoutConnection} */
let target = {
module: rawTarget.connection.module,
export: rawTarget.export
@@ -1293,26 +1324,26 @@ class ExportInfo {
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target
* @returns {{ module: Module, export: string[] | undefined } | undefined} the target
* @param {function(TargetItem): boolean} resolveTargetFilter filter function to further resolve target
* @returns {TargetItem | undefined} the target
*/
getTarget(moduleGraph, resolveTargetFilter = RETURNS_TRUE) {
const result = this._getTarget(moduleGraph, resolveTargetFilter, undefined);
if (result === CIRCULAR) return undefined;
if (result === CIRCULAR) return;
return result;
}
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {function({ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target
* @param {function(TargetItem): boolean} resolveTargetFilter filter function to further resolve target
* @param {Set<ExportInfo> | undefined} alreadyVisited set of already visited export info to avoid circular references
* @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | undefined} the target
* @returns {TargetItem | CIRCULAR | undefined} the target
*/
_getTarget(moduleGraph, resolveTargetFilter, alreadyVisited) {
/**
* @param {{ connection: ModuleGraphConnection, export: string[] | undefined } | null} inputTarget unresolved target
* @param {TargetItem | null} inputTarget unresolved target
* @param {Set<ExportInfo>} alreadyVisited set of already visited export info to avoid circular references
* @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | null} resolved target
* @returns {TargetItem | CIRCULAR | null} resolved target
*/
const resolveTarget = (inputTarget, alreadyVisited) => {
if (!inputTarget) return null;
@@ -1323,7 +1354,7 @@ class ExportInfo {
export: undefined
};
}
/** @type {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} */
/** @type {TargetItem} */
let target = {
module: inputTarget.connection.module,
connection: inputTarget.connection,
@@ -1333,7 +1364,10 @@ class ExportInfo {
let alreadyVisitedOwned = false;
for (;;) {
const exportsInfo = moduleGraph.getExportsInfo(target.module);
const exportInfo = exportsInfo.getExportInfo(target.export[0]);
const exportInfo = exportsInfo.getExportInfo(
/** @type {NonNullable<TargetItem["export"]>} */
(target.export)[0]
);
if (!exportInfo) return target;
if (alreadyVisited.has(exportInfo)) return CIRCULAR;
const newTarget = exportInfo._getTarget(
@@ -1343,7 +1377,10 @@ class ExportInfo {
);
if (newTarget === CIRCULAR) return CIRCULAR;
if (!newTarget) return target;
if (target.export.length === 1) {
if (
/** @type {NonNullable<TargetItem["export"]>} */
(target.export).length === 1
) {
target = newTarget;
if (!target.export) return target;
} else {
@@ -1351,8 +1388,12 @@ class ExportInfo {
module: newTarget.module,
connection: newTarget.connection,
export: newTarget.export
? newTarget.export.concat(target.export.slice(1))
: target.export.slice(1)
? newTarget.export.concat(
/** @type {NonNullable<TargetItem["export"]>} */
(target.export).slice(1)
)
: /** @type {NonNullable<TargetItem["export"]>} */
(target.export).slice(1)
};
}
if (!resolveTargetFilter(target)) return target;
@@ -1364,26 +1405,26 @@ class ExportInfo {
}
};
if (!this._target || this._target.size === 0) return undefined;
if (!this._target || this._target.size === 0) return;
if (alreadyVisited && alreadyVisited.has(this)) return CIRCULAR;
const newAlreadyVisited = new Set(alreadyVisited);
newAlreadyVisited.add(this);
const values = this._getMaxTarget().values();
const values = /** @type {Target} */ (this._getMaxTarget()).values();
const target = resolveTarget(values.next().value, newAlreadyVisited);
if (target === CIRCULAR) return CIRCULAR;
if (target === null) return undefined;
if (target === null) return;
let result = values.next();
while (!result.done) {
const t = resolveTarget(result.value, newAlreadyVisited);
if (t === CIRCULAR) return CIRCULAR;
if (t === null) return undefined;
if (t.module !== target.module) return undefined;
if (!t.export !== !target.export) return undefined;
if (t === null) return;
if (t.module !== target.module) return;
if (!t.export !== !target.export) return;
if (
target.export &&
!equals(/** @type {ArrayLike<string>} */ (t.export), target.export)
)
return undefined;
return;
result = values.next();
}
return target;
@@ -1392,34 +1433,42 @@ class ExportInfo {
/**
* Move the target forward as long resolveTargetFilter is fulfilled
* @param {ModuleGraph} moduleGraph the module graph
* @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target
* @param {function({ module: Module, export: string[] | undefined }): ModuleGraphConnection=} updateOriginalConnection updates the original connection instead of using the target connection
* @returns {{ module: Module, export: string[] | undefined } | undefined} the resolved target when moved
* @param {function(TargetItem): boolean} resolveTargetFilter filter function to further resolve target
* @param {function(TargetItem): ModuleGraphConnection=} updateOriginalConnection updates the original connection instead of using the target connection
* @returns {TargetItem | undefined} the resolved target when moved
*/
moveTarget(moduleGraph, resolveTargetFilter, updateOriginalConnection) {
const target = this._getTarget(moduleGraph, resolveTargetFilter, undefined);
if (target === CIRCULAR) return undefined;
if (!target) return undefined;
const originalTarget = this._getMaxTarget().values().next().value;
if (target === CIRCULAR) return;
if (!target) return;
const originalTarget =
/** @type {Target} */
(this._getMaxTarget()).values().next().value;
if (
originalTarget.connection === target.connection &&
originalTarget.export === target.export
) {
return undefined;
return;
}
this._target.clear();
this._target.set(undefined, {
/** @type {Target} */
(this._target).clear();
/** @type {Target} */
(this._target).set(undefined, {
connection: updateOriginalConnection
? updateOriginalConnection(target)
: target.connection,
export: target.export,
export: /** @type {NonNullable<TargetItem["export"]>} */ (target.export),
priority: 0
});
return target;
}
/**
* @returns {ExportsInfo} an exports info
*/
createNestedExportsInfo() {
if (this.exportsInfoOwned) return this.exportsInfo;
if (this.exportsInfoOwned)
return /** @type {ExportsInfo} */ (this.exportsInfo);
this.exportsInfoOwned = true;
const oldExportsInfo = this.exportsInfo;
this.exportsInfo = new ExportsInfo();
@@ -1434,6 +1483,11 @@ class ExportInfo {
return this.exportsInfo;
}
/**
* @param {ExportInfo} baseInfo base info
* @param {RuntimeSpec} runtime runtime
* @returns {boolean} true when has info, otherwise false
*/
hasInfo(baseInfo, runtime) {
return (
(this._usedName && this._usedName !== this.name) ||
@@ -1443,10 +1497,20 @@ class ExportInfo {
);
}
/**
* @param {Hash} hash the hash
* @param {RuntimeSpec} runtime the runtime
* @returns {void}
*/
updateHash(hash, runtime) {
this._updateHash(hash, runtime, new Set());
}
/**
* @param {Hash} hash the hash
* @param {RuntimeSpec} runtime the runtime
* @param {Set<ExportsInfo>} alreadyVisitedExportsInfo for circular references
*/
_updateHash(hash, runtime, alreadyVisitedExportsInfo) {
hash.update(
`${this._usedName || this.name}${this.getUsed(runtime)}${this.provided}${
@@ -1480,6 +1544,7 @@ class ExportInfo {
if (list !== undefined) list.push(runtime);
else map.set(used, [runtime]);
}
// eslint-disable-next-line array-callback-return
const specificInfo = Array.from(map, ([used, runtimes]) => {
switch (used) {
case UsageState.NoInfo:

View File

@@ -11,6 +11,11 @@ const EnvironmentNotSupportAsyncWarning = require("./EnvironmentNotSupportAsyncW
const { UsageState } = require("./ExportsInfo");
const InitFragment = require("./InitFragment");
const Module = require("./Module");
const {
JS_TYPES,
CSS_URL_TYPES,
CSS_IMPORT_TYPES
} = require("./ModuleSourceTypesConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const Template = require("./Template");
@@ -30,6 +35,7 @@ const { register } = require("./util/serialization");
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
@@ -37,7 +43,6 @@ const { register } = require("./util/serialization");
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./RequestShortener")} RequestShortener */
@@ -53,10 +58,11 @@ const { register } = require("./util/serialization");
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {{ attributes?: ImportAttributes }} ImportDependencyMeta */
/** @typedef {{ attributes?: ImportAttributes, externalType: "import" | "module" | undefined }} ImportDependencyMeta */
/** @typedef {{ layer?: string, supports?: string, media?: string }} CssImportDependencyMeta */
/** @typedef {{ sourceType: "css-url" }} AssetDependencyMeta */
/** @typedef {ImportDependencyMeta | CssImportDependencyMeta} DependencyMeta */
/** @typedef {ImportDependencyMeta | CssImportDependencyMeta | AssetDependencyMeta} DependencyMeta */
/**
* @typedef {object} SourceData
@@ -67,8 +73,6 @@ const { register } = require("./util/serialization");
* @property {ReadOnlyRuntimeRequirements=} runtimeRequirements
*/
const TYPES = new Set(["javascript"]);
const CSS_TYPES = new Set(["css-import"]);
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]);
const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([
@@ -164,7 +168,10 @@ const getSourceForImportExternal = (
dependencyMeta
) => {
const importName = runtimeTemplate.outputOptions.importFunctionName;
if (!runtimeTemplate.supportsDynamicImport() && importName === "import") {
if (
!runtimeTemplate.supportsDynamicImport() &&
(importName === "import" || importName === "module-import")
) {
throw new Error(
"The target environment doesn't support 'import()' so it's not possible to use external type 'import'"
);
@@ -210,7 +217,7 @@ const getSourceForImportExternal = (
*/
const importAssertionReplacer = (key, value) => {
if (key === "_isLegacyAssert") {
return undefined;
return;
}
return value;
@@ -353,7 +360,7 @@ const getSourceForModuleExternal = (
runtime,
runtimeTemplate
);
let expression = moduleRemapping || baseAccess;
const expression = moduleRemapping || baseAccess;
return {
expression,
init: moduleRemapping
@@ -415,11 +422,10 @@ const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => {
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {string} the generated source
*/
const checkExternalVariable = (variableName, request, runtimeTemplate) => {
return `if(typeof ${variableName} === 'undefined') { ${runtimeTemplate.throwMissingModuleErrorBlock(
const checkExternalVariable = (variableName, request, runtimeTemplate) =>
`if(typeof ${variableName} === 'undefined') { ${runtimeTemplate.throwMissingModuleErrorBlock(
{ request }
)} }\n`;
};
/**
* @param {string|number} id the module id
@@ -498,7 +504,18 @@ class ExternalModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return this.externalType === "css-import" ? CSS_TYPES : TYPES;
if (
this.externalType === "asset" &&
this.dependencyMeta &&
/** @type {AssetDependencyMeta} */
(this.dependencyMeta).sourceType === "css-url"
) {
return CSS_URL_TYPES;
} else if (this.externalType === "css-import") {
return CSS_IMPORT_TYPES;
}
return JS_TYPES;
}
/**
@@ -524,7 +541,7 @@ class ExternalModule extends Module {
* @returns {string} a unique identifier of the module
*/
identifier() {
return `external ${this.externalType} ${JSON.stringify(this.request)}`;
return `external ${this._resolveExternalType(this.externalType)} ${JSON.stringify(this.request)}`;
}
/**
@@ -532,7 +549,7 @@ class ExternalModule extends Module {
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return "external " + JSON.stringify(this.request);
return `external ${JSON.stringify(this.request)}`;
}
/**
@@ -658,9 +675,43 @@ class ExternalModule extends Module {
let { request, externalType } = this;
if (typeof request === "object" && !Array.isArray(request))
request = request[externalType];
externalType = this._resolveExternalType(externalType);
return { request, externalType };
}
/**
* Resolve the detailed external type from the raw external type.
* e.g. resolve "module" or "import" from "module-import" type
* @param {string} externalType raw external type
* @returns {string} resolved external type
*/
_resolveExternalType(externalType) {
if (externalType === "module-import") {
if (
this.dependencyMeta &&
/** @type {ImportDependencyMeta} */
(this.dependencyMeta).externalType
) {
return /** @type {ImportDependencyMeta} */ (this.dependencyMeta)
.externalType;
}
return "module";
} else if (externalType === "asset") {
if (
this.dependencyMeta &&
/** @type {AssetDependencyMeta} */
(this.dependencyMeta).sourceType
) {
return /** @type {AssetDependencyMeta} */ (this.dependencyMeta)
.sourceType;
}
return "asset";
}
return externalType;
}
/**
* @private
* @param {string | string[]} request request
@@ -702,7 +753,8 @@ class ExternalModule extends Module {
request,
/** @type {string} */
(runtimeTemplate.outputOptions.importMetaName),
runtimeTemplate.supportNodePrefixForCoreModules()
/** @type {boolean} */
(runtimeTemplate.supportNodePrefixForCoreModules())
)
: getSourceForCommonJsExternal(request);
case "amd":
@@ -731,10 +783,11 @@ class ExternalModule extends Module {
if (!(/** @type {BuildInfo} */ (this.buildInfo).module)) {
if (!runtimeTemplate.supportsDynamicImport()) {
throw new Error(
"The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script" +
(runtimeTemplate.supportsEcmaScriptModuleSyntax()
`The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script${
runtimeTemplate.supportsEcmaScriptModuleSyntax()
? "\nDid you mean to build a EcmaScript Module ('output.module: true')?"
: "")
: ""
}`
);
}
return getSourceForImportExternal(
@@ -790,7 +843,13 @@ class ExternalModule extends Module {
new RawSource(`module.exports = ${JSON.stringify(request)};`)
);
const data = new Map();
data.set("url", request);
data.set("url", { javascript: request });
return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data };
}
case "css-url": {
const sources = new Map();
const data = new Map();
data.set("url", { "css-url": request });
return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data };
}
case "css-import": {
@@ -846,7 +905,7 @@ class ExternalModule extends Module {
if (sourceData.init)
sourceString = `${sourceData.init}\n${sourceString}`;
let data = undefined;
let data;
if (sourceData.chunkInitFragments) {
data = new Map();
data.set("chunkInitFragments", sourceData.chunkInitFragments);
@@ -899,7 +958,7 @@ class ExternalModule extends Module {
updateHash(hash, context) {
const { chunkGraph } = context;
hash.update(
`${this.externalType}${JSON.stringify(this.request)}${this.isOptional(
`${this._resolveExternalType(this.externalType)}${JSON.stringify(this.request)}${this.isOptional(
chunkGraph.moduleGraph
)}`
);

View File

@@ -9,10 +9,12 @@ const util = require("util");
const ExternalModule = require("./ExternalModule");
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const CssImportDependency = require("./dependencies/CssImportDependency");
const CssUrlDependency = require("./dependencies/CssUrlDependency");
const HarmonyImportDependency = require("./dependencies/HarmonyImportDependency");
const ImportDependency = require("./dependencies/ImportDependency");
const { resolveByProperty, cachedSetProperty } = require("./util/cleverMerge");
/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionData} ExternalItemFunctionData */
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Compilation").DepConstructor} DepConstructor */
/** @typedef {import("./ExternalModule").DependencyMeta} DependencyMeta */
@@ -24,7 +26,14 @@ const EMPTY_RESOLVE_OPTIONS = {};
// TODO webpack 6 remove this
const callDeprecatedExternals = util.deprecate(
/**
* @param {TODO} externalsFunction externals function
* @param {string} context context
* @param {string} request request
* @param {(err: Error | null | undefined, value: ExternalValue | undefined, ty: ExternalType | undefined) => void} cb cb
*/
(externalsFunction, context, request, cb) => {
// eslint-disable-next-line no-useless-call
externalsFunction.call(null, context, request, cb);
},
"The externals-function should be defined like ({context, request}, cb) => { ... }",
@@ -33,11 +42,17 @@ const callDeprecatedExternals = util.deprecate(
const cache = new WeakMap();
/**
* @template {object} T
* @param {T} obj obj
* @param {TODO} layer layer
* @returns {Omit<T, "byLayer">} result
*/
const resolveLayer = (obj, layer) => {
let map = cache.get(obj);
let map = cache.get(/** @type {object} */ (obj));
if (map === undefined) {
map = new Map();
cache.set(obj, map);
cache.set(/** @type {object} */ (obj), map);
} else {
const cacheEntry = map.get(layer);
if (cacheEntry !== undefined) return cacheEntry;
@@ -47,6 +62,9 @@ const resolveLayer = (obj, layer) => {
return result;
};
/** @typedef {string | string[] | boolean | Record<string, string | string[]>} ExternalValue */
/** @typedef {string | undefined} ExternalType */
class ExternalModuleFactoryPlugin {
/**
* @param {string | undefined} type default external type
@@ -72,8 +90,8 @@ class ExternalModuleFactoryPlugin {
const dependencyType = data.dependencyType;
/**
* @param {string|string[]|boolean|Record<string, string|string[]>} value the external config
* @param {string|undefined} type type of external
* @param {ExternalValue} value the external config
* @param {ExternalType | undefined} type type of external
* @param {function((Error | null)=, ExternalModule=): void} callback callback
* @returns {void}
*/
@@ -83,12 +101,7 @@ class ExternalModuleFactoryPlugin {
return callback();
}
/** @type {string | string[] | Record<string, string|string[]>} */
let externalConfig;
if (value === true) {
externalConfig = dependency.request;
} else {
externalConfig = value;
}
let externalConfig = value === true ? dependency.request : value;
// When no explicit type is specified, extract it from the externalConfig
if (type === undefined) {
if (
@@ -113,6 +126,8 @@ class ExternalModuleFactoryPlugin {
}
}
const resolvedType = /** @type {string} */ (type || globalType);
// TODO make it pluggable/add hooks to `ExternalModule` to allow output modules own externals?
/** @type {DependencyMeta | undefined} */
let dependencyMeta;
@@ -122,8 +137,16 @@ class ExternalModuleFactoryPlugin {
dependency instanceof ImportDependency ||
dependency instanceof ContextElementDependency
) {
const externalType =
dependency instanceof HarmonyImportDependency
? "module"
: dependency instanceof ImportDependency
? "import"
: undefined;
dependencyMeta = {
attributes: dependency.assertions
attributes: dependency.assertions,
externalType
};
} else if (dependency instanceof CssImportDependency) {
dependencyMeta = {
@@ -133,11 +156,18 @@ class ExternalModuleFactoryPlugin {
};
}
if (
resolvedType === "asset" &&
dependency instanceof CssUrlDependency
) {
dependencyMeta = { sourceType: "css-url" };
}
callback(
null,
new ExternalModule(
externalConfig,
type || globalType,
resolvedType,
dependency.request,
dependencyMeta
)
@@ -191,6 +221,12 @@ class ExternalModuleFactoryPlugin {
return handleExternal(dependency.request, undefined, callback);
}
} else if (typeof externals === "function") {
/**
* @param {Error | null | undefined} err err
* @param {ExternalValue=} value value
* @param {ExternalType=} type type
* @returns {void}
*/
const cb = (err, value, type) => {
if (err) return callback(err);
if (value !== undefined) {
@@ -237,7 +273,8 @@ class ExternalModuleFactoryPlugin {
context,
request,
resolveContext,
callback
/** @type {TODO} */
(callback)
);
} else {
return new Promise((resolve, reject) => {

File diff suppressed because it is too large Load Diff

View File

@@ -30,7 +30,7 @@ class FlagAllModulesAsUsedPlugin {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, modules => {
/** @type {RuntimeSpec} */
let runtime = undefined;
let runtime;
for (const [name, { options }] of compilation.entries) {
runtime = mergeRuntimeOwned(
runtime,

View File

@@ -54,14 +54,15 @@ class FlagDependencyExportsPlugin {
const exportsInfo = moduleGraph.getExportsInfo(module);
// If the module doesn't have an exportsType, it's a module
// without declared exports.
if (!module.buildMeta || !module.buildMeta.exportsType) {
if (exportsInfo.otherExportsInfo.provided !== null) {
// It's a module without declared exports
statNoExports++;
exportsInfo.setHasProvideInfo();
exportsInfo.setUnknownExportsProvided();
return callback();
}
if (
(!module.buildMeta || !module.buildMeta.exportsType) &&
exportsInfo.otherExportsInfo.provided !== null
) {
// It's a module without declared exports
statNoExports++;
exportsInfo.setHasProvideInfo();
exportsInfo.setUnknownExportsProvided();
return callback();
}
// If the module has no hash, it's uncacheable
if (
@@ -189,9 +190,9 @@ class FlagDependencyExportsPlugin {
let name;
let canMangle = globalCanMangle;
let terminalBinding = globalTerminalBinding;
let exports = undefined;
let exports;
let from = globalFrom;
let fromExport = undefined;
let fromExport;
let priority = globalPriority;
let hidden = false;
if (typeof exportNameOrSpec === "string") {
@@ -261,7 +262,7 @@ class FlagDependencyExportsPlugin {
// Recalculate target exportsInfo
const target = exportInfo.getTarget(moduleGraph);
let targetExportsInfo = undefined;
let targetExportsInfo;
if (target) {
const targetModuleExportsInfo =
moduleGraph.getExportsInfo(target.module);

View File

@@ -308,7 +308,7 @@ class FlagDependencyUsagePlugin {
}
};
/** @type {RuntimeSpec} */
let globalRuntime = undefined;
let globalRuntime;
for (const [
entryName,
{ dependencies: deps, includeDependencies: includeDeps, options }

View File

@@ -14,6 +14,7 @@
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
@@ -42,9 +43,6 @@
* @property {RuntimeTemplate=} runtimeTemplate
*/
/**
*
*/
class Generator {
/**
* @param {Record<string, Generator>} map map of types
@@ -58,7 +56,7 @@ class Generator {
/**
* @abstract
* @param {NormalModule} module fresh module
* @returns {Set<string>} available types (do not mutate)
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
const AbstractMethodError = require("./AbstractMethodError");
@@ -82,7 +80,7 @@ class Generator {
* @abstract
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source} generated code
* @returns {Source | null} generated code
*/
generate(
module,
@@ -122,7 +120,7 @@ class ByTypeGenerator extends Generator {
/**
* @param {NormalModule} module fresh module
* @returns {Set<string>} available types (do not mutate)
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
return this._types;
@@ -133,8 +131,8 @@ class ByTypeGenerator extends Generator {
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
const t = type || "javascript";
getSize(module, type = "javascript") {
const t = type;
const generator = this.map[t];
return generator ? generator.getSize(module, t) : 0;
}
@@ -142,7 +140,7 @@ class ByTypeGenerator extends Generator {
/**
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source} generated code
* @returns {Source | null} generated code
*/
generate(module, generateContext) {
const type = generateContext.type;

View File

@@ -33,5 +33,6 @@ const connectChunkGroupParentAndChild = (parent, child) => {
}
};
exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk;
exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild;
module.exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk;
module.exports.connectChunkGroupParentAndChild =
connectChunkGroupParentAndChild;

View File

@@ -55,18 +55,16 @@ module.exports.makeWebpackError = makeWebpackError;
* @param {string} hook name of hook
* @returns {Callback<T>} generic callback
*/
const makeWebpackErrorCallback = (callback, hook) => {
return (err, result) => {
if (err) {
if (err instanceof WebpackError) {
callback(err);
return;
}
callback(new HookWebpackError(err, hook));
const makeWebpackErrorCallback = (callback, hook) => (err, result) => {
if (err) {
if (err instanceof WebpackError) {
callback(err);
return;
}
callback(null, result);
};
callback(new HookWebpackError(err, hook));
return;
}
callback(null, result);
};
module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback;

View File

@@ -44,8 +44,11 @@ const {
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").SpreadElement} SpreadElement */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
@@ -58,11 +61,12 @@ const {
/**
* @typedef {object} HMRJavascriptParserHooks
* @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback
* @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback
* @property {SyncBailHook<[Expression | SpreadElement, string[]], void>} hotAcceptCallback
* @property {SyncBailHook<[CallExpression, string[]], void>} hotAcceptWithoutCallback
*/
/** @typedef {Map<string, { updatedChunkIds: Set<ChunkId>, removedChunkIds: Set<ChunkId>, removedModules: Set<Module>, filename: string, assetInfo: AssetInfo }>} HotUpdateMainContentByRuntime */
/** @typedef {{ updatedChunkIds: Set<ChunkId>, removedChunkIds: Set<ChunkId>, removedModules: Set<Module>, filename: string, assetInfo: AssetInfo }} HotUpdateMainContentByRuntimeItem */
/** @typedef {Map<string, HotUpdateMainContentByRuntimeItem>} HotUpdateMainContentByRuntime */
/** @type {WeakMap<JavascriptParser, HMRJavascriptParserHooks>} */
const parserHooksMap = new WeakMap();
@@ -130,6 +134,7 @@ class HotModuleReplacementPlugin {
/** @type {BuildInfo} */
(module.buildInfo).moduleConcatenationBailout =
"Hot Module Replacement";
if (expr.arguments.length >= 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
/** @type {BasicEvaluatedExpression[]} */
@@ -142,9 +147,9 @@ class HotModuleReplacementPlugin {
(arg.items).filter(param => param.isString());
}
/** @type {string[]} */
let requests = [];
const requests = [];
if (params.length > 0) {
params.forEach((param, idx) => {
for (const [idx, param] of params.entries()) {
const request = /** @type {string} */ (param.string);
const dep = new ParamDependency(
request,
@@ -157,17 +162,16 @@ class HotModuleReplacementPlugin {
dep.loc.index = idx;
module.addDependency(dep);
requests.push(request);
});
}
if (expr.arguments.length > 1) {
hotAcceptCallback.call(expr.arguments[1], requests);
for (let i = 1; i < expr.arguments.length; i++) {
parser.walkExpression(expr.arguments[i]);
}
return true;
} else {
hotAcceptWithoutCallback.call(expr, requests);
return true;
}
hotAcceptWithoutCallback.call(expr, requests);
return true;
}
}
parser.walkExpressions(expr.arguments);
@@ -202,7 +206,7 @@ class HotModuleReplacementPlugin {
/** @type {BasicEvaluatedExpression[]} */
(arg.items).filter(param => param.isString());
}
params.forEach((param, idx) => {
for (const [idx, param] of params.entries()) {
const dep = new ParamDependency(
/** @type {string} */ (param.string),
/** @type {Range} */ (param.range)
@@ -211,7 +215,7 @@ class HotModuleReplacementPlugin {
dep.loc = Object.create(/** @type {DependencyLocation} */ (expr.loc));
dep.loc.index = idx;
module.addDependency(dep);
});
}
}
return true;
};
@@ -244,14 +248,13 @@ class HotModuleReplacementPlugin {
name: PLUGIN_NAME,
before: "NodeStuffPlugin"
},
expr => {
return evaluateToIdentifier(
expr =>
evaluateToIdentifier(
"module.hot",
"module",
() => ["hot"],
true
)(expr);
}
)(expr)
);
parser.hooks.call
.for("module.hot.accept")
@@ -277,14 +280,14 @@ class HotModuleReplacementPlugin {
const applyImportMetaHot = parser => {
parser.hooks.evaluateIdentifier
.for("import.meta.webpackHot")
.tap(PLUGIN_NAME, expr => {
return evaluateToIdentifier(
.tap(PLUGIN_NAME, expr =>
evaluateToIdentifier(
"import.meta.webpackHot",
"import.meta",
() => ["webpackHot"],
true
)(expr);
});
)(expr)
);
parser.hooks.call
.for("import.meta.webpackHot.accept")
.tap(
@@ -309,7 +312,7 @@ class HotModuleReplacementPlugin {
// It should not affect child compilations
if (compilation.compiler !== compiler) return;
//#region module.hot.* API
// #region module.hot.* API
compilation.dependencyFactories.set(
ModuleHotAcceptDependency,
normalModuleFactory
@@ -326,9 +329,9 @@ class HotModuleReplacementPlugin {
ModuleHotDeclineDependency,
new ModuleHotDeclineDependency.Template()
);
//#endregion
// #endregion
//#region import.meta.webpackHot.* API
// #region import.meta.webpackHot.* API
compilation.dependencyFactories.set(
ImportMetaHotAcceptDependency,
normalModuleFactory
@@ -345,7 +348,7 @@ class HotModuleReplacementPlugin {
ImportMetaHotDeclineDependency,
new ImportMetaHotDeclineDependency.Template()
);
//#endregion
// #endregion
let hotIndex = 0;
/** @type {Record<string, string>} */
@@ -401,10 +404,9 @@ class HotModuleReplacementPlugin {
module,
chunk.runtime
);
} else {
nonCodeGeneratedModules.add(module, chunk.runtime);
return chunkGraph.getModuleHash(module, chunk.runtime);
}
nonCodeGeneratedModules.add(module, chunk.runtime);
return chunkGraph.getModuleHash(module, chunk.runtime);
};
const fullHashModulesInThisChunk =
chunkGraph.getChunkFullHashModulesSet(chunk);
@@ -446,28 +448,26 @@ class HotModuleReplacementPlugin {
chunkModuleHashes[key] = hash;
}
}
} else {
if (fullHashModulesInThisChunk !== undefined) {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (
fullHashModulesInThisChunk.has(
/** @type {RuntimeModule} */ (module)
)
) {
fullHashChunkModuleHashes[key] = hash;
} else {
chunkModuleHashes[key] = hash;
}
}
} else {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
} else if (fullHashModulesInThisChunk !== undefined) {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (
fullHashModulesInThisChunk.has(
/** @type {RuntimeModule} */ (module)
)
) {
fullHashChunkModuleHashes[key] = hash;
} else {
chunkModuleHashes[key] = hash;
}
}
} else {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
chunkModuleHashes[key] = hash;
}
}
}
}
@@ -517,7 +517,8 @@ class HotModuleReplacementPlugin {
forEachRuntime(allOldRuntime, runtime => {
const { path: filename, info: assetInfo } =
compilation.getPathWithInfo(
compilation.outputOptions.hotUpdateMainFilename,
/** @type {NonNullable<OutputNormalized["hotUpdateMainFilename"]>} */
(compilation.outputOptions.hotUpdateMainFilename),
{
hash: records.hash,
runtime
@@ -540,7 +541,9 @@ class HotModuleReplacementPlugin {
/** @type {Map<number|string, Module>} */
const allModules = new Map();
for (const module of compilation.modules) {
const id = chunkGraph.getModuleId(module);
const id =
/** @type {ModuleId} */
(chunkGraph.getModuleId(module));
allModules.set(id, module);
}
@@ -604,16 +607,20 @@ class HotModuleReplacementPlugin {
removedFromRuntime = subtractRuntime(oldRuntime, newRuntime);
} else {
// chunk has completely removed
chunkId = `${+key}` === key ? +key : key;
chunkId = `${Number(key)}` === key ? Number(key) : key;
removedFromRuntime = oldRuntime;
newRuntime = oldRuntime;
}
if (removedFromRuntime) {
// chunk was removed from some runtimes
forEachRuntime(removedFromRuntime, runtime => {
const item = hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
);
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */
(
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.removedChunkIds.add(/** @type {ChunkId} */ (chunkId));
});
// dispose modules from the chunk in these runtimes
@@ -654,16 +661,18 @@ class HotModuleReplacementPlugin {
for (const moduleRuntime of runtimes) {
if (typeof moduleRuntime === "string") {
if (moduleRuntime === runtime) return;
} else if (moduleRuntime !== undefined) {
if (
moduleRuntime.has(/** @type {string} */ (runtime))
)
return;
}
} else if (
moduleRuntime !== undefined &&
moduleRuntime.has(/** @type {string} */ (runtime))
)
return;
}
const item = hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
);
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */ (
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.removedModules.add(module);
});
}
@@ -677,7 +686,9 @@ class HotModuleReplacementPlugin {
if (backCompat)
ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph);
hotUpdateChunk.id = chunkId;
hotUpdateChunk.runtime = newRuntime;
hotUpdateChunk.runtime = currentChunk
? currentChunk.runtime
: newRuntime;
if (currentChunk) {
for (const group of currentChunk.groupsIterable)
hotUpdateChunk.addGroup(group);
@@ -738,9 +749,12 @@ class HotModuleReplacementPlugin {
}
}
forEachRuntime(newRuntime, runtime => {
const item = hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
);
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */ (
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.updatedChunkIds.add(/** @type {ChunkId} */ (chunkId));
});
}
@@ -795,8 +809,10 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
removedModules.size === 0
? completelyRemovedModulesArray
: completelyRemovedModulesArray.concat(
Array.from(removedModules, m =>
chunkGraph.getModuleId(m)
Array.from(
removedModules,
m =>
/** @type {ModuleId} */ (chunkGraph.getModuleId(m))
)
)
};

View File

@@ -30,9 +30,9 @@ class IgnoreErrorModuleFactory extends ModuleFactory {
* @returns {void}
*/
create(data, callback) {
this.normalModuleFactory.create(data, (err, result) => {
return callback(null, result);
});
this.normalModuleFactory.create(data, (err, result) =>
callback(null, result)
);
}
}

View File

@@ -5,6 +5,8 @@
"use strict";
const RawModule = require("./RawModule");
const EntryDependency = require("./dependencies/EntryDependency");
const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */
@@ -36,9 +38,7 @@ class IgnorePlugin {
}
/**
* Note that if "contextRegExp" is given, both the "resourceRegExp"
* and "contextRegExp" have to match.
*
* Note that if "contextRegExp" is given, both the "resourceRegExp" and "contextRegExp" have to match.
* @param {ResolveData} resolveData resolve data
* @returns {false|undefined} returns false when the request should be ignored, otherwise undefined
*/
@@ -75,7 +75,23 @@ class IgnorePlugin {
*/
apply(compiler) {
compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => {
nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
nmf.hooks.beforeResolve.tap("IgnorePlugin", resolveData => {
const result = this.checkIgnore(resolveData);
if (
result === false &&
resolveData.dependencies.length > 0 &&
resolveData.dependencies[0] instanceof EntryDependency
) {
resolveData.ignoredModule = new RawModule(
"",
"ignored-entry-module",
"(ignored-entry-module)"
);
}
return result;
});
});
compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => {
cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);

View File

@@ -15,6 +15,7 @@ class IgnoreWarningsPlugin {
constructor(ignoreWarnings) {
this._ignoreWarnings = ignoreWarnings;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
@@ -22,15 +23,11 @@ class IgnoreWarningsPlugin {
*/
apply(compiler) {
compiler.hooks.compilation.tap("IgnoreWarningsPlugin", compilation => {
compilation.hooks.processWarnings.tap(
"IgnoreWarningsPlugin",
warnings => {
return warnings.filter(warning => {
return !this._ignoreWarnings.some(ignore =>
ignore(warning, compilation)
);
});
}
compilation.hooks.processWarnings.tap("IgnoreWarningsPlugin", warnings =>
warnings.filter(
warning =>
!this._ignoreWarnings.some(ignore => ignore(warning, compilation))
)
);
});
}

View File

@@ -116,7 +116,7 @@ class InitFragment {
continue;
}
}
keyedFragments.set(fragment.key || Symbol(), fragment);
keyedFragments.set(fragment.key || Symbol("fragment key"), fragment);
}
const concatSource = new ConcatSource();
@@ -137,9 +137,8 @@ class InitFragment {
concatSource.add(content);
}
return concatSource;
} else {
return source;
}
return source;
}
/**

View File

@@ -11,6 +11,7 @@ const { someInIterable } = require("./util/IterableHelpers");
const { compareModulesById } = require("./util/comparators");
const { dirname, mkdirp } = require("./util/fs");
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
@@ -55,7 +56,7 @@ class LibManifestPlugin {
const moduleGraph = compilation.moduleGraph;
// store used paths to detect issue and output an error. #18200
const usedPaths = new Set();
asyncLib.forEach(
asyncLib.each(
Array.from(compilation.chunks),
(chunk, callback) => {
if (!chunk.canBeInitial()) {
@@ -67,7 +68,7 @@ class LibManifestPlugin {
chunk
});
if (usedPaths.has(targetPath)) {
callback(new Error(`each chunk must have a unique path`));
callback(new Error("each chunk must have a unique path"));
return;
}
usedPaths.add(targetPath);
@@ -102,7 +103,7 @@ class LibManifestPlugin {
const providedExports = exportsInfo.getProvidedExports();
/** @type {ManifestModuleData} */
const data = {
id: chunkGraph.getModuleId(module),
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
buildMeta: /** @type {BuildMeta} */ (module.buildMeta),
exports: Array.isArray(providedExports)
? providedExports

View File

@@ -69,7 +69,9 @@ class LoaderOptionsPlugin {
if (key === "include" || key === "exclude" || key === "test") {
continue;
}
context[key] = options[key];
/** @type {any} */
(context)[key] = options[key];
}
}
}

View File

@@ -10,6 +10,7 @@ const util = require("util");
const RuntimeGlobals = require("./RuntimeGlobals");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
@@ -17,15 +18,24 @@ const memoize = require("./util/memoize");
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").InterpolatedPathAndAssetInfo} InterpolatedPathAndAssetInfo */
/** @typedef {import("./Module")} Module} */
/** @typedef {import("./util/Hash")} Hash} */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates} */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext} */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderBootstrapContext} RenderBootstrapContext} */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkHashContext} ChunkHashContext} */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate} */
/** @typedef {import("./ModuleGraph")} ModuleGraph} */
/** @typedef {import("./ChunkGraph")} ChunkGraph} */
/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions} */
/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry} */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath} */
/** @typedef {import("./TemplatedPathPlugin").PathData} PathData} */
/**
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
@@ -40,7 +50,6 @@ const getLoadScriptRuntimeModule = memoize(() =>
// TODO webpack 6 remove this class
class MainTemplate {
/**
*
* @param {OutputOptions} outputOptions output options for the MainTemplate
* @param {Compilation} compilation the compilation
*/
@@ -50,6 +59,11 @@ class MainTemplate {
this.hooks = Object.freeze({
renderManifest: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(RenderManifestEntry[], RenderManifestOptions): RenderManifestEntry[]} fn fn
*/
(options, fn) => {
compilation.hooks.renderManifest.tap(
options,
@@ -79,6 +93,11 @@ class MainTemplate {
},
require: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(string, RenderBootstrapContext): string} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -111,6 +130,11 @@ class MainTemplate {
},
render: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Chunk, string | undefined, ModuleTemplate, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -138,6 +162,11 @@ class MainTemplate {
},
renderWithEntry: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Chunk, string | undefined): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -159,6 +188,11 @@ class MainTemplate {
},
assetPath: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(string, object, AssetInfo | undefined): string} fn fn
*/
(options, fn) => {
compilation.hooks.assetPath.tap(options, fn);
},
@@ -166,15 +200,23 @@ class MainTemplate {
"DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH"
),
call: util.deprecate(
(filename, options) => {
return compilation.getAssetPath(filename, options);
},
/**
* @param {TemplatePath} filename used to get asset path with hash
* @param {PathData} options context data
* @returns {string} interpolated path
*/
(filename, options) => compilation.getAssetPath(filename, options),
"MainTemplate.hooks.assetPath is deprecated (use Compilation.hooks.assetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH"
)
},
hash: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash): void} fn fn
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
@@ -184,6 +226,11 @@ class MainTemplate {
},
hashForChunk: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash, Chunk): void} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -259,7 +306,8 @@ class MainTemplate {
* @param {string} hash the hash
* @param {number=} length length of the hash
* @returns {string} generated code
*/ (hash, length) => {
*/
(hash, length) => {
if (length) {
return `${RuntimeGlobals.getFullHash} ? ${
RuntimeGlobals.getFullHash
@@ -273,31 +321,36 @@ class MainTemplate {
this.getPublicPath = util.deprecate(
/**
*
* @param {object} options get public path options
* @returns {string} hook call
*/ options => {
return compilation.getAssetPath(
compilation.outputOptions.publicPath,
* @param {PathData} options context data
* @returns {string} interpolated path
*/ options =>
compilation.getAssetPath(
/** @type {string} */
(compilation.outputOptions.publicPath),
options
);
},
),
"MainTemplate.getPublicPath is deprecated (use Compilation.getAssetPath(compilation.outputOptions.publicPath, options) instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_PUBLIC_PATH"
);
this.getAssetPath = util.deprecate(
(path, options) => {
return compilation.getAssetPath(path, options);
},
/**
* @param {TemplatePath} path used to get asset path with hash
* @param {PathData} options context data
* @returns {string} interpolated path
*/
(path, options) => compilation.getAssetPath(path, options),
"MainTemplate.getAssetPath is deprecated (use Compilation.getAssetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH"
);
this.getAssetPathWithInfo = util.deprecate(
(path, options) => {
return compilation.getAssetPathWithInfo(path, options);
},
/**
* @param {TemplatePath} path used to get asset path with hash
* @param {PathData} options context data
* @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info
*/
(path, options) => compilation.getAssetPathWithInfo(path, options),
"MainTemplate.getAssetPathWithInfo is deprecated (use Compilation.getAssetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH_WITH_INFO"
);

45
node_modules/webpack/lib/Module.js generated vendored
View File

@@ -9,6 +9,7 @@ const util = require("util");
const ChunkGraph = require("./ChunkGraph");
const DependenciesBlock = require("./DependenciesBlock");
const ModuleGraph = require("./ModuleGraph");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const { first } = require("./util/SetHelpers");
const { compareChunksById } = require("./util/comparators");
@@ -18,6 +19,7 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Compilation")} Compilation */
@@ -54,6 +56,8 @@ const makeSerializable = require("./util/makeSerializable");
* @property {string=} type the type of source that should be generated
*/
/** @typedef {ReadonlySet<string>} SourceTypes */
// TODO webpack 6: compilation will be required in CodeGenerationContext
/**
* @typedef {object} CodeGenerationContext
@@ -65,7 +69,7 @@ const makeSerializable = require("./util/makeSerializable");
* @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
* @property {CodeGenerationResults | undefined} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
* @property {Compilation=} compilation the compilation
* @property {ReadonlySet<string>=} sourceTypes source types
* @property {SourceTypes=} sourceTypes source types
*/
/**
@@ -81,7 +85,7 @@ const makeSerializable = require("./util/makeSerializable");
* @typedef {object} CodeGenerationResult
* @property {Map<string, Source>} sources the resulting sources for all source types
* @property {Map<string, any>=} data the resulting data for all source types
* @property {ReadOnlyRuntimeRequirements} runtimeRequirements the runtime requirements
* @property {ReadOnlyRuntimeRequirements | null} runtimeRequirements the runtime requirements
* @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided)
*/
@@ -112,18 +116,20 @@ const makeSerializable = require("./util/makeSerializable");
* @property {LazySet<string>=} contextDependencies
* @property {LazySet<string>=} missingDependencies
* @property {LazySet<string>=} buildDependencies
* @property {(Map<string, string | Set<string>>)=} valueDependencies
* @property {ValueCacheVersions=} valueDependencies
* @property {TODO=} hash
* @property {Record<string, Source>=} assets
* @property {Map<string, AssetInfo | undefined>=} assetsInfo
* @property {(Snapshot | null)=} snapshot
*/
/** @typedef {Map<string, string | Set<string>>} ValueCacheVersions */
/**
* @typedef {object} NeedBuildContext
* @property {Compilation} compilation
* @property {FileSystemInfo} fileSystemInfo
* @property {Map<string, string | Set<string>>} valueCacheVersions
* @property {ValueCacheVersions} valueCacheVersions
*/
/** @typedef {KnownBuildMeta & Record<string, any>} BuildMeta */
@@ -134,8 +140,6 @@ const makeSerializable = require("./util/makeSerializable");
* @property {boolean=} sideEffectFree
*/
/** @typedef {Set<string>} SourceTypes */
/** @typedef {{ factoryMeta: FactoryMeta | undefined, resolveOptions: ResolveOptions | undefined }} UnsafeCacheData */
const EMPTY_RESOLVE_OPTIONS = {};
@@ -143,7 +147,6 @@ const EMPTY_RESOLVE_OPTIONS = {};
let debugId = 1000;
const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]);
const DEFAULT_TYPES_JS = new Set(["javascript"]);
const deprecatedNeedRebuild = util.deprecate(
/**
@@ -151,12 +154,11 @@ const deprecatedNeedRebuild = util.deprecate(
* @param {NeedBuildContext} context context info
* @returns {boolean} true, when rebuild is needed
*/
(module, context) => {
return module.needRebuild(
(module, context) =>
module.needRebuild(
context.fileSystemInfo.getDeprecatedFileTimestamps(),
context.fileSystemInfo.getDeprecatedContextTimestamps()
);
},
),
"Module.needRebuild is deprecated in favor of Module.needBuild",
"DEP_WEBPACK_MODULE_NEED_REBUILD"
);
@@ -214,6 +216,9 @@ class Module extends DependenciesBlock {
// TODO remove in webpack 6
// BACKWARD-COMPAT START
/**
* @returns {ModuleId | null} module id
*/
get id() {
return ChunkGraph.getChunkGraphForModule(
this,
@@ -222,6 +227,9 @@ class Module extends DependenciesBlock {
).getModuleId(this);
}
/**
* @param {ModuleId} value value
*/
set id(value) {
if (value === "") {
this.needId = false;
@@ -865,9 +873,8 @@ class Module extends DependenciesBlock {
// Better override this method to return the correct types
if (this.source === Module.prototype.source) {
return DEFAULT_TYPES_UNKNOWN;
} else {
return DEFAULT_TYPES_JS;
}
return JS_TYPES;
}
/**
@@ -899,7 +906,11 @@ class Module extends DependenciesBlock {
};
const sources = this.codeGeneration(codeGenContext).sources;
return type ? sources.get(type) : sources.get(first(this.getSourceTypes()));
return /** @type {Source} */ (
type
? sources.get(type)
: sources.get(/** @type {string} */ (first(this.getSourceTypes())))
);
}
/* istanbul ignore next */
@@ -1105,6 +1116,8 @@ class Module extends DependenciesBlock {
makeSerializable(Module, "webpack/lib/Module");
// TODO remove in webpack 6
// eslint-disable-next-line no-warning-comments
// @ts-ignore https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Module.prototype, "hasEqualsChunks", {
get() {
throw new Error(
@@ -1114,6 +1127,8 @@ Object.defineProperty(Module.prototype, "hasEqualsChunks", {
});
// TODO remove in webpack 6
// eslint-disable-next-line no-warning-comments
// @ts-ignore https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Module.prototype, "isUsed", {
get() {
throw new Error(
@@ -1159,6 +1174,8 @@ Object.defineProperty(Module.prototype, "warnings", {
});
// TODO remove in webpack 6
// eslint-disable-next-line no-warning-comments
// @ts-ignore https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Module.prototype, "used", {
get() {
throw new Error(

View File

@@ -19,13 +19,9 @@ class ModuleBuildError extends WebpackError {
*/
constructor(err, { from = null } = {}) {
let message = "Module build failed";
let details = undefined;
let details;
if (from) {
message += ` (from ${from}):\n`;
} else {
message += ": ";
}
message += from ? ` (from ${from}):\n` : ": ";
if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) {
@@ -36,11 +32,8 @@ class ModuleBuildError extends WebpackError {
} else {
details = stack;
if (typeof err.message === "string" && err.message) {
message += err.message;
} else {
message += err;
}
message +=
typeof err.message === "string" && err.message ? err.message : err;
}
} else if (typeof err.message === "string" && err.message) {
message += err.message;

View File

@@ -30,11 +30,11 @@ class ModuleDependencyError extends WebpackError {
/** error is not (de)serialized, so it might be undefined after deserialization */
this.error = err;
if (err && /** @type {any} */ (err).hideStack) {
this.stack =
/** @type {string} */ (err.stack).split("\n").slice(1).join("\n") +
"\n\n" +
this.stack;
if (err && /** @type {any} */ (err).hideStack && err.stack) {
this.stack = /** @type {string} */ `${err.stack
.split("\n")
.slice(1)
.join("\n")}\n\n${this.stack}`;
}
}
}

View File

@@ -30,11 +30,11 @@ class ModuleDependencyWarning extends WebpackError {
/** error is not (de)serialized, so it might be undefined after deserialization */
this.error = err;
if (err && /** @type {any} */ (err).hideStack) {
this.stack =
/** @type {string} */ (err.stack).split("\n").slice(1).join("\n") +
"\n\n" +
this.stack;
if (err && /** @type {any} */ (err).hideStack && err.stack) {
this.stack = /** @type {string} */ `${err.stack
.split("\n")
.slice(1)
.join("\n")}\n\n${this.stack}`;
}
}
}

View File

@@ -20,11 +20,7 @@ class ModuleError extends WebpackError {
constructor(err, { from = null } = {}) {
let message = "Module Error";
if (from) {
message += ` (from ${from}):\n`;
} else {
message += ": ";
}
message += from ? ` (from ${from}):\n` : ": ";
if (err && typeof err === "object" && err.message) {
message += err.message;

View File

@@ -17,7 +17,7 @@ const memoize = require("./util/memoize");
/** @typedef {string | RegExp | (string | RegExp)[]} Matcher */
/** @typedef {{test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */
const ModuleFilenameHelpers = exports;
const ModuleFilenameHelpers = module.exports;
// TODO webpack 6: consider removing these
ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
@@ -54,12 +54,10 @@ ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi;
* @param {string} token the token to search for
* @returns {ReturnStringCallback} a function that returns the part of the string after the token
*/
const getAfter = (strFn, token) => {
return () => {
const str = strFn();
const idx = str.indexOf(token);
return idx < 0 ? "" : str.slice(idx);
};
const getAfter = (strFn, token) => () => {
const str = strFn();
const idx = str.indexOf(token);
return idx < 0 ? "" : str.slice(idx);
};
/**
@@ -68,12 +66,10 @@ const getAfter = (strFn, token) => {
* @param {string} token the token to search for
* @returns {ReturnStringCallback} a function that returns the part of the string before the token
*/
const getBefore = (strFn, token) => {
return () => {
const str = strFn();
const idx = str.lastIndexOf(token);
return idx < 0 ? "" : str.slice(0, idx);
};
const getBefore = (strFn, token) => () => {
const str = strFn();
const idx = str.lastIndexOf(token);
return idx < 0 ? "" : str.slice(0, idx);
};
/**
@@ -82,14 +78,14 @@ const getBefore = (strFn, token) => {
* @param {string | Hash=} hashFunction the hash function to use
* @returns {ReturnStringCallback} a function that returns the hash of the string
*/
const getHash = (strFn, hashFunction = "md4") => {
return () => {
const getHash =
(strFn, hashFunction = "md4") =>
() => {
const hash = createHash(hashFunction);
hash.update(strFn());
const digest = /** @type {string} */ (hash.digest("hex"));
return digest.slice(0, 4);
};
};
/**
* Returns a function that returns the string with the token replaced with the replacement
@@ -108,7 +104,7 @@ const asRegExp = test => {
if (typeof test === "string") {
// Escape special characters in the string to prevent them from being interpreted as special characters in a regular expression. Do this by
// adding a backslash before each special character
test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
test = new RegExp(`^${test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")}`);
}
return test;
};
@@ -143,7 +139,6 @@ const lazyObject = obj => {
const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
/**
*
* @param {Module | string} module the module
* @param {TODO} options options
* @param {object} contextInfo context info
@@ -153,6 +148,7 @@ const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
* @returns {string} the filename
*/
ModuleFilenameHelpers.createFilename = (
// eslint-disable-next-line default-param-last
module = "",
options,
{ requestShortener, chunkGraph, hashFunction = "md4" }
@@ -213,9 +209,9 @@ ModuleFilenameHelpers.createFilename = (
if (typeof opts.moduleFilenameTemplate === "function") {
return opts.moduleFilenameTemplate(
lazyObject({
identifier: identifier,
shortIdentifier: shortIdentifier,
resource: resource,
identifier,
shortIdentifier,
resource,
resourcePath: memoize(resourcePath),
absoluteResourcePath: memoize(absoluteResourcePath),
loaders: memoize(loaders),
@@ -285,13 +281,11 @@ ModuleFilenameHelpers.createFilename = (
* Replaces duplicate items in an array with new values generated by a callback function.
* The callback function is called with the duplicate item, the index of the duplicate item, and the number of times the item has been replaced.
* The callback function should return the new value for the duplicate item.
*
* @template T
* @param {T[]} array the array with duplicates to be replaced
* @param {(duplicateItem: T, duplicateItemIndex: number, numberOfTimesReplaced: number) => T} fn callback function to generate new values for the duplicate items
* @param {(firstElement:T, nextElement:T) => -1 | 0 | 1} [comparator] optional comparator function to sort the duplicate items
* @returns {T[]} the array with duplicates replaced
*
* @example
* ```js
* const array = ["a", "b", "c", "a", "b", "a"];
@@ -303,33 +297,30 @@ ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
const countMap = Object.create(null);
const posMap = Object.create(null);
array.forEach((item, idx) => {
for (const [idx, item] of array.entries()) {
countMap[item] = countMap[item] || [];
countMap[item].push(idx);
posMap[item] = 0;
});
}
if (comparator) {
Object.keys(countMap).forEach(item => {
for (const item of Object.keys(countMap)) {
countMap[item].sort(comparator);
});
}
}
return array.map((item, i) => {
if (countMap[item].length > 1) {
if (comparator && countMap[item][0] === i) return item;
return fn(item, i, posMap[item]++);
} else {
return item;
}
return item;
});
};
/**
* Tests if a string matches a RegExp or an array of RegExp.
*
* @param {string} str string to test
* @param {Matcher} test value which will be used to match against the string
* @returns {boolean} true, when the RegExp matches
*
* @example
* ```js
* ModuleFilenameHelpers.matchPart("foo.js", "foo"); // true
@@ -349,9 +340,8 @@ ModuleFilenameHelpers.matchPart = (str, test) => {
if (Array.isArray(test)) {
return test.map(asRegExp).some(regExp => regExp.test(str));
} else {
return asRegExp(test).test(str);
}
return asRegExp(test).test(str);
};
/**
@@ -361,7 +351,6 @@ ModuleFilenameHelpers.matchPart = (str, test) => {
* - `exclude`: a RegExp or an array of RegExp
*
* The `test` property is tested first, then `include` and then `exclude`.
*
* @param {MatchObject} obj a match object to test against the string
* @param {string} str string to test against the matching object
* @returns {boolean} true, when the object matches
@@ -381,20 +370,14 @@ ModuleFilenameHelpers.matchPart = (str, test) => {
* ```
*/
ModuleFilenameHelpers.matchObject = (obj, str) => {
if (obj.test) {
if (!ModuleFilenameHelpers.matchPart(str, obj.test)) {
return false;
}
if (obj.test && !ModuleFilenameHelpers.matchPart(str, obj.test)) {
return false;
}
if (obj.include) {
if (!ModuleFilenameHelpers.matchPart(str, obj.include)) {
return false;
}
if (obj.include && !ModuleFilenameHelpers.matchPart(str, obj.include)) {
return false;
}
if (obj.exclude) {
if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
return false;
}
if (obj.exclude && ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
return false;
}
return true;
};

View File

@@ -36,7 +36,7 @@ const getConnectionsByOriginModule = set => {
/** @type {Module | 0} */
let lastModule = 0;
/** @type {ModuleGraphConnection[] | undefined} */
let lastList = undefined;
let lastList;
for (const connection of set) {
const { originModule } = connection;
if (lastModule === originModule) {
@@ -67,7 +67,7 @@ const getConnectionsByModule = set => {
/** @type {Module | 0} */
let lastModule = 0;
/** @type {ModuleGraphConnection[] | undefined} */
let lastList = undefined;
let lastList;
for (const connection of set) {
const { module } = connection;
if (lastModule === module) {
@@ -445,7 +445,7 @@ class ModuleGraph {
}
}
this._dependencyMap.set(dependency, null);
return undefined;
return;
}
return connection === null ? undefined : connection;
}
@@ -851,12 +851,13 @@ class ModuleGraph {
const moduleGraph = moduleGraphForModuleMap.get(module);
if (!moduleGraph)
throw new Error(
deprecateMessage +
"There was no ModuleGraph assigned to the Module for backward-compat (Use the new API)"
`${
deprecateMessage
}There was no ModuleGraph assigned to the Module for backward-compat (Use the new API)`
);
return moduleGraph;
},
deprecateMessage + ": Use new ModuleGraph API",
`${deprecateMessage}: Use new ModuleGraph API`,
deprecationCode
);
deprecateMap.set(deprecateMessage, newFn);

View File

@@ -73,7 +73,7 @@ class ModuleGraphConnection {
this.resolvedModule = module;
this.module = module;
this.weak = weak;
this.conditional = !!condition;
this.conditional = Boolean(condition);
this._active = condition !== false;
/** @type {(function(ModuleGraphConnection, RuntimeSpec): ConnectionState) | undefined} */
this.condition = condition || undefined;
@@ -135,11 +135,6 @@ class ModuleGraphConnection {
return Array.from(this.explanations).join(" ");
}
// TODO webpack 5 remove
get active() {
throw new Error("Use getActiveState instead");
}
/**
* @param {RuntimeSpec} runtime the runtime
* @returns {boolean} true, if the connection is active
@@ -187,6 +182,11 @@ class ModuleGraphConnection {
this._active = value;
}
// TODO webpack 5 remove
get active() {
throw new Error("Use getActiveState instead");
}
set active(value) {
throw new Error("Use setActive instead");
}

View File

@@ -8,6 +8,7 @@
const { ConcatSource, RawSource, CachedSource } = require("webpack-sources");
const { UsageState } = require("./ExportsInfo");
const Template = require("./Template");
const CssModulesPlugin = require("./css/CssModulesPlugin");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("webpack-sources").Source} Source */
@@ -84,7 +85,7 @@ const printExportsInfoToSource = (
for (const exportInfo of printedExports) {
const target = exportInfo.getTarget(moduleGraph);
source.add(
Template.toComment(
`${Template.toComment(
`${indent}export ${JSON.stringify(exportInfo.name).slice(
1,
-1
@@ -99,12 +100,12 @@ const printExportsInfoToSource = (
}`
: ""
}`
) + "\n"
)}\n`
);
if (exportInfo.exportsInfo) {
printExportsInfoToSource(
source,
indent + " ",
`${indent} `,
exportInfo.exportsInfo,
moduleGraph,
requestShortener,
@@ -115,9 +116,9 @@ const printExportsInfoToSource = (
if (alreadyPrintedExports) {
source.add(
Template.toComment(
`${Template.toComment(
`${indent}... (${alreadyPrintedExports} already listed exports)`
) + "\n"
)}\n`
);
}
@@ -133,13 +134,13 @@ const printExportsInfoToSource = (
? "other exports"
: "exports";
source.add(
Template.toComment(
`${Template.toComment(
`${indent}${title} [${otherExportsInfo.getProvidedInfo()}] [${otherExportsInfo.getUsedInfo()}]${
target
? ` -> ${target.module.readableIdentifier(requestShortener)}`
: ""
}`
) + "\n"
)}\n`
);
}
}
@@ -155,6 +156,7 @@ class ModuleInfoHeaderPlugin {
constructor(verbose = true) {
this._verbose = verbose;
}
/**
* @param {Compiler} compiler the compiler
* @returns {void}
@@ -162,8 +164,9 @@ class ModuleInfoHeaderPlugin {
apply(compiler) {
const { _verbose: verbose } = this;
compiler.hooks.compilation.tap("ModuleInfoHeaderPlugin", compilation => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModulePackage.tap(
const javascriptHooks =
JavascriptModulesPlugin.getCompilationHooks(compilation);
javascriptHooks.renderModulePackage.tap(
"ModuleInfoHeaderPlugin",
(
moduleSource,
@@ -194,11 +197,7 @@ class ModuleInfoHeaderPlugin {
const source = new ConcatSource();
let header = cacheEntry.header;
if (header === undefined) {
const req = module.readableIdentifier(requestShortener);
const reqStr = req.replace(/\*\//g, "*_/");
const reqStrStar = "*".repeat(reqStr.length);
const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`;
header = new RawSource(headerStr);
header = this.generateHeader(module, requestShortener);
cacheEntry.header = header;
}
source.add(header);
@@ -206,11 +205,11 @@ class ModuleInfoHeaderPlugin {
const exportsType = /** @type {BuildMeta} */ (module.buildMeta)
.exportsType;
source.add(
Template.toComment(
`${Template.toComment(
exportsType
? `${exportsType} exports`
: "unknown exports (runtime-defined)"
) + "\n"
)}\n`
);
if (exportsType) {
const exportsInfo = moduleGraph.getExportsInfo(module);
@@ -223,40 +222,93 @@ class ModuleInfoHeaderPlugin {
);
}
source.add(
Template.toComment(
`${Template.toComment(
`runtime requirements: ${joinIterableWithComma(
chunkGraph.getModuleRuntimeRequirements(module, chunk.runtime)
)}`
) + "\n"
)}\n`
);
const optimizationBailout =
moduleGraph.getOptimizationBailout(module);
if (optimizationBailout) {
for (const text of optimizationBailout) {
let code;
if (typeof text === "function") {
code = text(requestShortener);
} else {
code = text;
}
source.add(Template.toComment(`${code}`) + "\n");
const code =
typeof text === "function" ? text(requestShortener) : text;
source.add(`${Template.toComment(`${code}`)}\n`);
}
}
source.add(moduleSource);
return source;
} else {
source.add(moduleSource);
const cachedSource = new CachedSource(source);
cacheEntry.full.set(moduleSource, cachedSource);
return cachedSource;
}
source.add(moduleSource);
const cachedSource = new CachedSource(source);
cacheEntry.full.set(moduleSource, cachedSource);
return cachedSource;
}
);
hooks.chunkHash.tap("ModuleInfoHeaderPlugin", (chunk, hash) => {
javascriptHooks.chunkHash.tap(
"ModuleInfoHeaderPlugin",
(_chunk, hash) => {
hash.update("ModuleInfoHeaderPlugin");
hash.update("1");
}
);
const cssHooks = CssModulesPlugin.getCompilationHooks(compilation);
cssHooks.renderModulePackage.tap(
"ModuleInfoHeaderPlugin",
(moduleSource, module, { runtimeTemplate }) => {
const { requestShortener } = runtimeTemplate;
let cacheEntry;
let cache = caches.get(requestShortener);
if (cache === undefined) {
caches.set(requestShortener, (cache = new WeakMap()));
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else {
cacheEntry = cache.get(module);
if (cacheEntry === undefined) {
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else if (!verbose) {
const cachedSource = cacheEntry.full.get(moduleSource);
if (cachedSource !== undefined) return cachedSource;
}
}
const source = new ConcatSource();
let header = cacheEntry.header;
if (header === undefined) {
header = this.generateHeader(module, requestShortener);
cacheEntry.header = header;
}
source.add(header);
source.add(moduleSource);
const cachedSource = new CachedSource(source);
cacheEntry.full.set(moduleSource, cachedSource);
return cachedSource;
}
);
cssHooks.chunkHash.tap("ModuleInfoHeaderPlugin", (_chunk, hash) => {
hash.update("ModuleInfoHeaderPlugin");
hash.update("1");
});
});
}
/**
* @param {Module} module the module
* @param {RequestShortener} requestShortener request shortener
* @returns {RawSource} the header
*/
generateHeader(module, requestShortener) {
const req = module.readableIdentifier(requestShortener);
const reqStr = req.replace(/\*\//g, "*_/");
const reqStrStar = "*".repeat(reqStr.length);
const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`;
return new RawSource(headerStr);
}
}
module.exports = ModuleInfoHeaderPlugin;

View File

@@ -16,13 +16,13 @@ const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]);
class ModuleParseError extends WebpackError {
/**
* @param {string | Buffer} source source code
* @param {Error&any} err the parse error
* @param {Error & any} err the parse error
* @param {string[]} loaders the loaders used
* @param {string} type module type
*/
constructor(source, err, loaders, type) {
let message = "Module parse failed: " + (err && err.message);
let loc = undefined;
let message = `Module parse failed: ${err && err.message}`;
let loc;
if (
((Buffer.isBuffer(source) && source.slice(0, 4).equals(WASM_HEADER)) ||
@@ -57,7 +57,7 @@ class ModuleParseError extends WebpackError {
typeof err.loc === "object" &&
typeof err.loc.line === "number"
) {
var lineNumber = err.loc.line;
const lineNumber = err.loc.line;
if (
Buffer.isBuffer(source) ||
@@ -72,15 +72,14 @@ class ModuleParseError extends WebpackError {
const theLine = sourceLines[lineNumber - 1];
const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2);
message +=
linesBefore.map(l => `\n| ${l}`).join("") +
`\n> ${theLine}` +
linesAfter.map(l => `\n| ${l}`).join("");
message += `${linesBefore
.map(l => `\n| ${l}`)
.join("")}\n> ${theLine}${linesAfter.map(l => `\n| ${l}`).join("")}`;
}
loc = { start: err.loc };
} else if (err && err.stack) {
message += "\n" + err.stack;
message += `\n${err.stack}`;
}
super(message);

View File

@@ -17,7 +17,7 @@ class ModuleRestoreError extends WebpackError {
constructor(module, err) {
let message = "Module restore failed: ";
/** @type {string | undefined} */
let details = undefined;
const details = undefined;
if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) {
const stack = err.stack;

View File

@@ -17,7 +17,7 @@ class ModuleStoreError extends WebpackError {
constructor(module, err) {
let message = "Module storing failed: ";
/** @type {string | undefined} */
let details = undefined;
const details = undefined;
if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) {
const stack = err.stack;

View File

@@ -8,6 +8,7 @@
const util = require("util");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
@@ -16,8 +17,14 @@ const memoize = require("./util/memoize");
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
/** @typedef {import("./util/Hash")} Hash */
/**
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
@@ -34,6 +41,11 @@ class ModuleTemplate {
this.hooks = Object.freeze({
content: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -54,6 +66,11 @@ class ModuleTemplate {
},
module: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -74,6 +91,11 @@ class ModuleTemplate {
},
render: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -94,6 +116,11 @@ class ModuleTemplate {
},
package: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
@@ -114,6 +141,11 @@ class ModuleTemplate {
},
hash: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash): void} fn fn
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
@@ -129,7 +161,7 @@ Object.defineProperty(ModuleTemplate.prototype, "runtimeTemplate", {
get: util.deprecate(
/**
* @this {ModuleTemplate}
* @returns {TODO} output options
* @returns {RuntimeTemplate} output options
*/
function () {
return this._runtimeTemplate;

View File

@@ -31,7 +31,6 @@ const JSON_MODULE_TYPE = "json";
/**
* @type {Readonly<"webassembly/async">}
* This is the module type used for WebAssembly modules. In webpack 5 they are always treated as async modules.
*
*/
const WEBASSEMBLY_MODULE_TYPE_ASYNC = "webassembly/async";
@@ -144,26 +143,26 @@ const WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = "lazy-compilation-proxy";
/** @typedef {string} UnknownModuleTypes */
/** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CSSModuleTypes | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */
exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE;
exports.ASSET_MODULE_TYPE_RAW_DATA_URL = ASSET_MODULE_TYPE_RAW_DATA_URL;
exports.ASSET_MODULE_TYPE_SOURCE = ASSET_MODULE_TYPE_SOURCE;
exports.ASSET_MODULE_TYPE_RESOURCE = ASSET_MODULE_TYPE_RESOURCE;
exports.ASSET_MODULE_TYPE_INLINE = ASSET_MODULE_TYPE_INLINE;
exports.JAVASCRIPT_MODULE_TYPE_AUTO = JAVASCRIPT_MODULE_TYPE_AUTO;
exports.JAVASCRIPT_MODULE_TYPE_DYNAMIC = JAVASCRIPT_MODULE_TYPE_DYNAMIC;
exports.JAVASCRIPT_MODULE_TYPE_ESM = JAVASCRIPT_MODULE_TYPE_ESM;
exports.JSON_MODULE_TYPE = JSON_MODULE_TYPE;
exports.WEBASSEMBLY_MODULE_TYPE_ASYNC = WEBASSEMBLY_MODULE_TYPE_ASYNC;
exports.WEBASSEMBLY_MODULE_TYPE_SYNC = WEBASSEMBLY_MODULE_TYPE_SYNC;
exports.CSS_MODULE_TYPE = CSS_MODULE_TYPE;
exports.CSS_MODULE_TYPE_GLOBAL = CSS_MODULE_TYPE_GLOBAL;
exports.CSS_MODULE_TYPE_MODULE = CSS_MODULE_TYPE_MODULE;
exports.CSS_MODULE_TYPE_AUTO = CSS_MODULE_TYPE_AUTO;
exports.WEBPACK_MODULE_TYPE_RUNTIME = WEBPACK_MODULE_TYPE_RUNTIME;
exports.WEBPACK_MODULE_TYPE_FALLBACK = WEBPACK_MODULE_TYPE_FALLBACK;
exports.WEBPACK_MODULE_TYPE_REMOTE = WEBPACK_MODULE_TYPE_REMOTE;
exports.WEBPACK_MODULE_TYPE_PROVIDE = WEBPACK_MODULE_TYPE_PROVIDE;
exports.WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE =
module.exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE;
module.exports.ASSET_MODULE_TYPE_RAW_DATA_URL = ASSET_MODULE_TYPE_RAW_DATA_URL;
module.exports.ASSET_MODULE_TYPE_SOURCE = ASSET_MODULE_TYPE_SOURCE;
module.exports.ASSET_MODULE_TYPE_RESOURCE = ASSET_MODULE_TYPE_RESOURCE;
module.exports.ASSET_MODULE_TYPE_INLINE = ASSET_MODULE_TYPE_INLINE;
module.exports.JAVASCRIPT_MODULE_TYPE_AUTO = JAVASCRIPT_MODULE_TYPE_AUTO;
module.exports.JAVASCRIPT_MODULE_TYPE_DYNAMIC = JAVASCRIPT_MODULE_TYPE_DYNAMIC;
module.exports.JAVASCRIPT_MODULE_TYPE_ESM = JAVASCRIPT_MODULE_TYPE_ESM;
module.exports.JSON_MODULE_TYPE = JSON_MODULE_TYPE;
module.exports.WEBASSEMBLY_MODULE_TYPE_ASYNC = WEBASSEMBLY_MODULE_TYPE_ASYNC;
module.exports.WEBASSEMBLY_MODULE_TYPE_SYNC = WEBASSEMBLY_MODULE_TYPE_SYNC;
module.exports.CSS_MODULE_TYPE = CSS_MODULE_TYPE;
module.exports.CSS_MODULE_TYPE_GLOBAL = CSS_MODULE_TYPE_GLOBAL;
module.exports.CSS_MODULE_TYPE_MODULE = CSS_MODULE_TYPE_MODULE;
module.exports.CSS_MODULE_TYPE_AUTO = CSS_MODULE_TYPE_AUTO;
module.exports.WEBPACK_MODULE_TYPE_RUNTIME = WEBPACK_MODULE_TYPE_RUNTIME;
module.exports.WEBPACK_MODULE_TYPE_FALLBACK = WEBPACK_MODULE_TYPE_FALLBACK;
module.exports.WEBPACK_MODULE_TYPE_REMOTE = WEBPACK_MODULE_TYPE_REMOTE;
module.exports.WEBPACK_MODULE_TYPE_PROVIDE = WEBPACK_MODULE_TYPE_PROVIDE;
module.exports.WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE =
WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE;
exports.WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY =
module.exports.WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY =
WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY;

View File

@@ -20,11 +20,7 @@ class ModuleWarning extends WebpackError {
constructor(warning, { from = null } = {}) {
let message = "Module Warning";
if (from) {
message += ` (from ${from}):\n`;
} else {
message += ": ";
}
message += from ? ` (from ${from}):\n` : ": ";
if (warning && typeof warning === "object" && warning.message) {
message += warning.message;

View File

@@ -91,6 +91,7 @@ module.exports = class MultiCompiler {
const compiler = this.compilers[index];
const compilerIndex = index;
let compilerDone = false;
// eslint-disable-next-line no-loop-func
compiler.hooks.done.tap("MultiCompiler", stats => {
if (!compilerDone) {
compilerDone = true;
@@ -103,6 +104,7 @@ module.exports = class MultiCompiler {
);
}
});
// eslint-disable-next-line no-loop-func
compiler.hooks.invalid.tap("MultiCompiler", () => {
if (compilerDone) {
compilerDone = false;
@@ -172,18 +174,6 @@ module.exports = class MultiCompiler {
throw new Error("Cannot read inputFileSystem of a MultiCompiler");
}
get outputFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
get watchFileSystem() {
throw new Error("Cannot read watchFileSystem of a MultiCompiler");
}
get intermediateFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {InputFileSystem} value the new input file system
*/
@@ -193,6 +183,10 @@ module.exports = class MultiCompiler {
}
}
get outputFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {OutputFileSystem} value the new output file system
*/
@@ -202,6 +196,10 @@ module.exports = class MultiCompiler {
}
}
get watchFileSystem() {
throw new Error("Cannot read watchFileSystem of a MultiCompiler");
}
/**
* @param {WatchFileSystem} value the new watch file system
*/
@@ -220,6 +218,10 @@ module.exports = class MultiCompiler {
}
}
get intermediateFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {string | (function(): string)} name name of the logger, or function called once to get the logger name
* @returns {Logger} a logger with that name
@@ -263,16 +265,11 @@ module.exports = class MultiCompiler {
* @param {{source: Compiler, target: Compiler}} e2 edge 2
* @returns {number} result
*/
const sortEdges = (e1, e2) => {
return (
/** @type {string} */
(e1.source.name).localeCompare(
/** @type {string} */ (e2.source.name)
) ||
/** @type {string} */
(e1.target.name).localeCompare(/** @type {string} */ (e2.target.name))
);
};
const sortEdges = (e1, e2) =>
/** @type {string} */
(e1.source.name).localeCompare(/** @type {string} */ (e2.source.name)) ||
/** @type {string} */
(e1.target.name).localeCompare(/** @type {string} */ (e2.target.name));
for (const source of this.compilers) {
const dependencies = this.dependencies.get(source);
if (dependencies) {
@@ -340,8 +337,8 @@ module.exports = class MultiCompiler {
* @returns {Compiler[]} compilers
*/
const getReadyCompilers = () => {
let readyCompilers = [];
let list = remainingCompilers;
const readyCompilers = [];
const list = remainingCompilers;
remainingCompilers = [];
for (const c of list) {
const dependencies = this.dependencies.get(c);
@@ -514,7 +511,7 @@ module.exports = class MultiCompiler {
/** @type {SetupResult[]} */
const setupResults = [];
nodes.forEach((node, i) => {
for (const [i, node] of nodes.entries()) {
setupResults.push(
(node.setupResult = setup(
node.compiler,
@@ -525,7 +522,7 @@ module.exports = class MultiCompiler {
() => nodeInvalid(node)
))
);
});
}
let processing = true;
const processQueue = () => {
if (processing) return;
@@ -533,6 +530,7 @@ module.exports = class MultiCompiler {
process.nextTick(processQueueWorker);
};
const processQueueWorker = () => {
// eslint-disable-next-line no-unmodified-loop-condition
while (running < parallelism && queue.length > 0 && !errored) {
const node = /** @type {Node} */ (queue.dequeue());
if (

View File

@@ -8,15 +8,25 @@
const identifierUtils = require("./util/identifier");
/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
/** @typedef {import("./Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */
/** @typedef {import("./Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
/** @typedef {import("./Stats")} Stats */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").KnownStatsCompilation} KnownStatsCompilation */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */
/**
* @param {string} str string
* @param {string} prefix pref
* @returns {string} indent
*/
const indent = (str, prefix) => {
const rem = str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
const rem = str.replace(/\n([^\n])/g, `\n${prefix}$1`);
return prefix + rem;
};
/** @typedef {{ version: boolean, hash: boolean, errorsCount: boolean, warningsCount: boolean, errors: boolean, warnings: boolean, children: NormalizedStatsOptions[] }} ChildOptions */
class MultiStats {
/**
* @param {Stats[]} stats the child stats
@@ -43,13 +53,30 @@ class MultiStats {
return this.stats.some(stat => stat.hasWarnings());
}
/**
* @param {string | boolean | StatsOptions | undefined} options stats options
* @param {CreateStatsOptionsContext} context context
* @returns {ChildOptions} context context
*/
_createChildOptions(options, context) {
if (!options) {
options = {};
}
const { children: childrenOptions = undefined, ...baseOptions } =
typeof options === "string" ? { preset: options } : options;
const getCreateStatsOptions = () => {
if (!options) {
options = {};
}
const { children: childrenOptions = undefined, ...baseOptions } =
typeof options === "string"
? { preset: options }
: /** @type {StatsOptions} */ (options);
return { childrenOptions, baseOptions };
};
const children = this.stats.map((stat, idx) => {
if (typeof options === "boolean") {
return stat.compilation.createStatsOptions(options, context);
}
const { childrenOptions, baseOptions } = getCreateStatsOptions();
const childOptions = Array.isArray(childrenOptions)
? childrenOptions[idx]
: childrenOptions;
@@ -77,81 +104,96 @@ class MultiStats {
}
/**
* @param {any} options stats options
* @param {(string | boolean | StatsOptions)=} options stats options
* @returns {StatsCompilation} json output
*/
toJson(options) {
options = this._createChildOptions(options, { forToString: false });
const childOptions = this._createChildOptions(options, {
forToString: false
});
/** @type {KnownStatsCompilation} */
const obj = {};
obj.children = this.stats.map((stat, idx) => {
const obj = stat.toJson(options.children[idx]);
const obj = stat.toJson(childOptions.children[idx]);
const compilationName = stat.compilation.name;
const name =
compilationName &&
identifierUtils.makePathsRelative(
options.context,
stat.compilation.compiler.context,
compilationName,
stat.compilation.compiler.root
);
obj.name = name;
return obj;
});
if (options.version) {
if (childOptions.version) {
obj.version = obj.children[0].version;
}
if (options.hash) {
if (childOptions.hash) {
obj.hash = obj.children.map(j => j.hash).join("");
}
const mapError = (j, obj) => {
return {
...obj,
compilerPath: obj.compilerPath
? `${j.name}.${obj.compilerPath}`
: j.name
};
};
if (options.errors) {
/**
* @param {StatsCompilation} j stats error
* @param {StatsError} obj Stats error
* @returns {TODO} result
*/
const mapError = (j, obj) => ({
...obj,
compilerPath: obj.compilerPath ? `${j.name}.${obj.compilerPath}` : j.name
});
if (childOptions.errors) {
obj.errors = [];
for (const j of obj.children) {
for (const i of j.errors) {
const errors =
/** @type {NonNullable<KnownStatsCompilation["errors"]>} */
(j.errors);
for (const i of errors) {
obj.errors.push(mapError(j, i));
}
}
}
if (options.warnings) {
if (childOptions.warnings) {
obj.warnings = [];
for (const j of obj.children) {
for (const i of j.warnings) {
const warnings =
/** @type {NonNullable<KnownStatsCompilation["warnings"]>} */
(j.warnings);
for (const i of warnings) {
obj.warnings.push(mapError(j, i));
}
}
}
if (options.errorsCount) {
if (childOptions.errorsCount) {
obj.errorsCount = 0;
for (const j of obj.children) {
obj.errorsCount += j.errorsCount;
obj.errorsCount += /** @type {number} */ (j.errorsCount);
}
}
if (options.warningsCount) {
if (childOptions.warningsCount) {
obj.warningsCount = 0;
for (const j of obj.children) {
obj.warningsCount += j.warningsCount;
obj.warningsCount += /** @type {number} */ (j.warningsCount);
}
}
return obj;
}
/**
* @param {(string | boolean | StatsOptions)=} options stats options
* @returns {string} string output
*/
toString(options) {
options = this._createChildOptions(options, { forToString: true });
const childOptions = this._createChildOptions(options, {
forToString: true
});
const results = this.stats.map((stat, idx) => {
const str = stat.toString(options.children[idx]);
const str = stat.toString(childOptions.children[idx]);
const compilationName = stat.compilation.name;
const name =
compilationName &&
identifierUtils
.makePathsRelative(
options.context,
stat.compilation.compiler.context,
compilationName,
stat.compilation.compiler.root
)

View File

@@ -62,7 +62,7 @@ class MultiWatching {
* @returns {void}
*/
close(callback) {
asyncLib.forEach(
asyncLib.each(
this.watchings,
(watching, finishedCallback) => {
watching.close(finishedCallback);

View File

@@ -65,12 +65,13 @@ const memoize = require("./util/memoize");
/** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").UnsafeCacheData} UnsafeCacheData */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./ModuleTypeConstants").JavaScriptModuleTypes} JavaScriptModuleTypes */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */
/** @typedef {import("./Parser")} Parser */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */
@@ -82,12 +83,27 @@ const memoize = require("./util/memoize");
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./util/createHash").Algorithm} Algorithm */
/**
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook
*/
/** @typedef {{[k: string]: any}} ParserOptions */
/** @typedef {{[k: string]: any}} GeneratorOptions */
/** @typedef {UnsafeCacheData & { parser: undefined | Parser, parserOptions: undefined | ParserOptions, generator: undefined | Generator, generatorOptions: undefined | GeneratorOptions }} NormalModuleUnsafeCacheData */
/**
* @template T
* @typedef {import("../declarations/LoaderContext").LoaderContext<T>} LoaderContext
*/
/**
* @template T
* @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} NormalModuleLoaderContext
*/
/**
* @typedef {object} SourceMap
* @property {number} version
@@ -184,11 +200,14 @@ const asBuffer = input => {
};
class NonErrorEmittedError extends WebpackError {
/**
* @param {any} error value which is not an instance of Error
*/
constructor(error) {
super();
this.name = "NonErrorEmittedError";
this.message = "(Emitted value instead of an instance of Error) " + error;
this.message = `(Emitted value instead of an instance of Error) ${error}`;
}
}
@@ -200,12 +219,12 @@ makeSerializable(
/**
* @typedef {object} NormalModuleCompilationHooks
* @property {SyncHook<[object, NormalModule]>} loader
* @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders
* @property {SyncHook<[LoaderContext<any>, NormalModule]>} loader
* @property {SyncHook<[LoaderItem[], NormalModule, LoaderContext<any>]>} beforeLoaders
* @property {SyncHook<[NormalModule]>} beforeParse
* @property {SyncHook<[NormalModule]>} beforeSnapshot
* @property {HookMap<AsyncSeriesBailHook<[string, NormalModule], string | Buffer>>} readResourceForScheme
* @property {HookMap<AsyncSeriesBailHook<[object], string | Buffer>>} readResource
* @property {HookMap<FakeHook<AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>>>} readResourceForScheme
* @property {HookMap<AsyncSeriesBailHook<[LoaderContext<any>], string | Buffer | null>>} readResource
* @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
*/
@@ -251,20 +270,32 @@ class NormalModule extends Module {
beforeSnapshot: new SyncHook(["module"]),
// TODO webpack 6 deprecate
readResourceForScheme: new HookMap(scheme => {
const hook = hooks.readResource.for(scheme);
const hook =
/** @type {NormalModuleCompilationHooks} */
(hooks).readResource.for(scheme);
return createFakeHook(
/** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({
/** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>} */ ({
tap: (options, fn) =>
hook.tap(options, loaderContext =>
fn(loaderContext.resource, loaderContext._module)
fn(
loaderContext.resource,
/** @type {NormalModule} */ (loaderContext._module)
)
),
tapAsync: (options, fn) =>
hook.tapAsync(options, (loaderContext, callback) =>
fn(loaderContext.resource, loaderContext._module, callback)
fn(
loaderContext.resource,
/** @type {NormalModule} */ (loaderContext._module),
callback
)
),
tapPromise: (options, fn) =>
hook.tapPromise(options, loaderContext =>
fn(loaderContext.resource, loaderContext._module)
fn(
loaderContext.resource,
/** @type {NormalModule} */ (loaderContext._module)
)
)
})
);
@@ -343,7 +374,7 @@ class NormalModule extends Module {
this._source = null;
/**
* @private
* @type {Map<string, number> | undefined}
* @type {Map<string | undefined, number> | undefined}
*/
this._sourceSizes = undefined;
/**
@@ -369,12 +400,10 @@ class NormalModule extends Module {
if (this.layer === null) {
if (this.type === JAVASCRIPT_MODULE_TYPE_AUTO) {
return this.request;
} else {
return `${this.type}|${this.request}`;
}
} else {
return `${this.type}|${this.request}|${this.layer}`;
return `${this.type}|${this.request}`;
}
return `${this.type}|${this.request}|${this.layer}`;
}
/**
@@ -382,7 +411,7 @@ class NormalModule extends Module {
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return requestShortener.shorten(this.userRequest);
return /** @type {string} */ (requestShortener.shorten(this.userRequest));
}
/**
@@ -556,30 +585,36 @@ class NormalModule extends Module {
/**
* @returns {ResolveContext} resolve context
*/
const getResolveContext = () => {
return {
fileDependencies: {
add: d => /** @type {TODO} */ (loaderContext).addDependency(d)
},
contextDependencies: {
add: d => /** @type {TODO} */ (loaderContext).addContextDependency(d)
},
missingDependencies: {
add: d => /** @type {TODO} */ (loaderContext).addMissingDependency(d)
}
};
};
const getResolveContext = () => ({
fileDependencies: {
add: d => /** @type {TODO} */ (loaderContext).addDependency(d)
},
contextDependencies: {
add: d => /** @type {TODO} */ (loaderContext).addContextDependency(d)
},
missingDependencies: {
add: d => /** @type {TODO} */ (loaderContext).addMissingDependency(d)
}
});
const getAbsolutify = memoize(() =>
absolutify.bindCache(compilation.compiler.root)
);
const getAbsolutifyInContext = memoize(() =>
absolutify.bindContextCache(this.context, compilation.compiler.root)
absolutify.bindContextCache(
/** @type {string} */
(this.context),
compilation.compiler.root
)
);
const getContextify = memoize(() =>
contextify.bindCache(compilation.compiler.root)
);
const getContextifyInContext = memoize(() =>
contextify.bindContextCache(this.context, compilation.compiler.root)
contextify.bindContextCache(
/** @type {string} */
(this.context),
compilation.compiler.root
)
);
const utils = {
/**
@@ -587,28 +622,29 @@ class NormalModule extends Module {
* @param {string} request request
* @returns {string} result
*/
absolutify: (context, request) => {
return context === this.context
absolutify: (context, request) =>
context === this.context
? getAbsolutifyInContext()(request)
: getAbsolutify()(context, request);
},
: getAbsolutify()(context, request),
/**
* @param {string} context context
* @param {string} request request
* @returns {string} result
*/
contextify: (context, request) => {
return context === this.context
contextify: (context, request) =>
context === this.context
? getContextifyInContext()(request)
: getContextify()(context, request);
},
: getContextify()(context, request),
/**
* @param {(string | typeof import("./util/Hash"))=} type type
* @returns {Hash} hash
*/
createHash: type => {
return createHash(type || compilation.outputOptions.hashFunction);
}
createHash: type =>
createHash(
type ||
/** @type {Algorithm} */
(compilation.outputOptions.hashFunction)
)
};
/** @type {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} */
const loaderContext = {
@@ -622,8 +658,10 @@ class NormalModule extends Module {
if (options.startsWith("{") && options.endsWith("}")) {
try {
options = parseJson(options);
} catch (e) {
throw new Error(`Cannot parse string options: ${e.message}`);
} catch (err) {
throw new Error(
`Cannot parse string options: ${/** @type {Error} */ (err).message}`
);
}
} else {
options = querystring.parse(options, "&", "=", {
@@ -738,17 +776,21 @@ class NormalModule extends Module {
utils,
rootContext: /** @type {string} */ (options.context),
webpack: true,
sourceMap: !!this.useSourceMap,
sourceMap: Boolean(this.useSourceMap),
mode: options.mode || "production",
hashFunction: /** @type {TODO} */ (options.output.hashFunction),
hashDigest: /** @type {string} */ (options.output.hashDigest),
hashDigestLength: /** @type {number} */ (options.output.hashDigestLength),
hashSalt: /** @type {string} */ (options.output.hashSalt),
_module: this,
_compilation: compilation,
_compiler: compilation.compiler,
fs: fs
fs
};
Object.assign(loaderContext, options.loader);
hooks.loader.call(loaderContext, this);
hooks.loader.call(/** @type {LoaderContext<any>} */ (loaderContext), this);
return loaderContext;
}
@@ -775,7 +817,7 @@ class NormalModule extends Module {
/**
* @param {string} context the compilation context
* @param {string | Buffer} content the content
* @param {(string | SourceMapSource)=} sourceMap an optional source map
* @param {(string | SourceMapSource | null)=} sourceMap an optional source map
* @param {object=} associatedObjectForCache object for caching
* @returns {Source} the created source
*/
@@ -832,7 +874,14 @@ class NormalModule extends Module {
hooks
);
const processResult = (err, result) => {
/** @typedef {[string | Buffer, string | SourceMapSource, Record<string, any>]} Result */
/**
* @param {Error | null} err err
* @param {(Result | null)=} _result result
* @returns {void}
*/
const processResult = (err, _result) => {
if (err) {
if (!(err instanceof Error)) {
err = new NonErrorEmittedError(err);
@@ -848,6 +897,7 @@ class NormalModule extends Module {
return callback(error);
}
const result = /** @type {Result} */ (_result);
const source = result[0];
const sourceMap = result.length >= 1 ? result[1] : null;
const extraInfo = result.length >= 2 ? result[2] : null;
@@ -896,9 +946,13 @@ class NormalModule extends Module {
buildInfo.cacheable = true;
try {
hooks.beforeLoaders.call(this.loaders, this, loaderContext);
hooks.beforeLoaders.call(
this.loaders,
this,
/** @type {LoaderContext<any>} */ (loaderContext)
);
} catch (err) {
processResult(err);
processResult(/** @type {Error} */ (err));
return;
}
@@ -912,6 +966,11 @@ class NormalModule extends Module {
resource: this.resource,
loaders: this.loaders,
context: loaderContext,
/**
* @param {LoaderContext<TODO>} loaderContext the loader context
* @param {string} resourcePath the resource Path
* @param {(err: Error | null, result?: string | Buffer) => void} callback callback
*/
processResource: (loaderContext, resourcePath, callback) => {
const resource = loaderContext.resource;
const scheme = getScheme(resource);
@@ -920,7 +979,13 @@ class NormalModule extends Module {
.callAsync(loaderContext, (err, result) => {
if (err) return callback(err);
if (typeof result !== "string" && !result) {
return callback(new UnhandledSchemeError(scheme, resource));
return callback(
new UnhandledSchemeError(
/** @type {string} */
(scheme),
resource
)
);
}
return callback(null, result);
});
@@ -1037,7 +1102,10 @@ class NormalModule extends Module {
* @private
*/
_initBuildHash(compilation) {
const hash = createHash(compilation.outputOptions.hashFunction);
const hash = createHash(
/** @type {Algorithm} */
(compilation.outputOptions.hashFunction)
);
if (this._source) {
hash.update("source");
this._source.updateHash(hash);
@@ -1128,7 +1196,7 @@ class NormalModule extends Module {
try {
hooks.beforeSnapshot.call(this);
} catch (err) {
this.markModuleAsErrored(err);
this.markModuleAsErrored(/** @type {WebpackError} */ (err));
return callback();
}
@@ -1140,7 +1208,7 @@ class NormalModule extends Module {
// add warning for all non-absolute paths in fileDependencies, etc
// This makes it easier to find problems with watching and/or caching
/** @type {undefined | Set<string>} */
let nonAbsoluteDependencies = undefined;
let nonAbsoluteDependencies;
/**
* @param {LazySet<string>} deps deps
*/
@@ -1155,7 +1223,8 @@ class NormalModule extends Module {
const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, "");
const absolute = join(
compilation.fileSystemInfo.fs,
this.context,
/** @type {string} */
(this.context),
depWithoutGlob
);
if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) {
@@ -1168,7 +1237,7 @@ class NormalModule extends Module {
: deps
).add(absolute);
}
} catch (e) {
} catch (_err) {
// ignore
}
}
@@ -1218,7 +1287,7 @@ class NormalModule extends Module {
try {
hooks.beforeParse.call(this);
} catch (err) {
this.markModuleAsErrored(err);
this.markModuleAsErrored(/** @type {WebpackError} */ (err));
this._initBuildHash(compilation);
return callback();
}
@@ -1241,11 +1310,11 @@ class NormalModule extends Module {
source,
current: this,
module: this,
compilation: compilation,
options: options
compilation,
options
});
} catch (e) {
handleParseError(/** @type {Error} */ (e));
} catch (parseErr) {
handleParseError(/** @type {Error} */ (parseErr));
return;
}
handleParseResult();
@@ -1305,9 +1374,8 @@ class NormalModule extends Module {
// When caching is implemented here, make sure to not cache when
// at least one circular connection was in the loop above
return current;
} else {
return true;
}
return true;
}
/**
@@ -1348,15 +1416,13 @@ class NormalModule extends Module {
}
/** @type {function(): Map<string, any>} */
const getData = () => {
return this._codeGeneratorData;
};
const getData = () => this._codeGeneratorData;
const sources = new Map();
for (const type of sourceTypes || chunkGraph.getModuleSourceTypes(this)) {
const source = this.error
? new RawSource(
"throw new Error(" + JSON.stringify(this.error.message) + ");"
`throw new Error(${JSON.stringify(this.error.message)});`
)
: /** @type {Generator} */ (this.generator).generate(this, {
dependencyTemplates,
@@ -1453,7 +1519,7 @@ class NormalModule extends Module {
)
);
}
callback(null, !!needBuild);
callback(null, Boolean(needBuild));
});
});
}
@@ -1519,7 +1585,8 @@ class NormalModule extends Module {
*/
updateHash(hash, context) {
hash.update(/** @type {BuildInfo} */ (this.buildInfo).hash);
this.generator.updateHash(hash, {
/** @type {Generator} */
(this.generator).updateHash(hash, {
module: this,
...context
});
@@ -1540,24 +1607,28 @@ class NormalModule extends Module {
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
* @returns {TODO} Module
*/
static deserialize(context) {
const obj = new NormalModule({
// will be deserialized by Module
layer: null,
layer: /** @type {EXPECTED_ANY} */ (null),
type: "",
// will be filled by updateCacheModule
resource: "",
context: "",
request: null,
userRequest: null,
rawRequest: null,
loaders: null,
matchResource: null,
parser: null,
parserOptions: null,
generator: null,
generatorOptions: null,
resolveOptions: null
request: /** @type {EXPECTED_ANY} */ (null),
userRequest: /** @type {EXPECTED_ANY} */ (null),
rawRequest: /** @type {EXPECTED_ANY} */ (null),
loaders: /** @type {EXPECTED_ANY} */ (null),
matchResource: /** @type {EXPECTED_ANY} */ (null),
parser: /** @type {EXPECTED_ANY} */ (null),
parserOptions: /** @type {EXPECTED_ANY} */ (null),
generator: /** @type {EXPECTED_ANY} */ (null),
generatorOptions: /** @type {EXPECTED_ANY} */ (null),
resolveOptions: /** @type {EXPECTED_ANY} */ (null)
});
obj.deserialize(context);
return obj;

View File

@@ -52,8 +52,8 @@ const {
/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {Pick<RuleSetRule, 'type'|'sideEffects'|'parser'|'generator'|'resolve'|'layer'>} ModuleSettings */
/** @typedef {Partial<NormalModuleCreateData & {settings: ModuleSettings}>} CreateData */
/** @typedef {Pick<RuleSetRule, 'type' | 'sideEffects' | 'parser' | 'generator' | 'resolve' | 'layer'>} ModuleSettings */
/** @typedef {Partial<NormalModuleCreateData & { settings: ModuleSettings }>} CreateData */
/**
* @typedef {object} ResolveData
@@ -68,6 +68,7 @@ const {
* @property {LazySet<string>} fileDependencies
* @property {LazySet<string>} missingDependencies
* @property {LazySet<string>} contextDependencies
* @property {Module=} ignoredModule
* @property {boolean} cacheable allow to use the unsafe cache
*/
@@ -116,15 +117,15 @@ const loaderToIdent = data => {
return data.loader;
}
if (typeof data.options === "string") {
return data.loader + "?" + data.options;
return `${data.loader}?${data.options}`;
}
if (typeof data.options !== "object") {
throw new Error("loader options must be string or object");
}
if (data.ident) {
return data.loader + "??" + data.ident;
return `${data.loader}??${data.ident}`;
}
return data.loader + "?" + JSON.stringify(data.options);
return `${data.loader}?${JSON.stringify(data.options)}`;
};
/**
@@ -135,7 +136,7 @@ const loaderToIdent = data => {
const stringifyLoadersAndResource = (loaders, resource) => {
let str = "";
for (const loader of loaders) {
str += loaderToIdent(loader) + "!";
str += `${loaderToIdent(loader)}!`;
}
return str + resource;
};
@@ -145,16 +146,14 @@ const stringifyLoadersAndResource = (loaders, resource) => {
* @param {(err?: null | Error) => void} callback callback
* @returns {(err?: null | Error) => void} callback
*/
const needCalls = (times, callback) => {
return err => {
if (--times === 0) {
return callback(err);
}
if (err && times > 0) {
times = NaN;
return callback(err);
}
};
const needCalls = (times, callback) => err => {
if (--times === 0) {
return callback(err);
}
if (err && times > 0) {
times = Number.NaN;
return callback(err);
}
};
/**
@@ -171,20 +170,18 @@ const mergeGlobalOptions = (globalOptions, type, localOptions) => {
let current = "";
for (const part of parts) {
current = current ? `${current}/${part}` : part;
const options = globalOptions[current];
const options =
/** @type {T} */
(globalOptions[/** @type {keyof T} */ (current)]);
if (typeof options === "object") {
if (result === undefined) {
result = options;
} else {
result = cachedCleverMerge(result, options);
}
result =
result === undefined ? options : cachedCleverMerge(result, options);
}
}
if (result === undefined) {
return localOptions;
} else {
return cachedCleverMerge(result, localOptions);
}
return cachedCleverMerge(result, localOptions);
};
// TODO webpack 6 remove
@@ -200,9 +197,7 @@ const deprecationChangedHookMessage = (name, hook) => {
* @param {TODO} tapped tapped
* @returns {string} name
*/
tapped => {
return tapped.name;
}
tapped => tapped.name
)
.join(", ");
@@ -227,16 +222,19 @@ const ruleSetCompiler = new RuleSetCompiler([
new BasicMatcherRulePlugin("issuer"),
new BasicMatcherRulePlugin("compiler"),
new BasicMatcherRulePlugin("issuerLayer"),
new ObjectMatcherRulePlugin(
"assert",
"assertions",
value => value && /** @type {any} */ (value)._isLegacyAssert !== undefined
),
new ObjectMatcherRulePlugin(
"with",
"assertions",
value => value && !(/** @type {any} */ (value)._isLegacyAssert)
),
new ObjectMatcherRulePlugin("assert", "assertions", value => {
if (value) {
return /** @type {any} */ (value)._isLegacyAssert !== undefined;
}
return false;
}),
new ObjectMatcherRulePlugin("with", "assertions", value => {
if (value) {
return !(/** @type {any} */ (value)._isLegacyAssert);
}
return false;
}),
new ObjectMatcherRulePlugin("descriptionData"),
new BasicEffectRulePlugin("type"),
new BasicEffectRulePlugin("sideEffects"),
@@ -254,7 +252,7 @@ class NormalModuleFactory extends ModuleFactory {
* @param {InputFileSystem} param.fs file system
* @param {ResolverFactory} param.resolverFactory resolverFactory
* @param {ModuleOptions} param.options options
* @param {object=} param.associatedObjectForCache an object to which the cache will be attached
* @param {object} param.associatedObjectForCache an object to which the cache will be attached
* @param {boolean=} param.layers enable layers
*/
constructor({
@@ -285,13 +283,13 @@ class NormalModuleFactory extends ModuleFactory {
afterResolve: new AsyncSeriesBailHook(["resolveData"]),
/** @type {AsyncSeriesBailHook<[ResolveData["createData"], ResolveData], Module | void>} */
createModule: new AsyncSeriesBailHook(["createData", "resolveData"]),
/** @type {SyncWaterfallHook<[Module, ResolveData["createData"], ResolveData], Module>} */
/** @type {SyncWaterfallHook<[Module, ResolveData["createData"], ResolveData]>} */
module: new SyncWaterfallHook(["module", "createData", "resolveData"]),
/** @type {HookMap<SyncBailHook<[ParserOptions], Parser>>} */
/** @type {HookMap<SyncBailHook<[ParserOptions], Parser | void>>} */
createParser: new HookMap(() => new SyncBailHook(["parserOptions"])),
/** @type {HookMap<SyncBailHook<[TODO, ParserOptions], void>>} */
parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])),
/** @type {HookMap<SyncBailHook<[GeneratorOptions], Generator>>} */
/** @type {HookMap<SyncBailHook<[GeneratorOptions], Generator | void>>} */
createGenerator: new HookMap(
() => new SyncBailHook(["generatorOptions"])
),
@@ -299,7 +297,7 @@ class NormalModuleFactory extends ModuleFactory {
generator: new HookMap(
() => new SyncHook(["generator", "generatorOptions"])
),
/** @type {HookMap<SyncBailHook<[TODO, ResolveData], Module>>} */
/** @type {HookMap<SyncBailHook<[TODO, ResolveData], Module | void>>} */
createModuleClass: new HookMap(
() => new SyncBailHook(["createData", "resolveData"])
)
@@ -348,8 +346,10 @@ class NormalModuleFactory extends ModuleFactory {
if (typeof result === "object")
throw new Error(
deprecationChangedHookMessage("resolve", this.hooks.resolve) +
" Returning a Module object will result in this module used as result."
`${deprecationChangedHookMessage(
"resolve",
this.hooks.resolve
)} Returning a Module object will result in this module used as result.`
);
this.hooks.afterResolve.callAsync(resolveData, (err, result) => {
@@ -380,14 +380,16 @@ class NormalModuleFactory extends ModuleFactory {
// TODO webpack 6 make it required and move javascript/wasm/asset properties to own module
createdModule = this.hooks.createModuleClass
.for(
/** @type {ModuleSettings} */ (createData.settings).type
/** @type {ModuleSettings} */
(createData.settings).type
)
.call(createData, resolveData);
if (!createdModule) {
createdModule = /** @type {Module} */ (
new NormalModule(
/** @type {NormalModuleCreateData} */ (createData)
/** @type {NormalModuleCreateData} */
(createData)
)
);
}
@@ -427,7 +429,7 @@ class NormalModuleFactory extends ModuleFactory {
const loaderResolver = this.getResolver("loader");
/** @type {ResourceData | undefined} */
let matchResourceData = undefined;
let matchResourceData;
/** @type {string} */
let unresolvedResource;
/** @type {ParsedLoaderRequest[]} */
@@ -538,8 +540,8 @@ class NormalModuleFactory extends ModuleFactory {
item.ident = ident;
}
}
} catch (e) {
return callback(/** @type {Error} */ (e));
} catch (identErr) {
return callback(/** @type {Error} */ (identErr));
}
if (!resourceData) {
@@ -617,10 +619,15 @@ class NormalModuleFactory extends ModuleFactory {
} else if (
typeof r.value === "object" &&
r.value !== null &&
typeof settings[r.type] === "object" &&
settings[r.type] !== null
typeof settings[
/** @type {keyof ModuleSettings} */ (r.type)
] === "object" &&
settings[/** @type {keyof ModuleSettings} */ (r.type)] !== null
) {
settings[r.type] = cachedCleverMerge(settings[r.type], r.value);
settings[r.type] = cachedCleverMerge(
settings[/** @type {keyof ModuleSettings} */ (r.type)],
r.value
);
} else {
settings[r.type] = r.value;
}
@@ -652,7 +659,7 @@ class NormalModuleFactory extends ModuleFactory {
}
for (const loader of /** @type {LoaderItem[]} */ (preLoaders))
allLoaders.push(loader);
let type = /** @type {string} */ (settings.type);
const type = /** @type {string} */ (settings.type);
const resolveOptions = settings.resolve;
const layer = settings.layer;
if (layer !== undefined && !layers) {
@@ -688,8 +695,8 @@ class NormalModuleFactory extends ModuleFactory {
generatorOptions: settings.generator,
resolveOptions
});
} catch (e) {
return callback(/** @type {Error} */ (e));
} catch (createDataErr) {
return callback(/** @type {Error} */ (createDataErr));
}
callback();
});
@@ -772,12 +779,17 @@ class NormalModuleFactory extends ModuleFactory {
unresolvedResource,
normalResolver,
resolveContext,
(err, resolvedResource, resolvedResourceResolveData) => {
(err, _resolvedResource, resolvedResourceResolveData) => {
if (err) return continueCallback(err);
if (resolvedResource !== false) {
if (_resolvedResource !== false) {
const resolvedResource =
/** @type {string} */
(_resolvedResource);
resourceData = {
resource: resolvedResource,
data: resolvedResourceResolveData,
data:
/** @type {ResolveRequest} */
(resolvedResourceResolveData),
...cacheParseResource(resolvedResource)
};
}
@@ -883,12 +895,19 @@ class NormalModuleFactory extends ModuleFactory {
// Ignored
if (result === false) {
return callback(null, {
/** @type {ModuleFactoryResult} * */
const factoryResult = {
fileDependencies,
missingDependencies,
contextDependencies,
cacheable: resolveData.cacheable
});
};
if (resolveData.ignoredModule) {
factoryResult.module = resolveData.ignoredModule;
}
return callback(null, factoryResult);
}
if (typeof result === "object")
@@ -909,6 +928,7 @@ class NormalModuleFactory extends ModuleFactory {
});
}
/** @type {ModuleFactoryResult} * */
const factoryResult = {
module,
fileDependencies,
@@ -1066,13 +1086,12 @@ Add the extension to the request.`
/(\.[^.]+)(\?|$)/,
"$2"
);
if (resolver.options.extensions.has(match[1])) {
hint = `Did you mean '${fixedRequest}'?`;
} else {
hint = `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`;
}
hint = resolver.options.extensions.has(match[1])
? `Did you mean '${fixedRequest}'?`
: `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`;
} else {
hint = `Did you mean to omit the extension or to remove 'resolve.enforceExtension'?`;
hint =
"Did you mean to omit the extension or to remove 'resolve.enforceExtension'?";
}
return callback(
null,
@@ -1151,18 +1170,17 @@ If changing the source code is not an option there is also a resolve options cal
if (
err &&
/^[^/]*$/.test(item.loader) &&
!/-loader$/.test(item.loader)
!item.loader.endsWith("-loader")
) {
return resolver.resolve(
contextInfo,
context,
item.loader + "-loader",
`${item.loader}-loader`,
resolveContext,
err2 => {
if (!err2) {
err.message =
err.message +
"\n" +
`${err.message}\n` +
"BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" +
` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` +
" see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed";
@@ -1173,7 +1191,9 @@ If changing the source code is not an option there is also a resolve options cal
}
if (err) return callback(err);
const parsedResult = this._parseResourceWithoutFragment(result);
const parsedResult = this._parseResourceWithoutFragment(
/** @type {string} */ (result)
);
const type = /\.mjs$/i.test(parsedResult.path)
? "module"

View File

@@ -5,6 +5,6 @@
"use strict";
exports.STAGE_BASIC = -10;
exports.STAGE_DEFAULT = 0;
exports.STAGE_ADVANCED = 10;
module.exports.STAGE_BASIC = -10;
module.exports.STAGE_DEFAULT = 0;
module.exports.STAGE_ADVANCED = 10;

View File

@@ -5,7 +5,18 @@
"use strict";
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./Compiler")} Compiler */
class OptionsApply {
process(options, compiler) {}
/**
* @param {WebpackOptions} options options object
* @param {Compiler} compiler compiler object
* @returns {WebpackOptions} options object
*/
process(options, compiler) {
return options;
}
}
module.exports = OptionsApply;

View File

@@ -15,11 +15,18 @@ const { contextify } = require("./util/identifier");
/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */
/** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./logging/Logger").Logger} Logger */
/**
* @template T, K, R
* @typedef {import("./util/AsyncQueue")<T, K, R>} AsyncQueue
*/
/**
* @typedef {object} CountsData
* @property {number} modulesCount modules count
@@ -41,9 +48,7 @@ const validate = createSchemaValidation(
* @param {number} c c
* @returns {number} median
*/
const median3 = (a, b, c) => {
return a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
};
const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
/**
* @param {boolean | null | undefined} profile need profile
@@ -78,11 +83,12 @@ const createDefaultHandler = (profile, logger) => {
if (lastStateItem.value) {
let reportState = lastStateItem.value;
if (i > 0) {
reportState = lastStateInfo[i - 1].value + " > " + reportState;
reportState = `${lastStateInfo[i - 1].value} > ${reportState}`;
}
const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`;
const d = diff;
// This depends on timing so we ignore it for coverage
/* eslint-disable no-lone-blocks */
/* istanbul ignore next */
{
if (d > 10000) {
@@ -97,6 +103,7 @@ const createDefaultHandler = (profile, logger) => {
logger.debug(stateMsg);
}
}
/* eslint-enable no-lone-blocks */
}
if (stateItem === undefined) {
lastStateInfo.length = i;
@@ -121,6 +128,8 @@ const createDefaultHandler = (profile, logger) => {
return defaultHandler;
};
const SKIPPED_QUEUE_CONTEXTS = ["import-module", "load-module"];
/**
* @callback ReportProgress
* @param {number} p percentage
@@ -191,14 +200,14 @@ class ProgressPlugin {
const states = compiler.compilers.map(
() => /** @type {[number, ...string[]]} */ ([0])
);
compiler.compilers.forEach((compiler, idx) => {
for (const [idx, item] of compiler.compilers.entries()) {
new ProgressPlugin((p, msg, ...args) => {
states[idx] = [p, msg, ...args];
let sum = 0;
for (const [p] of states) sum += p;
handler(sum / states.length, `[${idx}] ${msg}`, ...args);
}).apply(compiler);
});
}).apply(item);
}
}
/**
@@ -217,7 +226,9 @@ class ProgressPlugin {
let lastDependenciesCount = 0;
let lastEntriesCount = 0;
let modulesCount = 0;
let skippedModulesCount = 0;
let dependenciesCount = 0;
let skippedDependenciesCount = 0;
let entriesCount = 1;
let doneModules = 0;
let doneDependencies = 0;
@@ -298,7 +309,15 @@ class ProgressPlugin {
lastUpdate = Date.now();
};
const factorizeAdd = () => {
/**
* @template T
* @param {AsyncQueue<FactorizeModuleOptions, string, Module | ModuleFactoryResult>} factorizeQueue async queue
* @param {T} _item item
*/
const factorizeAdd = (factorizeQueue, _item) => {
if (SKIPPED_QUEUE_CONTEXTS.includes(factorizeQueue.getContext())) {
skippedDependenciesCount++;
}
dependenciesCount++;
if (dependenciesCount < 50 || dependenciesCount % 100 === 0)
updateThrottled();
@@ -310,7 +329,15 @@ class ProgressPlugin {
updateThrottled();
};
const moduleAdd = () => {
/**
* @template T
* @param {AsyncQueue<Module, string, Module>} addModuleQueue async queue
* @param {T} _item item
*/
const moduleAdd = (addModuleQueue, _item) => {
if (SKIPPED_QUEUE_CONTEXTS.includes(addModuleQueue.getContext())) {
skippedModulesCount++;
}
modulesCount++;
if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled();
};
@@ -397,12 +424,19 @@ class ProgressPlugin {
if (compilation.compiler.isChild()) return Promise.resolve();
return /** @type {Promise<CountsData>} */ (cacheGetPromise).then(
async oldData => {
const realModulesCount = modulesCount - skippedModulesCount;
const realDependenciesCount =
dependenciesCount - skippedDependenciesCount;
if (
!oldData ||
oldData.modulesCount !== modulesCount ||
oldData.dependenciesCount !== dependenciesCount
oldData.modulesCount !== realModulesCount ||
oldData.dependenciesCount !== realDependenciesCount
) {
await cache.storePromise({ modulesCount, dependenciesCount });
await cache.storePromise({
modulesCount: realModulesCount,
dependenciesCount: realDependenciesCount
});
}
}
);
@@ -413,19 +447,25 @@ class ProgressPlugin {
lastModulesCount = modulesCount;
lastEntriesCount = entriesCount;
lastDependenciesCount = dependenciesCount;
modulesCount = dependenciesCount = entriesCount = 0;
modulesCount =
skippedModulesCount =
dependenciesCount =
skippedDependenciesCount =
entriesCount =
0;
doneModules = doneDependencies = doneEntries = 0;
compilation.factorizeQueue.hooks.added.tap(
"ProgressPlugin",
factorizeAdd
compilation.factorizeQueue.hooks.added.tap("ProgressPlugin", item =>
factorizeAdd(compilation.factorizeQueue, item)
);
compilation.factorizeQueue.hooks.result.tap(
"ProgressPlugin",
factorizeDone
);
compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", moduleAdd);
compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", item =>
moduleAdd(compilation.addModuleQueue, item)
);
compilation.processDependenciesQueue.hooks.result.tap(
"ProgressPlugin",
moduleDone
@@ -507,7 +547,7 @@ class ProgressPlugin {
afterSeal: "after seal"
};
const numberOfHooks = Object.keys(hooks).length;
Object.keys(hooks).forEach((name, idx) => {
for (const [idx, name] of Object.keys(hooks).entries()) {
const title = hooks[/** @type {keyof typeof hooks} */ (name)];
const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({
@@ -534,7 +574,7 @@ class ProgressPlugin {
handler(percentage, "sealing", title, tap.name);
}
});
});
}
});
compiler.hooks.make.intercept({
name: "ProgressPlugin",

View File

@@ -58,16 +58,16 @@ class ProvidePlugin {
* @returns {void}
*/
const handler = (parser, parserOptions) => {
Object.keys(definitions).forEach(name => {
for (const name of Object.keys(definitions)) {
const request =
/** @type {string[]} */
([]).concat(definitions[name]);
const splittedName = name.split(".");
if (splittedName.length > 0) {
splittedName.slice(1).forEach((_, i) => {
for (const [i, _] of splittedName.slice(1).entries()) {
const name = splittedName.slice(0, i + 1).join(".");
parser.hooks.canRename.for(name).tap(PLUGIN_NAME, approve);
});
}
}
parser.hooks.expression.for(name).tap(PLUGIN_NAME, expr => {
@@ -100,7 +100,7 @@ class ProvidePlugin {
parser.walkExpressions(expr.arguments);
return true;
});
});
}
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)

View File

@@ -7,6 +7,7 @@
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const makeSerializable = require("./util/makeSerializable");
@@ -16,11 +17,11 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
@@ -30,8 +31,6 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const TYPES = new Set(["javascript"]);
class RawModule extends Module {
/**
* @param {string} source source code
@@ -51,7 +50,7 @@ class RawModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
return JS_TYPES;
}
/**

View File

@@ -8,157 +8,158 @@
/**
* the internal require function
*/
exports.require = "__webpack_require__";
module.exports.require = "__webpack_require__";
/**
* access to properties of the internal require function/object
*/
exports.requireScope = "__webpack_require__.*";
module.exports.requireScope = "__webpack_require__.*";
/**
* the internal exports object
*/
exports.exports = "__webpack_exports__";
module.exports.exports = "__webpack_exports__";
/**
* top-level this need to be the exports object
*/
exports.thisAsExports = "top-level-this-exports";
module.exports.thisAsExports = "top-level-this-exports";
/**
* runtime need to return the exports of the last entry module
*/
exports.returnExportsFromRuntime = "return-exports-from-runtime";
module.exports.returnExportsFromRuntime = "return-exports-from-runtime";
/**
* the internal module object
*/
exports.module = "module";
module.exports.module = "module";
/**
* the internal module object
*/
exports.moduleId = "module.id";
module.exports.moduleId = "module.id";
/**
* the internal module object
*/
exports.moduleLoaded = "module.loaded";
module.exports.moduleLoaded = "module.loaded";
/**
* the bundle public path
*/
exports.publicPath = "__webpack_require__.p";
module.exports.publicPath = "__webpack_require__.p";
/**
* the module id of the entry point
*/
exports.entryModuleId = "__webpack_require__.s";
module.exports.entryModuleId = "__webpack_require__.s";
/**
* the module cache
*/
exports.moduleCache = "__webpack_require__.c";
module.exports.moduleCache = "__webpack_require__.c";
/**
* the module functions
*/
exports.moduleFactories = "__webpack_require__.m";
module.exports.moduleFactories = "__webpack_require__.m";
/**
* the module functions, with only write access
*/
exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)";
module.exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)";
/**
* the chunk ensure function
*/
exports.ensureChunk = "__webpack_require__.e";
module.exports.ensureChunk = "__webpack_require__.e";
/**
* an object with handlers to ensure a chunk
*/
exports.ensureChunkHandlers = "__webpack_require__.f";
module.exports.ensureChunkHandlers = "__webpack_require__.f";
/**
* a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries
*/
exports.ensureChunkIncludeEntries = "__webpack_require__.f (include entries)";
module.exports.ensureChunkIncludeEntries =
"__webpack_require__.f (include entries)";
/**
* the chunk prefetch function
*/
exports.prefetchChunk = "__webpack_require__.E";
module.exports.prefetchChunk = "__webpack_require__.E";
/**
* an object with handlers to prefetch a chunk
*/
exports.prefetchChunkHandlers = "__webpack_require__.F";
module.exports.prefetchChunkHandlers = "__webpack_require__.F";
/**
* the chunk preload function
*/
exports.preloadChunk = "__webpack_require__.G";
module.exports.preloadChunk = "__webpack_require__.G";
/**
* an object with handlers to preload a chunk
*/
exports.preloadChunkHandlers = "__webpack_require__.H";
module.exports.preloadChunkHandlers = "__webpack_require__.H";
/**
* the exported property define getters function
*/
exports.definePropertyGetters = "__webpack_require__.d";
module.exports.definePropertyGetters = "__webpack_require__.d";
/**
* define compatibility on export
*/
exports.makeNamespaceObject = "__webpack_require__.r";
module.exports.makeNamespaceObject = "__webpack_require__.r";
/**
* create a fake namespace object
*/
exports.createFakeNamespaceObject = "__webpack_require__.t";
module.exports.createFakeNamespaceObject = "__webpack_require__.t";
/**
* compatibility get default export
*/
exports.compatGetDefaultExport = "__webpack_require__.n";
module.exports.compatGetDefaultExport = "__webpack_require__.n";
/**
* harmony module decorator
*/
exports.harmonyModuleDecorator = "__webpack_require__.hmd";
module.exports.harmonyModuleDecorator = "__webpack_require__.hmd";
/**
* node.js module decorator
*/
exports.nodeModuleDecorator = "__webpack_require__.nmd";
module.exports.nodeModuleDecorator = "__webpack_require__.nmd";
/**
* the webpack hash
*/
exports.getFullHash = "__webpack_require__.h";
module.exports.getFullHash = "__webpack_require__.h";
/**
* an object containing all installed WebAssembly.Instance export objects keyed by module id
*/
exports.wasmInstances = "__webpack_require__.w";
module.exports.wasmInstances = "__webpack_require__.w";
/**
* instantiate a wasm instance from module exports object, id, hash and importsObject
*/
exports.instantiateWasm = "__webpack_require__.v";
module.exports.instantiateWasm = "__webpack_require__.v";
/**
* the uncaught error handler for the webpack runtime
*/
exports.uncaughtErrorHandler = "__webpack_require__.oe";
module.exports.uncaughtErrorHandler = "__webpack_require__.oe";
/**
* the script nonce
*/
exports.scriptNonce = "__webpack_require__.nc";
module.exports.scriptNonce = "__webpack_require__.nc";
/**
* function to load a script tag.
@@ -166,101 +167,101 @@ exports.scriptNonce = "__webpack_require__.nc";
* done function is called when loading has finished or timeout occurred.
* It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url.
*/
exports.loadScript = "__webpack_require__.l";
module.exports.loadScript = "__webpack_require__.l";
/**
* function to promote a string to a TrustedScript using webpack's Trusted
* Types policy
* Arguments: (script: string) => TrustedScript
*/
exports.createScript = "__webpack_require__.ts";
module.exports.createScript = "__webpack_require__.ts";
/**
* function to promote a string to a TrustedScriptURL using webpack's Trusted
* Types policy
* Arguments: (url: string) => TrustedScriptURL
*/
exports.createScriptUrl = "__webpack_require__.tu";
module.exports.createScriptUrl = "__webpack_require__.tu";
/**
* function to return webpack's Trusted Types policy
* Arguments: () => TrustedTypePolicy
*/
exports.getTrustedTypesPolicy = "__webpack_require__.tt";
module.exports.getTrustedTypesPolicy = "__webpack_require__.tt";
/**
* a flag when a chunk has a fetch priority
*/
exports.hasFetchPriority = "has fetch priority";
module.exports.hasFetchPriority = "has fetch priority";
/**
* the chunk name of the chunk with the runtime
*/
exports.chunkName = "__webpack_require__.cn";
module.exports.chunkName = "__webpack_require__.cn";
/**
* the runtime id of the current runtime
*/
exports.runtimeId = "__webpack_require__.j";
module.exports.runtimeId = "__webpack_require__.j";
/**
* the filename of the script part of the chunk
*/
exports.getChunkScriptFilename = "__webpack_require__.u";
module.exports.getChunkScriptFilename = "__webpack_require__.u";
/**
* the filename of the css part of the chunk
*/
exports.getChunkCssFilename = "__webpack_require__.k";
module.exports.getChunkCssFilename = "__webpack_require__.k";
/**
* a flag when a module/chunk/tree has css modules
*/
exports.hasCssModules = "has css modules";
module.exports.hasCssModules = "has css modules";
/**
* the filename of the script part of the hot update chunk
*/
exports.getChunkUpdateScriptFilename = "__webpack_require__.hu";
module.exports.getChunkUpdateScriptFilename = "__webpack_require__.hu";
/**
* the filename of the css part of the hot update chunk
*/
exports.getChunkUpdateCssFilename = "__webpack_require__.hk";
module.exports.getChunkUpdateCssFilename = "__webpack_require__.hk";
/**
* startup signal from runtime
* This will be called when the runtime chunk has been loaded.
*/
exports.startup = "__webpack_require__.x";
module.exports.startup = "__webpack_require__.x";
/**
* @deprecated
* creating a default startup function with the entry modules
*/
exports.startupNoDefault = "__webpack_require__.x (no default handler)";
module.exports.startupNoDefault = "__webpack_require__.x (no default handler)";
/**
* startup signal from runtime but only used to add logic after the startup
*/
exports.startupOnlyAfter = "__webpack_require__.x (only after)";
module.exports.startupOnlyAfter = "__webpack_require__.x (only after)";
/**
* startup signal from runtime but only used to add sync logic before the startup
*/
exports.startupOnlyBefore = "__webpack_require__.x (only before)";
module.exports.startupOnlyBefore = "__webpack_require__.x (only before)";
/**
* global callback functions for installing chunks
*/
exports.chunkCallback = "webpackChunk";
module.exports.chunkCallback = "webpackChunk";
/**
* method to startup an entrypoint with needed chunks.
* Signature: (moduleId: Id, chunkIds: Id[]) => any.
* Returns the exports of the module or a Promise
*/
exports.startupEntrypoint = "__webpack_require__.X";
module.exports.startupEntrypoint = "__webpack_require__.X";
/**
* register deferred code, which will run when certain
@@ -270,106 +271,106 @@ exports.startupEntrypoint = "__webpack_require__.X";
* When (priority & 1) it will wait for all other handlers with lower priority to
* be executed before itself is executed
*/
exports.onChunksLoaded = "__webpack_require__.O";
module.exports.onChunksLoaded = "__webpack_require__.O";
/**
* method to install a chunk that was loaded somehow
* Signature: ({ id, ids, modules, runtime }) => void
*/
exports.externalInstallChunk = "__webpack_require__.C";
module.exports.externalInstallChunk = "__webpack_require__.C";
/**
* interceptor for module executions
*/
exports.interceptModuleExecution = "__webpack_require__.i";
module.exports.interceptModuleExecution = "__webpack_require__.i";
/**
* the global object
*/
exports.global = "__webpack_require__.g";
module.exports.global = "__webpack_require__.g";
/**
* an object with all share scopes
*/
exports.shareScopeMap = "__webpack_require__.S";
module.exports.shareScopeMap = "__webpack_require__.S";
/**
* The sharing init sequence function (only runs once per share scope).
* Has one argument, the name of the share scope.
* Creates a share scope if not existing
*/
exports.initializeSharing = "__webpack_require__.I";
module.exports.initializeSharing = "__webpack_require__.I";
/**
* The current scope when getting a module from a remote
*/
exports.currentRemoteGetScope = "__webpack_require__.R";
module.exports.currentRemoteGetScope = "__webpack_require__.R";
/**
* the filename of the HMR manifest
*/
exports.getUpdateManifestFilename = "__webpack_require__.hmrF";
module.exports.getUpdateManifestFilename = "__webpack_require__.hmrF";
/**
* function downloading the update manifest
*/
exports.hmrDownloadManifest = "__webpack_require__.hmrM";
module.exports.hmrDownloadManifest = "__webpack_require__.hmrM";
/**
* array with handler functions to download chunk updates
*/
exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC";
module.exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC";
/**
* object with all hmr module data for all modules
*/
exports.hmrModuleData = "__webpack_require__.hmrD";
module.exports.hmrModuleData = "__webpack_require__.hmrD";
/**
* array with handler functions when a module should be invalidated
*/
exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI";
module.exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI";
/**
* the prefix for storing state of runtime modules when hmr is enabled
*/
exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS";
module.exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS";
/**
* the AMD define function
*/
exports.amdDefine = "__webpack_require__.amdD";
module.exports.amdDefine = "__webpack_require__.amdD";
/**
* the AMD options
*/
exports.amdOptions = "__webpack_require__.amdO";
module.exports.amdOptions = "__webpack_require__.amdO";
/**
* the System polyfill object
*/
exports.system = "__webpack_require__.System";
module.exports.system = "__webpack_require__.System";
/**
* the shorthand for Object.prototype.hasOwnProperty
* using of it decreases the compiled bundle size
*/
exports.hasOwnProperty = "__webpack_require__.o";
module.exports.hasOwnProperty = "__webpack_require__.o";
/**
* the System.register context object
*/
exports.systemContext = "__webpack_require__.y";
module.exports.systemContext = "__webpack_require__.y";
/**
* the baseURI of current document
*/
exports.baseURI = "__webpack_require__.b";
module.exports.baseURI = "__webpack_require__.b";
/**
* a RelativeURL class when relative URLs are used
*/
exports.relativeUrl = "__webpack_require__.U";
module.exports.relativeUrl = "__webpack_require__.U";
/**
* Creates an async module. The body function must be a async function.
@@ -383,4 +384,4 @@ exports.relativeUrl = "__webpack_require__.U";
* hasAwaitAfterDependencies?: boolean
* ) => void
*/
exports.asyncModule = "__webpack_require__.a";
module.exports.asyncModule = "__webpack_require__.a";

View File

@@ -8,6 +8,7 @@
const { RawSource } = require("webpack-sources");
const OriginalSource = require("webpack-sources").OriginalSource;
const Module = require("./Module");
const { RUNTIME_TYPES } = require("./ModuleSourceTypesConstants");
const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
/** @typedef {import("webpack-sources").Source} Source */
@@ -16,18 +17,16 @@ const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const TYPES = new Set([WEBPACK_MODULE_TYPE_RUNTIME]);
class RuntimeModule extends Module {
/**
* @param {string} name a readable name
@@ -127,7 +126,7 @@ class RuntimeModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
return RUNTIME_TYPES;
}
/**
@@ -159,7 +158,7 @@ class RuntimeModule extends Module {
try {
const source = this.getGeneratedCode();
return source ? source.length : 0;
} catch (e) {
} catch (_err) {
return 0;
}
}

View File

@@ -34,10 +34,19 @@ const RuntimeIdRuntimeModule = require("./runtime/RuntimeIdRuntimeModule");
const SystemContextRuntimeModule = require("./runtime/SystemContextRuntimeModule");
const ShareRuntimeModule = require("./sharing/ShareRuntimeModule");
const StringXor = require("./util/StringXor");
const memoize = require("./util/memoize");
/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
const getCssModulesPlugin = memoize(() => require("./css/CssModulesPlugin"));
const GLOBALS_ON_REQUIRE = [
RuntimeGlobals.chunkName,
@@ -241,13 +250,12 @@ class RuntimePlugin {
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.systemContext)
.tap("RuntimePlugin", chunk => {
const { outputOptions } = compilation;
const { library: globalLibrary } = outputOptions;
const entryOptions = chunk.getEntryOptions();
const libraryType =
entryOptions && entryOptions.library !== undefined
? entryOptions.library.type
: globalLibrary.type;
: /** @type {LibraryOptions} */
(compilation.outputOptions.library).type;
if (libraryType === "system") {
compilation.addRuntimeModule(
@@ -259,7 +267,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getChunkScriptFilename)
.tap("RuntimePlugin", (chunk, set) => {
.tap("RuntimePlugin", (chunk, set, { chunkGraph }) => {
if (
typeof compilation.outputOptions.chunkFilename === "string" &&
/\[(full)?hash(:\d+)?\]/.test(
@@ -275,10 +283,13 @@ class RuntimePlugin {
"javascript",
RuntimeGlobals.getChunkScriptFilename,
chunk =>
chunk.filenameTemplate ||
(chunk.canBeInitial()
? compilation.outputOptions.filename
: compilation.outputOptions.chunkFilename),
getJavascriptModulesPlugin().chunkHasJs(chunk, chunkGraph) &&
/** @type {TemplatePath} */ (
chunk.filenameTemplate ||
(chunk.canBeInitial()
? compilation.outputOptions.filename
: compilation.outputOptions.chunkFilename)
),
false
)
);
@@ -286,7 +297,7 @@ class RuntimePlugin {
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getChunkCssFilename)
.tap("RuntimePlugin", (chunk, set) => {
.tap("RuntimePlugin", (chunk, set, { chunkGraph }) => {
if (
typeof compilation.outputOptions.cssChunkFilename === "string" &&
/\[(full)?hash(:\d+)?\]/.test(
@@ -302,6 +313,7 @@ class RuntimePlugin {
"css",
RuntimeGlobals.getChunkCssFilename,
chunk =>
getCssModulesPlugin().chunkHasCss(chunk, chunkGraph) &&
getChunkFilenameTemplate(chunk, compilation.outputOptions),
set.has(RuntimeGlobals.hmrDownloadUpdateHandlers)
)
@@ -313,7 +325,8 @@ class RuntimePlugin {
.tap("RuntimePlugin", (chunk, set) => {
if (
/\[(full)?hash(:\d+)?\]/.test(
compilation.outputOptions.hotUpdateChunkFilename
/** @type {NonNullable<OutputNormalized["hotUpdateChunkFilename"]>} */
(compilation.outputOptions.hotUpdateChunkFilename)
)
)
set.add(RuntimeGlobals.getFullHash);
@@ -323,7 +336,9 @@ class RuntimePlugin {
"javascript",
"javascript update",
RuntimeGlobals.getChunkUpdateScriptFilename,
c => compilation.outputOptions.hotUpdateChunkFilename,
c =>
/** @type {NonNullable<OutputNormalized["hotUpdateChunkFilename"]>} */
(compilation.outputOptions.hotUpdateChunkFilename),
true
)
);
@@ -334,7 +349,8 @@ class RuntimePlugin {
.tap("RuntimePlugin", (chunk, set) => {
if (
/\[(full)?hash(:\d+)?\]/.test(
compilation.outputOptions.hotUpdateMainFilename
/** @type {NonNullable<OutputNormalized["hotUpdateMainFilename"]>} */
(compilation.outputOptions.hotUpdateMainFilename)
)
) {
set.add(RuntimeGlobals.getFullHash);
@@ -344,7 +360,8 @@ class RuntimePlugin {
new GetMainFilenameRuntimeModule(
"update manifest",
RuntimeGlobals.getUpdateManifestFilename,
compilation.outputOptions.hotUpdateMainFilename
/** @type {NonNullable<OutputNormalized["hotUpdateMainFilename"]>} */
(compilation.outputOptions.hotUpdateMainFilename)
)
);
return true;
@@ -376,7 +393,9 @@ class RuntimePlugin {
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.loadScript)
.tap("RuntimePlugin", (chunk, set) => {
const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes;
const withCreateScriptUrl = Boolean(
compilation.outputOptions.trustedTypes
);
if (withCreateScriptUrl) {
set.add(RuntimeGlobals.createScriptUrl);
}

View File

@@ -34,27 +34,28 @@ const { forEachRuntime, subtractRuntime } = require("./util/runtime");
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {string} error message
*/
const noModuleIdErrorMessage = (module, chunkGraph) => {
return `Module ${module.identifier()} has no id assigned.
const noModuleIdErrorMessage = (
module,
chunkGraph
) => `Module ${module.identifier()} has no id assigned.
This should not happen.
It's in these chunks: ${
Array.from(
chunkGraph.getModuleChunksIterable(module),
c => c.name || c.id || c.debugId
).join(", ") || "none"
} (If module is in no chunk this indicates a bug in some chunk/module optimization logic)
Array.from(
chunkGraph.getModuleChunksIterable(module),
c => c.name || c.id || c.debugId
).join(", ") || "none"
} (If module is in no chunk this indicates a bug in some chunk/module optimization logic)
Module has these incoming connections: ${Array.from(
chunkGraph.moduleGraph.getIncomingConnections(module),
connection =>
`\n - ${
connection.originModule && connection.originModule.identifier()
} ${connection.dependency && connection.dependency.type} ${
(connection.explanations &&
Array.from(connection.explanations).join(", ")) ||
""
}`
).join("")}`;
};
chunkGraph.moduleGraph.getIncomingConnections(module),
connection =>
`\n - ${
connection.originModule && connection.originModule.identifier()
} ${connection.dependency && connection.dependency.type} ${
(connection.explanations &&
Array.from(connection.explanations).join(", ")) ||
""
}`
).join("")}`;
/**
* @param {string | undefined} definition global object definition
@@ -66,11 +67,11 @@ function getGlobalObject(definition) {
if (
// identifier, we do not need real identifier regarding ECMAScript/Unicode
trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) ||
/^[_\p{L}][_0-9\p{L}]*$/iu.test(trimmed) ||
// iife
// call expression
// expression in parentheses
trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu)
/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu.test(trimmed)
)
return trimmed;
@@ -85,7 +86,7 @@ class RuntimeTemplate {
*/
constructor(compilation, outputOptions, requestShortener) {
this.compilation = compilation;
this.outputOptions = outputOptions || {};
this.outputOptions = /** @type {OutputOptions} */ (outputOptions || {});
this.requestShortener = requestShortener;
this.globalObject =
/** @type {string} */
@@ -105,55 +106,47 @@ class RuntimeTemplate {
}
supportsConst() {
return /** @type {Environment} */ (this.outputOptions.environment).const;
return this.outputOptions.environment.const;
}
supportsArrowFunction() {
return /** @type {Environment} */ (this.outputOptions.environment)
.arrowFunction;
return this.outputOptions.environment.arrowFunction;
}
supportsAsyncFunction() {
return /** @type {Environment} */ (this.outputOptions.environment)
.asyncFunction;
return this.outputOptions.environment.asyncFunction;
}
supportsOptionalChaining() {
return /** @type {Environment} */ (this.outputOptions.environment)
.optionalChaining;
return this.outputOptions.environment.optionalChaining;
}
supportsForOf() {
return /** @type {Environment} */ (this.outputOptions.environment).forOf;
return this.outputOptions.environment.forOf;
}
supportsDestructuring() {
return /** @type {Environment} */ (this.outputOptions.environment)
.destructuring;
return this.outputOptions.environment.destructuring;
}
supportsBigIntLiteral() {
return /** @type {Environment} */ (this.outputOptions.environment)
.bigIntLiteral;
return this.outputOptions.environment.bigIntLiteral;
}
supportsDynamicImport() {
return /** @type {Environment} */ (this.outputOptions.environment)
.dynamicImport;
return this.outputOptions.environment.dynamicImport;
}
supportsEcmaScriptModuleSyntax() {
return /** @type {Environment} */ (this.outputOptions.environment).module;
return this.outputOptions.environment.module;
}
supportTemplateLiteral() {
return /** @type {Environment} */ (this.outputOptions.environment)
.templateLiteral;
return this.outputOptions.environment.templateLiteral;
}
supportNodePrefixForCoreModules() {
return /** @type {Environment} */ (this.outputOptions.environment)
.nodePrefixForCoreModules;
return this.outputOptions.environment.nodePrefixForCoreModules;
}
/**
@@ -314,7 +307,7 @@ class RuntimeTemplate {
* Add a comment
* @param {object} options Information content of the comment
* @param {string=} options.request request string used originally
* @param {string=} options.chunkName name of the chunk referenced
* @param {(string | null)=} options.chunkName name of the chunk referenced
* @param {string=} options.chunkReason reason information of the chunk
* @param {string=} options.message additional message
* @param {string=} options.exportName name of the export
@@ -335,10 +328,9 @@ class RuntimeTemplate {
}
if (!content) return "";
if (this.outputOptions.pathinfo) {
return Template.toComment(content) + " ";
} else {
return Template.toNormalComment(content) + " ";
return `${Template.toComment(content)} `;
}
return `${Template.toNormalComment(content)} `;
}
/**
@@ -412,11 +404,10 @@ class RuntimeTemplate {
: JSON.stringify(
`Module '${moduleId}' is not available (weak dependency)`
);
const comment = request ? Template.toNormalComment(request) + " " : "";
const errorStatements =
`var e = new Error(${errorMessage}); ` +
comment +
"e.code = 'MODULE_NOT_FOUND'; throw e;";
const comment = request ? `${Template.toNormalComment(request)} ` : "";
const errorStatements = `var e = new Error(${errorMessage}); ${
comment
}e.code = 'MODULE_NOT_FOUND'; throw e;`;
switch (type) {
case "statements":
return errorStatements;
@@ -778,7 +769,6 @@ class RuntimeTemplate {
}
/**
*
* @param {object} options options object
* @param {boolean=} options.update whether a new variable should be created or the existing one updated
* @param {Module} options.module the module
@@ -907,13 +897,13 @@ class RuntimeTemplate {
case "dynamic":
if (isCall) {
return `${importVar}_default()${propertyAccess(exportName, 1)}`;
} else {
return asiSafe
? `(${importVar}_default()${propertyAccess(exportName, 1)})`
: asiSafe === false
? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
: `${importVar}_default.a${propertyAccess(exportName, 1)}`;
}
return asiSafe
? `(${importVar}_default()${propertyAccess(exportName, 1)})`
: asiSafe === false
? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
: `${importVar}_default.a${propertyAccess(exportName, 1)}`;
case "default-only":
case "default-with-named":
exportName = exportName.slice(1);
@@ -921,10 +911,10 @@ class RuntimeTemplate {
}
} else if (exportName.length > 0) {
if (exportsType === "default-only") {
return (
"/* non-default import from non-esm module */undefined" +
propertyAccess(exportName, 1)
);
return `/* non-default import from non-esm module */undefined${propertyAccess(
exportName,
1
)}`;
} else if (
exportsType !== "namespace" &&
exportName[0] === "__esModule"
@@ -963,7 +953,7 @@ class RuntimeTemplate {
}
const comment = equals(used, exportName)
? ""
: Template.toNormalComment(propertyAccess(exportName)) + " ";
: `${Template.toNormalComment(propertyAccess(exportName))} `;
const access = `${importVar}${comment}${propertyAccess(used)}`;
if (isCall && callContext === false) {
return asiSafe
@@ -973,9 +963,8 @@ class RuntimeTemplate {
: `/*#__PURE__*/Object(${access})`;
}
return access;
} else {
return importVar;
}
return importVar;
}
/**
@@ -1040,9 +1029,8 @@ class RuntimeTemplate {
return `Promise.all(${comment.trim()}[${chunks
.map(requireChunkId)
.join(", ")}])`;
} else {
return `Promise.resolve(${comment.trim()})`;
}
return `Promise.resolve(${comment.trim()})`;
}
/**
@@ -1109,27 +1097,6 @@ class RuntimeTemplate {
runtimeRequirements.add(RuntimeGlobals.exports);
return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`;
}
/**
* @param {object} options options object
* @param {Module} options.module the module
* @param {RuntimeSpec=} options.runtime runtime
* @param {CodeGenerationResults} options.codeGenerationResults the code generation results
* @returns {string} the url of the asset
*/
assetUrl({ runtime, module, codeGenerationResults }) {
if (!module) {
return "data:,";
}
const codeGen = codeGenerationResults.get(module, runtime);
const data = /** @type {NonNullable<CodeGenerationResult["data"]>} */ (
codeGen.data
);
const url = data.get("url");
if (url) return url.toString();
const assetPath = data.get("assetPathForCss");
return assetPath;
}
}
module.exports = RuntimeTemplate;

View File

@@ -9,7 +9,7 @@
* @param {number} size the size in bytes
* @returns {string} the formatted size
*/
exports.formatSize = size => {
module.exports.formatSize = size => {
if (typeof size !== "number" || Number.isNaN(size) === true) {
return "unknown size";
}
@@ -21,7 +21,5 @@ exports.formatSize = size => {
const abbreviations = ["bytes", "KiB", "MiB", "GiB"];
const index = Math.floor(Math.log(size) / Math.log(1024));
return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${
abbreviations[index]
}`;
return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`;
};

View File

@@ -24,11 +24,12 @@ const { makePathsAbsolute } = require("./util/identifier");
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation").Asset} Asset */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./NormalModule").SourceMap} SourceMap */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/createHash").Algorithm} Algorithm */
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
const validate = createSchemaValidation(
@@ -63,7 +64,6 @@ const URL_FORMATTING_REGEXP = /^\n\/\/(.*)$/;
* For when `test` or `exec` is called on them
* @param {RegExp} regexp Stateful Regular Expression to be reset
* @returns {void}
*
*/
const resetRegexpState = regexp => {
regexp.lastIndex = -1;
@@ -74,9 +74,7 @@ const resetRegexpState = regexp => {
* @param {string} str String to quote
* @returns {string} Escaped string
*/
const quoteMeta = str => {
return str.replace(METACHARACTERS_REGEXP, "\\$&");
};
const quoteMeta = str => str.replace(METACHARACTERS_REGEXP, "\\$&");
/**
* Creating {@link SourceMapTask} for given file
@@ -111,7 +109,7 @@ const getTaskForFile = (
source = asset.source();
}
if (!sourceMap || typeof source !== "string") return;
const context = compilation.options.context;
const context = /** @type {string} */ (compilation.options.context);
const root = compilation.compiler.root;
const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root);
const modules = sourceMap.sources.map(source => {
@@ -140,13 +138,13 @@ class SourceMapDevToolPlugin {
constructor(options = {}) {
validate(options);
/** @type {string | false} */
this.sourceMapFilename = options.filename;
/** @type {string | false | (function(PathData, AssetInfo=): string)}} */
this.sourceMapFilename = /** @type {string | false} */ (options.filename);
/** @type {false | TemplatePath}} */
this.sourceMappingURLComment =
options.append === false
? false
: options.append || "\n//# source" + "MappingURL=[url]";
: // eslint-disable-next-line no-useless-concat
options.append || "\n//# source" + "MappingURL=[url]";
/** @type {string | Function} */
this.moduleFilenameTemplate =
options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]";
@@ -223,7 +221,7 @@ class SourceMapDevToolPlugin {
}
}
reportProgress(0.0);
reportProgress(0);
/** @type {SourceMapTask[]} */
const tasks = [];
let fileIndex = 0;
@@ -238,11 +236,17 @@ class SourceMapDevToolPlugin {
fileIndex++;
return callback();
}
const chunk = fileToChunk.get(file);
const sourceMapNamespace = compilation.getPath(this.namespace, {
chunk
});
const cacheItem = cache.getItemCache(
file,
cache.mergeEtags(
cache.getLazyHashedEtag(asset.source),
namespace
sourceMapNamespace
)
);
@@ -272,11 +276,8 @@ class SourceMapDevToolPlugin {
/**
* Add file to chunk, if not presented there
*/
if (cachedFile !== file) {
const chunk = fileToChunk.get(file);
if (chunk !== undefined)
chunk.auxiliaryFiles.add(cachedFile);
}
if (cachedFile !== file && chunk !== undefined)
chunk.auxiliaryFiles.add(cachedFile);
}
reportProgress(
@@ -312,14 +313,23 @@ class SourceMapDevToolPlugin {
for (let idx = 0; idx < modules.length; idx++) {
const module = modules[idx];
if (
typeof module === "string" &&
/^(data|https?):/.test(module)
) {
moduleToSourceNameMapping.set(module, module);
continue;
}
if (!moduleToSourceNameMapping.get(module)) {
moduleToSourceNameMapping.set(
module,
ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: moduleFilenameTemplate,
namespace: namespace
moduleFilenameTemplate,
namespace: sourceMapNamespace
},
{
requestShortener,
@@ -383,7 +393,7 @@ class SourceMapDevToolPlugin {
module,
{
moduleFilenameTemplate: fallbackModuleFilenameTemplate,
namespace: namespace
namespace
},
{
requestShortener,
@@ -429,7 +439,7 @@ class SourceMapDevToolPlugin {
const moduleFilenames = modules.map(m =>
moduleToSourceNameMapping.get(m)
);
sourceMap.sources = moduleFilenames;
sourceMap.sources = /** @type {string[]} */ (moduleFilenames);
if (options.noSources) {
sourceMap.sourcesContent = undefined;
}
@@ -444,21 +454,18 @@ class SourceMapDevToolPlugin {
// If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file`
if (usesContentHash && task.assetInfo.contenthash) {
const contenthash = task.assetInfo.contenthash;
let pattern;
if (Array.isArray(contenthash)) {
pattern = contenthash.map(quoteMeta).join("|");
} else {
pattern = quoteMeta(contenthash);
}
const pattern = Array.isArray(contenthash)
? contenthash.map(quoteMeta).join("|")
: quoteMeta(contenthash);
sourceMap.file = sourceMap.file.replace(
new RegExp(pattern, "g"),
m => "x".repeat(m.length)
);
}
/** @type {string | false | (function(PathData, AssetInfo=): string)} */
/** @type {false | TemplatePath} */
let currentSourceMappingURLComment = sourceMappingURLComment;
let cssExtensionDetected =
const cssExtensionDetected =
CSS_EXTENSION_DETECT_REGEXP.test(file);
resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
if (
@@ -474,13 +481,17 @@ class SourceMapDevToolPlugin {
}
const sourceMapString = JSON.stringify(sourceMap);
if (sourceMapFilename) {
let filename = file;
const filename = file;
const sourceMapContentHash =
usesContentHash &&
/** @type {string} */ (
createHash(compilation.outputOptions.hashFunction)
.update(sourceMapString)
.digest("hex")
/** @type {string} */
(
usesContentHash &&
createHash(
/** @type {Algorithm} */
(compilation.outputOptions.hashFunction)
)
.update(sourceMapString)
.digest("hex")
);
const pathParams = {
chunk,
@@ -511,10 +522,10 @@ class SourceMapDevToolPlugin {
// Add source map url to compilation asset, if currentSourceMappingURLComment is set
asset = new ConcatSource(
asset,
compilation.getPath(
currentSourceMappingURLComment,
Object.assign({ url: sourceMapUrl }, pathParams)
)
compilation.getPath(currentSourceMappingURLComment, {
url: sourceMapUrl,
...pathParams
})
);
}
const assetInfo = {
@@ -584,7 +595,7 @@ class SourceMapDevToolPlugin {
});
},
err => {
reportProgress(1.0);
reportProgress(1);
callback(err);
}
);

16
node_modules/webpack/lib/Stats.js generated vendored
View File

@@ -55,13 +55,11 @@ class Stats {
* @returns {StatsCompilation} json output
*/
toJson(options) {
options = this.compilation.createStatsOptions(options, {
const normalizedOptions = this.compilation.createStatsOptions(options, {
forToString: false
});
const statsFactory = this.compilation.createStatsFactory(
/** @type {NormalizedStatsOptions} */ (options)
);
const statsFactory = this.compilation.createStatsFactory(normalizedOptions);
return statsFactory.create("compilation", this.compilation, {
compilation: this.compilation
@@ -73,16 +71,12 @@ class Stats {
* @returns {string} string output
*/
toString(options) {
options = this.compilation.createStatsOptions(options, {
const normalizedOptions = this.compilation.createStatsOptions(options, {
forToString: true
});
const statsFactory = this.compilation.createStatsFactory(
/** @type {NormalizedStatsOptions} */ (options)
);
const statsPrinter = this.compilation.createStatsPrinter(
/** @type {NormalizedStatsOptions} */ (options)
);
const statsFactory = this.compilation.createStatsFactory(normalizedOptions);
const statsPrinter = this.compilation.createStatsPrinter(normalizedOptions);
const data = statsFactory.create("compilation", this.compilation, {
compilation: this.compilation

42
node_modules/webpack/lib/Template.js generated vendored
View File

@@ -13,6 +13,7 @@ const RuntimeGlobals = require("./RuntimeGlobals");
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").PathData} PathData */
@@ -22,6 +23,7 @@ const RuntimeGlobals = require("./RuntimeGlobals");
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./RuntimeModule")} RuntimeModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
@@ -59,7 +61,7 @@ const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
/**
* @typedef {object} RenderManifestEntryTemplated
* @property {function(): Source} render
* @property {string | function(PathData, AssetInfo=): string} filenameTemplate
* @property {TemplatePath} filenameTemplate
* @property {PathData=} pathOptions
* @property {AssetInfo=} info
* @property {string} identifier
@@ -88,7 +90,6 @@ const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
class Template {
/**
*
* @param {Function} fn a runtime function (.runtime.js) "template"
* @returns {string} the updated and normalized function string
*/
@@ -110,8 +111,8 @@ class Template {
.replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1")
.replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
}
/**
*
* @param {string} str string to be converted to commented in bundle code
* @returns {string} returns a commented version of string
*/
@@ -121,7 +122,6 @@ class Template {
}
/**
*
* @param {string} str string to be converted to "normal comment"
* @returns {string} returns a commented version of string
*/
@@ -211,23 +211,20 @@ class Template {
}
/**
*
* @param {string | string[]} s string to convert to identity
* @returns {string} converted identity
*/
static indent(s) {
if (Array.isArray(s)) {
return s.map(Template.indent).join("\n");
} else {
const str = s.trimEnd();
if (!str) return "";
const ind = str[0] === "\n" ? "" : "\t";
return ind + str.replace(/\n([^\n])/g, "\n\t$1");
}
const str = s.trimEnd();
if (!str) return "";
const ind = str[0] === "\n" ? "" : "\t";
return ind + str.replace(/\n([^\n])/g, "\n\t$1");
}
/**
*
* @param {string|string[]} s string to create prefix for
* @param {string} prefix prefix to compose
* @returns {string} returns new prefix string
@@ -236,11 +233,10 @@ class Template {
const str = Template.asString(s).trim();
if (!str) return "";
const ind = str[0] === "\n" ? "" : prefix;
return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
return ind + str.replace(/\n([^\n])/g, `\n${prefix}$1`);
}
/**
*
* @param {string|string[]} str string or string collection
* @returns {string} returns a single string from array
*/
@@ -270,7 +266,7 @@ class Template {
if (maxId < moduleId) maxId = moduleId;
if (minId > moduleId) minId = moduleId;
}
if (minId < 16 + ("" + minId).length) {
if (minId < 16 + String(minId).length) {
// add minId x ',' instead of 'Array(minId).concat(…)'
minId = 0;
}
@@ -288,23 +284,21 @@ class Template {
/**
* @param {ChunkRenderContext} renderContext render context
* @param {Module[]} modules modules to render (should be ordered by identifier)
* @param {function(Module): Source} renderModule function to render a module
* @param {function(Module): Source | null} renderModule function to render a module
* @param {string=} prefix applying prefix strings
* @returns {Source | null} rendered chunk modules in a Source object or null if no modules
*/
static renderChunkModules(renderContext, modules, renderModule, prefix = "") {
const { chunkGraph } = renderContext;
var source = new ConcatSource();
const source = new ConcatSource();
if (modules.length === 0) {
return null;
}
/** @type {{id: string|number, source: Source|string}[]} */
const allModules = modules.map(module => {
return {
id: chunkGraph.getModuleId(module),
source: renderModule(module) || "false"
};
});
const allModules = modules.map(module => ({
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
source: renderModule(module) || "false"
}));
const bounds = Template.getModulesArrayBounds(allModules);
if (bounds) {
// Render a spare array
@@ -330,7 +324,7 @@ class Template {
source.add(module.source);
}
}
source.add("\n" + prefix + "]");
source.add(`\n${prefix}]`);
if (minId !== 0) {
source.add(")");
}
@@ -379,7 +373,7 @@ class Template {
runtimeSource = codeGenResult.sources.get("runtime");
}
if (runtimeSource) {
source.add(Template.toNormalComment(module.identifier()) + "\n");
source.add(`${Template.toNormalComment(module.identifier())}\n`);
if (!module.shouldIsolate()) {
source.add(runtimeSource);
source.add("\n\n");

View File

@@ -13,6 +13,7 @@ const Module = require("./Module");
const { parseResource } = require("./util/identifier");
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./Compiler")} Compiler */
@@ -55,7 +56,7 @@ const hashLength = (replacer, handler, assetInfo, hashName) => {
/** @type {ReplacerFunction} */
const fn = (match, arg, input) => {
let result;
const length = arg && parseInt(arg, 10);
const length = arg && Number.parseInt(arg, 10);
if (length && handler) {
result = handler(length);
@@ -101,9 +102,9 @@ const replacer = (value, allowEmpty) => {
}
return "";
} else {
return `${value}`;
}
return `${value}`;
};
return fn;
@@ -129,8 +130,10 @@ const deprecated = (fn, message, code) => {
};
};
/** @typedef {string | function(PathData, AssetInfo=): string} TemplatePath */
/**
* @param {string | function(PathData, AssetInfo=): string} path the raw path
* @param {TemplatePath} path the raw path
* @param {PathData} data context data
* @param {AssetInfo | undefined} assetInfo extra info about the asset (will be written to)
* @returns {string} the interpolated path
@@ -155,23 +158,29 @@ const replacePathVariables = (path, data, assetInfo) => {
// [ext] - .js
if (typeof data.filename === "string") {
// check that filename is data uri
let match = data.filename.match(/^data:([^;,]+)/);
const match = data.filename.match(/^data:([^;,]+)/);
if (match) {
const ext = mime.extension(match[1]);
const emptyReplacer = replacer("", true);
// "XXXX" used for `updateHash`, so we don't need it here
const contentHash =
data.contentHash && !/X+/.test(data.contentHash)
? data.contentHash
: false;
const baseReplacer = contentHash ? replacer(contentHash) : emptyReplacer;
replacements.set("file", emptyReplacer);
replacements.set("query", emptyReplacer);
replacements.set("fragment", emptyReplacer);
replacements.set("path", emptyReplacer);
replacements.set("base", emptyReplacer);
replacements.set("name", emptyReplacer);
replacements.set("base", baseReplacer);
replacements.set("name", baseReplacer);
replacements.set("ext", replacer(ext ? `.${ext}` : "", true));
// Legacy
replacements.set(
"filebase",
deprecated(
emptyReplacer,
baseReplacer,
"[filebase] is now [base]",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
)
@@ -292,17 +301,16 @@ const replacePathVariables = (path, data, assetInfo) => {
const idReplacer = replacer(() =>
prepareId(
module instanceof Module
? /** @type {ChunkGraph} */ (chunkGraph).getModuleId(module)
? /** @type {ModuleId} */
(/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
: module.id
)
);
const moduleHashReplacer = hashLength(
replacer(() =>
module instanceof Module
? /** @type {ChunkGraph} */ (chunkGraph).getRenderedModuleHash(
module,
data.runtime
)
? /** @type {ChunkGraph} */
(chunkGraph).getRenderedModuleHash(module, data.runtime)
: module.hash
),
"hashWithLength" in module ? module.hashWithLength : undefined,

Some files were not shown because too many files have changed in this diff Show More