Add JS-CATCH-FALLBACK-01 rule and update npm packages

Add PHP-ALIAS-01 rule: prohibit field aliasing in serialization

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-12-23 07:36:18 +00:00
parent 3cc590186a
commit 3ce82a924a
1256 changed files with 6491 additions and 3989 deletions

0
node_modules/webpack/LICENSE generated vendored Executable file → Normal file
View File

21
node_modules/webpack/hot/dev-server.js generated vendored Executable file → Normal file
View File

@@ -61,14 +61,29 @@ if (module.hot) {
}
});
};
/** @type {EventTarget | NodeJS.EventEmitter} */
var hotEmitter = require("./emitter");
hotEmitter.on("webpackHotUpdate", function (currentHash) {
lastHash = currentHash;
/**
* @param {CustomEvent<{ currentHash: string }>} event event or hash
*/
var handler = function (event) {
lastHash = typeof event === "string" ? event : event.detail.currentHash;
if (!upToDate() && module.hot.status() === "idle") {
log("info", "[HMR] Checking for updates on the server...");
check();
}
});
};
if (typeof EventTarget !== "undefined" && hotEmitter instanceof EventTarget) {
hotEmitter.addEventListener(
"webpackHotUpdate",
/** @type {EventListener} */
(handler)
);
} else {
hotEmitter.on("webpackHotUpdate", handler);
}
log("info", "[HMR] Waiting for update signal from WDS...");
} else {
throw new Error("[HMR] Hot Module Replacement is disabled.");

7
node_modules/webpack/hot/emitter-event-target.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
if (typeof EventTarget !== "function") {
throw new Error(
"Environment doesn't support lazy compilation (requires EventTarget)"
);
}
module.exports = new EventTarget();

0
node_modules/webpack/hot/emitter.js generated vendored Executable file → Normal file
View File

74
node_modules/webpack/hot/lazy-compilation-node.js generated vendored Executable file → Normal file
View File

@@ -1,7 +1,7 @@
/* global __resourceQuery */
"use strict";
/* global __resourceQuery */
var urlBase = decodeURIComponent(__resourceQuery.slice(1));
/**
@@ -10,29 +10,6 @@ var urlBase = decodeURIComponent(__resourceQuery.slice(1));
*/
exports.keepAlive = function (options) {
var data = options.data;
var onError = options.onError;
var active = options.active;
var module = options.module;
/** @type {import("http").IncomingMessage} */
var response;
var request = (
urlBase.startsWith("https") ? require("https") : require("http")
).request(
urlBase + data,
{
agent: false,
headers: { accept: "text/event-stream" }
},
function (res) {
response = res;
response.on("error", errorHandler);
if (!active && !module.hot) {
console.log(
"Hot Module Replacement is not enabled. Waiting for process restart..."
);
}
}
);
/**
* @param {Error} err error
@@ -40,11 +17,50 @@ exports.keepAlive = function (options) {
function errorHandler(err) {
err.message =
"Problem communicating active modules to the server: " + err.message;
onError(err);
options.onError(err);
}
request.on("error", errorHandler);
request.end();
/** @type {Promise<import("http") | import("https")>} */
var mod = require("./load-http")(urlBase.startsWith("https"));
/** @type {import("http").ClientRequest} */
var request;
/** @type {import("http").IncomingMessage} */
var response;
mod.then(function (client) {
request = client.request(
urlBase + data,
{
agent: false,
headers: { accept: "text/event-stream" }
},
function (res) {
response = res;
response.on("error", errorHandler);
if (!options.active && !options.module.hot) {
console.log(
"Hot Module Replacement is not enabled. Waiting for process restart..."
);
}
}
);
request.on("error", errorHandler);
request.end();
});
return function () {
response.destroy();
if (response) {
response.destroy();
}
};
};
/**
* @param {string} value new url value
*/
exports.setUrl = function (value) {
urlBase = value;
};

18
node_modules/webpack/hot/lazy-compilation-universal.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
"use strict";
/* global __resourceQuery */
var isNodeLikeEnv =
typeof global !== "undefined" && typeof global.process !== "undefined";
var handler = isNodeLikeEnv
? require("./lazy-compilation-node")
: require("./lazy-compilation-web");
handler.setUrl(decodeURIComponent(__resourceQuery.slice(1)));
/**
* @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options
* @returns {() => void} function to destroy response
*/
module.exports = handler;

20
node_modules/webpack/hot/lazy-compilation-web.js generated vendored Executable file → Normal file
View File

@@ -1,7 +1,7 @@
/* global __resourceQuery */
"use strict";
/* global __resourceQuery */
if (typeof EventSource !== "function") {
throw new Error(
"Environment doesn't support lazy compilation (requires EventSource)"
@@ -54,15 +54,18 @@ var updateEventSource = function updateEventSource() {
exports.keepAlive = function (options) {
var data = options.data;
var onError = options.onError;
var active = options.active;
var module = options.module;
errorHandlers.add(onError);
var value = activeKeys.get(data) || 0;
activeKeys.set(data, value + 1);
if (value === 0) {
updateEventSource();
}
if (!active && !module.hot) {
if (!options.active && !options.module.hot) {
console.log(
"Hot Module Replacement is not enabled. Waiting for process restart..."
);
@@ -81,3 +84,10 @@ exports.keepAlive = function (options) {
}, 1000);
};
};
/**
* @param {string} value new url value
*/
exports.setUrl = function (value) {
urlBase = value;
};

7
node_modules/webpack/hot/load-http.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
/**
* @param {boolean} isHTTPS true when need https module, otherwise false
* @returns {Promise<import("http") | import("https")>}
*/
module.exports = function (isHTTPS) {
return isHTTPS ? import("https") : import("http");
};

0
node_modules/webpack/hot/log-apply-result.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/log.js generated vendored Executable file → Normal file
View File

23
node_modules/webpack/hot/only-dev-server.js generated vendored Executable file → Normal file
View File

@@ -4,7 +4,7 @@
*/
/* globals __webpack_hash__ */
if (module.hot) {
/** @type {undefined|string} */
/** @type {undefined | string} */
var lastHash;
var upToDate = function upToDate() {
return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0;
@@ -79,9 +79,13 @@ if (module.hot) {
}
});
};
/** @type {EventTarget | NodeJS.EventEmitter} */
var hotEmitter = require("./emitter");
hotEmitter.on("webpackHotUpdate", function (currentHash) {
lastHash = currentHash;
/**
* @param {CustomEvent<{ currentHash: string }>} event event or hash
*/
var handler = function (event) {
lastHash = typeof event === "string" ? event : event.detail.currentHash;
if (!upToDate()) {
var status = module.hot.status();
if (status === "idle") {
@@ -96,7 +100,18 @@ if (module.hot) {
);
}
}
});
};
if (typeof EventTarget !== "undefined" && hotEmitter instanceof EventTarget) {
hotEmitter.addEventListener(
"webpackHotUpdate",
/** @type {EventListener} */
(handler)
);
} else {
hotEmitter.on("webpackHotUpdate", handler);
}
log("info", "[HMR] Waiting for update signal from WDS...");
} else {
throw new Error("[HMR] Hot Module Replacement is disabled.");

0
node_modules/webpack/hot/poll.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/signal.js generated vendored Executable file → Normal file
View File

6
node_modules/webpack/lib/APIPlugin.js generated vendored Executable file → Normal file
View File

@@ -42,6 +42,12 @@ function getReplacements() {
type: "function",
assign: false
},
__webpack_global__: {
expr: RuntimeGlobals.require,
req: [RuntimeGlobals.require],
type: "function",
assign: false
},
__webpack_public_path__: {
expr: RuntimeGlobals.publicPath,
req: [RuntimeGlobals.publicPath],

0
node_modules/webpack/lib/AbstractMethodError.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/AsyncDependenciesBlock.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/AsyncDependencyToInitialChunkError.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/AutomaticPrefetchPlugin.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/BannerPlugin.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/Cache.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/CacheFacade.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/CaseSensitiveModulesWarning.js generated vendored Executable file → Normal file
View File

2
node_modules/webpack/lib/Chunk.js generated vendored Executable file → Normal file
View File

@@ -207,7 +207,7 @@ class Chunk {
/**
* @param {Chunk} otherChunk the chunk to compare with
* @returns {-1|0|1} the comparison result
* @returns {-1 | 0 | 1} the comparison result
*/
compareTo(otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(

16
node_modules/webpack/lib/ChunkGraph.js generated vendored Executable file → Normal file
View File

@@ -35,8 +35,9 @@ const {
/** @typedef {import("./Chunk").Entrypoints} Entrypoints */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").SourceType} SourceType */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
@@ -97,7 +98,7 @@ const getModuleRuntimes = (chunks) => {
* @returns {(set: SortableSet<Module>) => Map<string, SortableSet<Module>>} modules by source type
*/
const modulesBySourceType = (sourceTypesByModule) => (set) => {
/** @type {Map<string, SortableSet<Module>>} */
/** @type {Map<SourceType, SortableSet<Module>>} */
const map = new Map();
for (const module of set) {
const sourceTypes =
@@ -220,7 +221,7 @@ class ChunkGraphModule {
}
}
/** @typedef {WeakMap<Module, Set<string>>} SourceTypesByModule */
/** @typedef {WeakMap<Module, SourceTypes>} SourceTypesByModule */
/** @typedef {Map<Module, Entrypoint>} EntryModules */
class ChunkGraphChunk {
@@ -631,7 +632,7 @@ class ChunkGraph {
/**
* @param {Chunk} chunk chunk
* @param {Module} module chunk module
* @param {Set<string>} sourceTypes source types
* @param {SourceTypes} sourceTypes source types
*/
setChunkModuleSourceTypes(chunk, module, sourceTypes) {
const cgc = this._getChunkGraphChunk(chunk);
@@ -668,10 +669,11 @@ class ChunkGraph {
/**
* @param {Module} module module
* @returns {Set<string> | undefined} source types
* @returns {SourceTypes | undefined} source types
*/
_getOverwrittenModuleSourceTypes(module) {
let newSet = false;
/** @type {Set<SourceType> | undefined} */
let sourceTypes;
for (const chunk of this.getModuleChunksIterable(module)) {
const cgc = this._getChunkGraphChunk(chunk);
@@ -679,7 +681,7 @@ class ChunkGraph {
const st = cgc.sourceTypesByModule.get(module);
if (st === undefined) return;
if (!sourceTypes) {
sourceTypes = st;
sourceTypes = /** @type {Set<SourceType>} */ (st);
} else if (!newSet) {
for (const type of st) {
if (!newSet) {
@@ -871,7 +873,7 @@ class ChunkGraph {
/**
* @param {Chunk} chunkA first chunk
* @param {Chunk} chunkB second chunk
* @returns {-1|0|1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order
* @returns {-1 | 0 | 1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order
*/
compareChunks(chunkA, chunkB) {
const cgcA = this._getChunkGraphChunk(chunkA);

13
node_modules/webpack/lib/ChunkGroup.js generated vendored Executable file → Normal file
View File

@@ -45,7 +45,7 @@ const getArray = (set) => [...set];
* A convenience method used to sort chunks based on their id's
* @param {ChunkGroup} a first sorting comparator
* @param {ChunkGroup} b second sorting comparator
* @returns {1|0|-1} a sorting index to determine order
* @returns {1 | 0 | -1} a sorting index to determine order
*/
const sortById = (a, b) => {
if (a.id < b.id) return -1;
@@ -56,7 +56,7 @@ const sortById = (a, b) => {
/**
* @param {OriginRecord} a the first comparator in sort
* @param {OriginRecord} b the second comparator in sort
* @returns {1|-1|0} returns sorting order as index
* @returns {1 | -1| 0} returns sorting order as index
*/
const sortOrigin = (a, b) => {
const aIdent = a.module ? a.module.identifier() : "";
@@ -91,16 +91,19 @@ class ChunkGroup {
this.chunks = [];
/** @type {OriginRecord[]} */
this.origins = [];
/** @typedef {Map<Module, number>} OrderIndices */
/** Indices in top-down order */
/**
* @private
* @type {Map<Module, number>}
* @type {OrderIndices}
*/
this._modulePreOrderIndices = new Map();
/** Indices in bottom-up order */
/**
* @private
* @type {Map<Module, number>}
* @type {OrderIndices}
*/
this._modulePostOrderIndices = new Map();
/** @type {number | undefined} */
@@ -485,7 +488,7 @@ class ChunkGroup {
* 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
* @returns {-1 | 0 | 1} sort position for comparison
*/
compareTo(chunkGraph, otherGroup) {
if (this.chunks.length > otherGroup.chunks.length) return -1;

0
node_modules/webpack/lib/ChunkRenderError.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/ChunkTemplate.js generated vendored Executable file → Normal file
View File

9
node_modules/webpack/lib/CleanPlugin.js generated vendored Executable file → Normal file
View File

@@ -63,8 +63,10 @@ const mergeAssets = (as1, as2) => {
}
};
/** @typedef {Map<string, number>} CurrentAssets */
/**
* @param {Map<string, number>} assets current assets
* @param {CurrentAssets} assets current assets
* @returns {Set<string>} Set of directory paths
*/
function getDirectories(assets) {
@@ -92,12 +94,13 @@ function getDirectories(assets) {
/**
* @param {OutputFileSystem} fs filesystem
* @param {string} outputPath output path
* @param {Map<string, number>} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
* @param {CurrentAssets} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
* @param {(err?: Error | null, set?: Diff) => void} callback returns the filenames of the assets that shouldn't be there
* @returns {void}
*/
const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
const directories = getDirectories(currentAssets);
/** @type {Diff} */
const diff = new Set();
asyncLib.forEachLimit(
directories,
@@ -388,7 +391,7 @@ class CleanPlugin {
// We assume that no external modification happens while the compiler is active
// So we can store the old assets and only diff to them to avoid fs access on
// incremental builds
/** @type {undefined|Assets} */
/** @type {undefined | Assets} */
let oldAssets;
compiler.hooks.emit.tapAsync(

0
node_modules/webpack/lib/CodeGenerationError.js generated vendored Executable file → Normal file
View File

3
node_modules/webpack/lib/CodeGenerationResults.js generated vendored Executable file → Normal file
View File

@@ -13,6 +13,7 @@ const { RuntimeSpecMap, runtimeToString } = require("./util/runtime");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").SourceType} SourceType */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").CodeGenerationResultData} CodeGenerationResultData */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
@@ -96,7 +97,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {string} sourceType the source type
* @param {SourceType} sourceType the source type
* @returns {Source} a source
*/
getSource(module, runtime, sourceType) {

0
node_modules/webpack/lib/CommentCompilationWarning.js generated vendored Executable file → Normal file
View File

3
node_modules/webpack/lib/CompatibilityPlugin.js generated vendored Executable file → Normal file
View File

@@ -147,6 +147,9 @@ class CompatibilityPlugin {
range: /** @type {Range} */ (pattern.range)
}
});
if (!parser.scope.topLevelScope) {
return true;
}
});
parser.hooks.pattern
.for(RuntimeGlobals.exports)

52
node_modules/webpack/lib/Compilation.js generated vendored Executable file → Normal file
View File

@@ -84,7 +84,6 @@ const processAsyncTree = require("./util/processAsyncTree");
const { getRuntimeKey } = require("./util/runtime");
const { isSourceEqual } = require("./util/source");
/** @template T @typedef {import("tapable").AsArray<T>} AsArray<T> */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
@@ -135,6 +134,11 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./util/Hash")} Hash */
/**
* @template T
* @typedef {import("tapable").AsArray<T>} AsArray<T>
*/
/**
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
@@ -200,9 +204,9 @@ const { isSourceEqual } = require("./util/source");
* @property {string | number} id
* @property {string=} name
* @property {string} hash
* @property {((length: number) => string)=} hashWithLength
* @property {HashWithLengthFunction=} hashWithLength
* @property {(Record<string, string>)=} contentHash
* @property {(Record<string, (length: number) => string>)=} contentHashWithLength
* @property {(Record<string, HashWithLengthFunction>)=} contentHashWithLength
*/
/**
@@ -224,17 +228,19 @@ const { isSourceEqual } = require("./util/source");
* @property {EntryOptions=} entryOptions
*/
/** @typedef {LazySet<string>} FileSystemDependencies */
/** @typedef {EXPECTED_ANY} ExecuteModuleExports */
/**
* @typedef {object} ExecuteModuleResult
* @property {ExecuteModuleExports} exports
* @property {boolean} cacheable
* @property {Map<string, { source: Source, info: AssetInfo | undefined }>} assets
* @property {LazySet<string>} fileDependencies
* @property {LazySet<string>} contextDependencies
* @property {LazySet<string>} missingDependencies
* @property {LazySet<string>} buildDependencies
* @property {ExecuteModuleAssets} assets
* @property {FileSystemDependencies} fileDependencies
* @property {FileSystemDependencies} contextDependencies
* @property {FileSystemDependencies} missingDependencies
* @property {FileSystemDependencies} buildDependencies
*/
/**
@@ -261,9 +267,11 @@ const { isSourceEqual } = require("./util/source");
* @property {WebpackRequire} require require function
*/
/** @typedef {Map<string, { source: Source, info: AssetInfo | undefined }>} ExecuteModuleAssets */
/**
* @typedef {object} ExecuteModuleContext
* @property {Map<string, { source: Source, info: AssetInfo | undefined }>} assets
* @property {ExecuteModuleAssets} assets
* @property {Chunk} chunk
* @property {ChunkGraph} chunkGraph
* @property {WebpackRequire=} __webpack_require__
@@ -312,18 +320,22 @@ const { isSourceEqual } = require("./util/source");
* @property {AssetInfo} info info about the asset
*/
/** @typedef {(length: number) => string} HashWithLengthFunction */
/**
* @typedef {object} ModulePathData
* @property {string | number} id
* @property {string} hash
* @property {((length: number) => string)=} hashWithLength
* @property {HashWithLengthFunction=} hashWithLength
*/
/** @typedef {(id: string | number) => string | number} PrepareIdFunction */
/**
* @typedef {object} PathData
* @property {ChunkGraph=} chunkGraph
* @property {string=} hash
* @property {((length: number) => string)=} hashWithLength
* @property {HashWithLengthFunction=} hashWithLength
* @property {(Chunk | ChunkPathData)=} chunk
* @property {(Module | ModulePathData)=} module
* @property {RuntimeSpec=} runtime
@@ -332,9 +344,10 @@ const { isSourceEqual } = require("./util/source");
* @property {string=} query
* @property {string=} contentHashType
* @property {string=} contentHash
* @property {((length: number) => string)=} contentHashWithLength
* @property {HashWithLengthFunction=} contentHashWithLength
* @property {boolean=} noChunkHash
* @property {string=} url
* @property {PrepareIdFunction=} prepareId
*/
/** @typedef {"module" | "chunk" | "root-of-chunk" | "nested"} ExcludeModulesType */
@@ -697,8 +710,8 @@ class Compilation {
) => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}.
BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`;
/**
* @param {string | (import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions)} options hook options
* @returns {import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions} modified options
* @param {string | (import("tapable").TapOptions & { name: string } & ProcessAssetsAdditionalOptions)} options hook options
* @returns {import("tapable").TapOptions & { name: string } & ProcessAssetsAdditionalOptions} modified options
*/
const getOptions = (options) => {
if (typeof options === "string") options = { name: options };
@@ -1218,20 +1231,20 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.emittedAssets = new Set();
/** @type {Set<string>} */
this.comparedForEmitAssets = new Set();
/** @type {LazySet<string>} */
/** @type {FileSystemDependencies} */
this.fileDependencies = new LazySet();
/** @type {LazySet<string>} */
/** @type {FileSystemDependencies} */
this.contextDependencies = new LazySet();
/** @type {LazySet<string>} */
/** @type {FileSystemDependencies} */
this.missingDependencies = new LazySet();
/** @type {LazySet<string>} */
/** @type {FileSystemDependencies} */
this.buildDependencies = new LazySet();
// TODO webpack 6 remove
this.compilationDependencies = {
add: util.deprecate(
/**
* @param {string} item item
* @returns {LazySet<string>} file dependencies
* @returns {FileSystemDependencies} file dependencies
*/
(item) => this.fileDependencies.add(item),
"Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)",
@@ -3744,6 +3757,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
dependencyTemplates,
runtimeTemplate,
runtime,
runtimes,
codeGenerationResults: results,
compilation: this
});

6
node_modules/webpack/lib/Compiler.js generated vendored Executable file → Normal file
View File

@@ -719,9 +719,9 @@ class Compiler {
({ name: file, source, info }, callback) => {
let targetFile = file;
let immutable = info.immutable;
const queryStringIdx = targetFile.indexOf("?");
if (queryStringIdx >= 0) {
targetFile = targetFile.slice(0, queryStringIdx);
const queryOrHashStringIdx = targetFile.search(/[?#]/);
if (queryOrHashStringIdx >= 0) {
targetFile = targetFile.slice(0, queryOrHashStringIdx);
// We may remove the hash, which is in the query string
// So we recheck if the file is immutable
// This doesn't cover all cases, but immutable is only a performance optimization anyway

0
node_modules/webpack/lib/ConcatenationScope.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/ConcurrentCompilationError.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/ConditionalInitFragment.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/ConstPlugin.js generated vendored Executable file → Normal file
View File

View File

@@ -9,7 +9,10 @@ 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_TYPE,
JAVASCRIPT_TYPES
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const Template = require("./Template");
@@ -162,7 +165,7 @@ class ContextModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -1184,7 +1187,7 @@ module.exports = webpackEmptyAsyncContext;`;
const { chunkGraph, compilation } = context;
const sources = new Map();
sources.set(
"javascript",
JAVASCRIPT_TYPE,
this.getSource(
this.getSourceString(this.options.mode, context),
compilation

View File

@@ -15,6 +15,8 @@ const { cachedSetProperty } = require("./util/cleverMerge");
const { createFakeHook } = require("./util/deprecation");
const { join } = require("./util/fs");
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/** @typedef {import("./Compilation").FileSystemDependencies} FileSystemDependencies */
/** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */
/** @typedef {import("./ContextModule").ResolveDependenciesCallback} ResolveDependenciesCallback */
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
@@ -22,7 +24,7 @@ const { join } = require("./util/fs");
/** @typedef {import("./ResolverFactory")} ResolverFactory */
/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
/** @typedef {import("./dependencies/ContextDependency").ContextOptions} ContextOptions */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/**
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
@@ -36,9 +38,9 @@ const { join } = require("./util/fs");
* @property {string} context
* @property {string} request
* @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions
* @property {LazySet<string>} fileDependencies
* @property {LazySet<string>} missingDependencies
* @property {LazySet<string>} contextDependencies
* @property {FileSystemDependencies} fileDependencies
* @property {FileSystemDependencies} missingDependencies
* @property {FileSystemDependencies} contextDependencies
* @property {ContextDependency[]} dependencies
*/

View File

@@ -5,6 +5,7 @@
"use strict";
const { SyncWaterfallHook } = require("tapable");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
@@ -32,6 +33,7 @@ const createHash = require("./util/createHash");
/** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperties} DestructuringAssignmentProperties */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {null | undefined | RegExp | EXPECTED_FUNCTION | string | number | boolean | bigint | undefined} CodeValuePrimitive */
/** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive | RuntimeValue>} CodeValue */
@@ -42,7 +44,7 @@ const createHash = require("./util/createHash");
* @property {string[]=} contextDependencies
* @property {string[]=} missingDependencies
* @property {string[]=} buildDependencies
* @property {string| (() => string)=} version
* @property {string | (() => string)=} version
*/
/** @typedef {(value: { module: NormalModule, key: string, readonly version: ValueCacheVersion }) => CodeValuePrimitive} GeneratorFn */
@@ -180,7 +182,7 @@ const stringifyObj = (
code = `{${keys
.map((key) => {
const code = obj[key];
return `${JSON.stringify(key)}:${toCode(
return `${key === "__proto__" ? '["__proto__"]' : JSON.stringify(key)}:${toCode(
code,
parser,
valueCacheVersions,
@@ -330,7 +332,30 @@ const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp(
);
const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require);
/**
* @typedef {object} DefinePluginHooks
* @property {SyncWaterfallHook<[Record<string, CodeValue>]>} definitions
*/
/** @type {WeakMap<Compilation, DefinePluginHooks>} */
const compilationHooksMap = new WeakMap();
class DefinePlugin {
/**
* @param {Compilation} compilation the compilation
* @returns {DefinePluginHooks} the attached hooks
*/
static getCompilationHooks(compilation) {
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
definitions: new SyncWaterfallHook(["definitions"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/**
* Create a new define plugin
* @param {Record<string, CodeValue>} definitions A map of global object definitions
@@ -358,6 +383,12 @@ class DefinePlugin {
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
const definitions = this.definitions;
const hooks = DefinePlugin.getCompilationHooks(compilation);
hooks.definitions.tap(PLUGIN_NAME, (previousDefinitions) => ({
...previousDefinitions,
...definitions
}));
/**
* @type {Map<string, Set<string>>}
@@ -505,7 +536,7 @@ class DefinePlugin {
return;
}
/** @type {Record<string, CodeValue>} */
const obj = {};
const obj = Object.create(null);
const finalSet = finalByNestedKey.get(nested);
for (const { id } of destructed) {
const fullKey = `${nested}.${id}`;

View File

@@ -7,7 +7,10 @@
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
@@ -80,7 +83,7 @@ class DelegatedModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -177,9 +180,9 @@ class DelegatedModule extends Module {
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set("javascript", new OriginalSource(str, this.identifier()));
sources.set(JAVASCRIPT_TYPE, new OriginalSource(str, this.identifier()));
} else {
sources.set("javascript", new RawSource(str));
sources.set(JAVASCRIPT_TYPE, new RawSource(str));
}
return {

View File

@@ -7,7 +7,10 @@
const { RawSource } = require("webpack-sources");
const Module = require("./Module");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const makeSerializable = require("./util/makeSerializable");
@@ -53,7 +56,7 @@ class DllModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -92,7 +95,7 @@ class DllModule extends Module {
codeGeneration(context) {
const sources = new Map();
sources.set(
"javascript",
JAVASCRIPT_TYPE,
new RawSource(`module.exports = ${RuntimeGlobals.require};`)
);
return {

View File

@@ -54,7 +54,7 @@ const validate = createSchemaValidation(
* @returns {Env} parsed environment variables object
*/
function parse(src) {
const obj = /** @type {Env} */ ({});
const obj = /** @type {Env} */ (Object.create(null));
// Convert buffer to string
let lines = src.toString();
@@ -174,7 +174,7 @@ function expandValue(value, processEnv, runningParsed) {
*/
function expand(options) {
// for use with progressive expansion
const runningParsed = /** @type {Env} */ ({});
const runningParsed = /** @type {Env} */ (Object.create(null));
const processEnv = options.processEnv;
// dotenv.config() ran before this so the assumption is process.env has already been set
@@ -183,7 +183,8 @@ function expand(options) {
// short-circuit scenario: process.env was already set prior to the file value
value =
processEnv[key] && processEnv[key] !== value
Object.prototype.hasOwnProperty.call(processEnv, key) &&
processEnv[key] !== value
? /** @type {string} */ (processEnv[key])
: expandValue(value, processEnv, runningParsed);
@@ -332,7 +333,7 @@ class DotenvPlugin {
// Parse all files and merge (later files override earlier ones)
// Similar to Vite's implementation
const parsed = /** @type {Env} */ ({});
const parsed = /** @type {Env} */ (Object.create(null));
for (const content of contents) {
if (!content) continue;
@@ -422,7 +423,7 @@ class DotenvPlugin {
// Make a copy of process.env so that dotenv-expand doesn't modify global process.env
const processEnv = { ...process.env };
expand({ parsed, processEnv });
const env = /** @type {Env} */ ({});
const env = /** @type {Env} */ (Object.create(null));
// Get all keys from parser and process.env
const keys = [...Object.keys(parsed), ...Object.keys(process.env)];
@@ -430,7 +431,11 @@ class DotenvPlugin {
// Prioritize actual env variables from `process.env`, fallback to parsed
for (const key of keys) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env[key] = process.env[key] ? process.env[key] : parsed[key];
env[key] =
Object.prototype.hasOwnProperty.call(process.env, key) &&
process.env[key]
? process.env[key]
: parsed[key];
}
}

View File

@@ -1346,11 +1346,11 @@ class ExportInfo {
export: rawTarget.export,
deferred: Boolean(
rawTarget.connection.dependency &&
ImportPhaseUtils.isDefer(
/** @type {HarmonyImportDependency} */ (
rawTarget.connection.dependency
).phase
)
ImportPhaseUtils.isDefer(
/** @type {HarmonyImportDependency} */ (
rawTarget.connection.dependency
).phase
)
)
};
for (;;) {

View File

@@ -14,8 +14,9 @@ const Module = require("./Module");
const {
CSS_IMPORT_TYPES,
CSS_URL_TYPES,
JS_TYPES
} = require("./ModuleSourceTypesConstants");
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const Template = require("./Template");
@@ -86,7 +87,7 @@ const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]);
const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([
RuntimeGlobals.definePropertyGetters
]);
const EMPTY_RUNTIME_REQUIREMENTS = new Set([]);
const EMPTY_RUNTIME_REQUIREMENTS = new Set();
/**
* @param {string | string[]} variableName the variable name or path
@@ -655,7 +656,7 @@ class ExternalModule extends Module {
return CSS_IMPORT_TYPES;
}
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -979,7 +980,7 @@ class ExternalModule extends Module {
case "asset": {
const sources = new Map();
sources.set(
"javascript",
JAVASCRIPT_TYPE,
new RawSource(`module.exports = ${JSON.stringify(request)};`)
);
const data = new Map();
@@ -1064,11 +1065,11 @@ class ExternalModule extends Module {
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set(
"javascript",
JAVASCRIPT_TYPE,
new OriginalSource(sourceString, this.identifier())
);
} else {
sources.set("javascript", new RawSource(sourceString));
sources.set(JAVASCRIPT_TYPE, new RawSource(sourceString));
}
let runtimeRequirements = sourceData.runtimeRequirements;

View File

@@ -26,7 +26,7 @@ const { cachedSetProperty, resolveByProperty } = require("./util/cleverMerge");
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {((context: string, request: string, callback: (err?: Error | null, result?: string | false, resolveRequest?: import('enhanced-resolve').ResolveRequest) => void) => void)} ExternalItemFunctionDataGetResolveCallbackResult */
/** @typedef {((context: string, request: string, callback: (err?: Error | null, result?: string | false, resolveRequest?: import("enhanced-resolve").ResolveRequest) => void) => void)} ExternalItemFunctionDataGetResolveCallbackResult */
/** @typedef {((context: string, request: string) => Promise<string>)} ExternalItemFunctionDataGetResolveResult */
/** @typedef {(options?: ResolveOptions) => ExternalItemFunctionDataGetResolveCallbackResult | ExternalItemFunctionDataGetResolveResult} ExternalItemFunctionDataGetResolve */

View File

@@ -939,7 +939,7 @@ const mergeSets = (a, b) => {
* Finding file or directory to manage
* @param {string} managedPath path that is managing by {@link FileSystemInfo}
* @param {string} path path to file or directory
* @returns {string|null} managed item
* @returns {string | null} managed item
* @example
* getManagedItem(
* '/Users/user/my-project/node_modules/',

View File

@@ -5,6 +5,8 @@
"use strict";
const { JAVASCRIPT_TYPE } = require("./ModuleSourceTypeConstants");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
@@ -13,6 +15,7 @@
/** @typedef {import("./Module").CodeGenerationResultData} CodeGenerationResultData */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./Module").SourceType} SourceType */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./NormalModule")} NormalModule */
@@ -30,7 +33,7 @@
* @property {RuntimeSpec} runtime the runtime
* @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
* @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
* @property {string} type which kind of code should be generated
* @property {SourceType} type which kind of code should be generated
* @property {() => CodeGenerationResultData=} getData get access to the code generation data
*/
@@ -52,7 +55,7 @@
class Generator {
/**
* @param {Record<string, Generator>} map map of types
* @param {{ [key in SourceType]?: Generator }} map map of types
* @returns {ByTypeGenerator} generator by type
*/
static byType(map) {
@@ -75,7 +78,7 @@ class Generator {
/**
* @abstract
* @param {NormalModule} module the module
* @param {string=} type source type
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
@@ -138,12 +141,12 @@ function generateError(error, module, generateContext) {
class ByTypeGenerator extends Generator {
/**
* @param {Record<string, Generator>} map map of types
* @param {{ [key in SourceType]?: Generator }} map map of types
*/
constructor(map) {
super();
this.map = map;
this._types = new Set(Object.keys(map));
this._types = /** @type {SourceTypes} */ (new Set(Object.keys(map)));
/** @type {GenerateErrorFn | undefined} */
this.generateError = generateError.bind(this);
}
@@ -158,10 +161,10 @@ class ByTypeGenerator extends Generator {
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type = "javascript") {
getSize(module, type = JAVASCRIPT_TYPE) {
const t = type;
const generator = this.map[t];
return generator ? generator.getSize(module, t) : 0;

View File

@@ -6,6 +6,10 @@
"use strict";
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/**
* @template T
@@ -22,18 +26,43 @@ class HookWebpackError extends WebpackError {
* @param {string} hook name of hook
*/
constructor(error, hook) {
super(error.message);
super(error ? error.message : undefined, error ? { cause: error } : {});
this.name = "HookWebpackError";
this.hook = hook;
this.error = error;
this.name = "HookWebpackError";
this.hideStack = true;
this.details = `caused by plugins in ${hook}\n${error.stack}`;
this.stack += `\n-- inner error --\n${error ? error.stack : ""}`;
this.details = `caused by plugins in ${hook}\n${error ? error.stack : ""}`;
}
this.stack += `\n-- inner error --\n${error.stack}`;
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.error);
write(this.hook);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.error = read();
this.hook = read();
super.deserialize(context);
}
}
makeSerializable(HookWebpackError, "webpack/lib/HookWebpackError");
module.exports = HookWebpackError;
/**

View File

@@ -19,6 +19,7 @@ const {
const NormalModule = require("./NormalModule");
const RuntimeGlobals = require("./RuntimeGlobals");
const WebpackError = require("./WebpackError");
const { chunkHasCss } = require("./css/CssModulesPlugin");
const ConstDependency = require("./dependencies/ConstDependency");
const ImportMetaHotAcceptDependency = require("./dependencies/ImportMetaHotAcceptDependency");
const ImportMetaHotDeclineDependency = require("./dependencies/ImportMetaHotDeclineDependency");
@@ -817,6 +818,7 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
filename,
{ removedChunkIds, removedModules, updatedChunkIds, assetInfo }
] of hotUpdateMainContentByFilename) {
/** @type {{c: ChunkId[], r: ChunkId[], m: ModuleId[], css?: {r: ChunkId[]}}} */
const hotUpdateMainJson = {
c: [...updatedChunkIds],
r: [...removedChunkIds],
@@ -833,6 +835,26 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
]
};
// Build CSS removed chunks list (chunks in updatedChunkIds that no longer have CSS)
/** @type {ChunkId[]} */
const cssRemovedChunkIds = [];
if (compilation.options.experiments.css) {
for (const chunkId of updatedChunkIds) {
for (const /** @type {Chunk} */ chunk of compilation.chunks) {
if (chunk.id === chunkId) {
if (!chunkHasCss(chunk, chunkGraph)) {
cssRemovedChunkIds.push(chunkId);
}
break;
}
}
}
}
if (cssRemovedChunkIds.length > 0) {
hotUpdateMainJson.css = { r: cssRemovedChunkIds };
}
const source = new RawSource(
(filename.endsWith(".json") ? "" : "export default ") +
JSON.stringify(hotUpdateMainJson)

View File

@@ -52,7 +52,7 @@ class ManifestPlugin {
constructor(options) {
validate(options);
/** @type {ManifestPluginOptions & Required<Omit<ManifestPluginOptions, "filter" | "generate">>} */
/** @type {ManifestPluginOptions & Required<Omit<ManifestPluginOptions, "filter" | "generate">>} */
this.options = {
filename: "manifest.json",
prefix: "[publicpath]",

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

@@ -9,7 +9,11 @@ const util = require("util");
const ChunkGraph = require("./ChunkGraph");
const DependenciesBlock = require("./DependenciesBlock");
const ModuleGraph = require("./ModuleGraph");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const {
JAVASCRIPT_TYPE,
UNKNOWN_TYPE
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_TYPES } = require("./ModuleSourceTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const { first } = require("./util/SetHelpers");
const { compareChunksById } = require("./util/comparators");
@@ -24,12 +28,14 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").FileSystemDependencies} FileSystemDependencies */
/** @typedef {import("./Compilation").UnsafeCacheData} UnsafeCacheData */
/** @typedef {import("./ConcatenationScope")} ConcatenationScope */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplate").CssData} CssData */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./ModuleSourceTypeConstants").AllTypes} AllTypes */
/** @typedef {import("./FileSystemInfo")} FileSystemInfo */
/** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
@@ -70,7 +76,9 @@ const makeSerializable = require("./util/makeSerializable");
* @property {string=} type the type of source that should be generated
*/
/** @typedef {ReadonlySet<string>} SourceTypes */
/** @typedef {AllTypes} KnownSourceType */
/** @typedef {KnownSourceType | string} SourceType */
/** @typedef {ReadonlySet<SourceType>} SourceTypes */
// TODO webpack 6: compilation will be required in CodeGenerationContext
/**
@@ -80,6 +88,7 @@ const makeSerializable = require("./util/makeSerializable");
* @property {ModuleGraph} moduleGraph the module graph
* @property {ChunkGraph} chunkGraph the chunk graph
* @property {RuntimeSpec} runtime the runtimes code should be generated for
* @property {RuntimeSpec[]} runtimes all runtimes code should be generated for
* @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
@@ -103,7 +112,7 @@ const makeSerializable = require("./util/makeSerializable");
/**
* @typedef {object} CodeGenerationResult
* @property {Map<string, Source>} sources the resulting sources for all source types
* @property {Map<SourceType, Source>} sources the resulting sources for all source types
* @property {CodeGenerationResultData=} data the resulting data for all source types
* @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)
@@ -126,12 +135,10 @@ const makeSerializable = require("./util/makeSerializable");
* @property {boolean=} sideEffectFree
* @property {boolean=} isCSSModule
* @property {Record<string, string>=} jsIncompatibleExports
* @property {Record<string, string>=} exportsFinalName
* @property {string=} factoryExportsBinding
* @property {Map<RuntimeSpec, Record<string, string>>=} exportsFinalNameByRuntime
* @property {Map<RuntimeSpec, string>=} exportsSourceByRuntime
*/
/** @typedef {LazySet<string>} FileSystemDependencies */
/**
* @typedef {object} KnownBuildInfo
* @property {boolean=} cacheable
@@ -188,7 +195,8 @@ const EMPTY_RESOLVE_OPTIONS = {};
let debugId = 1000;
const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]);
/** @type {SourceTypes} */
const DEFAULT_TYPES_UNKNOWN = new Set([UNKNOWN_TYPE]);
const deprecatedNeedRebuild = util.deprecate(
/**
@@ -839,8 +847,8 @@ class Module extends DependenciesBlock {
/**
* @deprecated Use needBuild instead
* @param {Map<string, number|null>} fileTimestamps timestamps of files
* @param {Map<string, number|null>} contextTimestamps timestamps of directories
* @param {Map<string, number | null>} fileTimestamps timestamps of files
* @param {Map<string, number | null>} contextTimestamps timestamps of directories
* @returns {boolean} true, if the module needs a rebuild
*/
needRebuild(fileTimestamps, contextTimestamps) {
@@ -928,7 +936,7 @@ class Module extends DependenciesBlock {
if (this.source === Module.prototype.source) {
return DEFAULT_TYPES_UNKNOWN;
}
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -936,10 +944,10 @@ class Module extends DependenciesBlock {
* @deprecated Use codeGeneration() instead
* @param {DependencyTemplates} dependencyTemplates the dependency templates
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {string=} type the type of source that should be generated
* @param {SourceType=} type the type of source that should be generated
* @returns {Source} generated source
*/
source(dependencyTemplates, runtimeTemplate, type = "javascript") {
source(dependencyTemplates, runtimeTemplate, type = JAVASCRIPT_TYPE) {
if (this.codeGeneration === Module.prototype.codeGeneration) {
const AbstractMethodError = require("./AbstractMethodError");
@@ -957,6 +965,7 @@ class Module extends DependenciesBlock {
moduleGraph: chunkGraph.moduleGraph,
chunkGraph,
runtime: undefined,
runtimes: [],
codeGenerationResults: undefined
};
const sources = this.codeGeneration(codeGenContext).sources;
@@ -964,7 +973,7 @@ class Module extends DependenciesBlock {
return /** @type {Source} */ (
type
? sources.get(type)
: sources.get(/** @type {string} */ (first(this.getSourceTypes())))
: sources.get(/** @type {SourceType} */ (first(this.getSourceTypes())))
);
}
@@ -1019,7 +1028,7 @@ class Module extends DependenciesBlock {
// Best override this method
const sources = new Map();
for (const type of this.getSourceTypes()) {
if (type !== "unknown") {
if (type !== UNKNOWN_TYPE) {
sources.set(
type,
this.source(

View File

@@ -17,7 +17,7 @@ const makeSerializable = require("./util/makeSerializable");
class ModuleBuildError extends WebpackError {
/**
* @param {string | ErrorWithHideStack} err error thrown
* @param {{from?: string|null}} info additional info
* @param {{from?: string | null}} info additional info
*/
constructor(err, { from = null } = {}) {
let message = "Module build failed";

View File

@@ -15,7 +15,7 @@ const makeSerializable = require("./util/makeSerializable");
class ModuleError extends WebpackError {
/**
* @param {Error} err error thrown
* @param {{from?: string|null}} info additional info
* @param {{from?: string | null}} info additional info
*/
constructor(err, { from = null } = {}) {
let message = "Module Error";

View File

@@ -281,7 +281,7 @@ ModuleFilenameHelpers.createFilename = (
* @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
* @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

View File

@@ -169,6 +169,12 @@ class ModuleGraph {
* @private
*/
this._dependencySourceOrderMap = new WeakMap();
/**
* @type {Set<Module>}
* @private
*/
this._modulesNeedingSort = new Set();
}
/**
@@ -305,17 +311,15 @@ class ModuleGraph {
// import { a, b } from "lib" -> a and b have the same source order -> a = b = 1
// import { d } from "lib/d" -> d = 2
const currentSourceOrder =
/** @type { HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */ (
dependency
).sourceOrder;
/** @type {HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */
(dependency).sourceOrder;
// lib/index.js (reexport)
// import { a } from "lib/a" -> a = 0
// import { b } from "lib/b" -> b = 1
const originSourceOrder =
/** @type { HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */ (
originDependency
).sourceOrder;
/** @type {HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */
(originDependency).sourceOrder;
if (
typeof currentSourceOrder === "number" &&
typeof originSourceOrder === "number"
@@ -330,17 +334,28 @@ class ModuleGraph {
sub: originSourceOrder
});
// Save for later batch sorting
this._modulesNeedingSort.add(parentModule);
}
}
/**
* @returns {void}
*/
finishUpdateParent() {
if (this._modulesNeedingSort.size === 0) {
return;
}
for (const mod of this._modulesNeedingSort) {
// If dependencies like HarmonyImportSideEffectDependency and HarmonyImportSpecifierDependency have a SourceOrder,
// we sort based on it; otherwise, we preserve the original order.
sortWithSourceOrder(
parentModule.dependencies,
this._dependencySourceOrderMap
mod.dependencies,
this._dependencySourceOrderMap,
(dep, index) => this.setParentDependenciesBlockIndex(dep, index)
);
for (const [index, dep] of parentModule.dependencies.entries()) {
this.setParentDependenciesBlockIndex(dep, index);
}
}
this._modulesNeedingSort.clear();
}
/**

View File

@@ -52,8 +52,8 @@ const intersectConnectionStates = (a, b) => {
class ModuleGraphConnection {
/**
* @param {Module|null} originModule the referencing module
* @param {Dependency|null} dependency the referencing dependency
* @param {Module | null} originModule the referencing module
* @param {Dependency | null} dependency the referencing dependency
* @param {Module} module the referenced module
* @param {string=} explanation some extra detail
* @param {boolean=} weak the reference is weak

189
node_modules/webpack/lib/ModuleSourceTypeConstants.js generated vendored Executable file
View File

@@ -0,0 +1,189 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Akait @alexander-akait
*/
"use strict";
/**
* @type {Readonly<"javascript">}
*/
const JAVASCRIPT_TYPE = "javascript";
/**
* @type {Readonly<"runtime">}
*/
const RUNTIME_TYPE = "runtime";
/**
* @type {Readonly<"webassembly">}
*/
const WEBASSEMBLY_TYPE = "webassembly";
/**
* @type {Readonly<"asset">}
*/
const ASSET_TYPE = "asset";
/**
* @type {Readonly<"css">}
*/
const CSS_TYPE = "css";
/**
* @type {Readonly<"css-import">}
*/
const CSS_IMPORT_TYPE = "css-import";
/**
* @type {Readonly<"css-url">}
*/
const CSS_URL_TYPE = "css-url";
/**
* @type {Readonly<"share-init">}
*/
const SHARED_INIT_TYPE = "share-init";
/**
* @type {Readonly<"remote">}
*/
const REMOTE_GENERATOR_TYPE = "remote";
/**
* @type {Readonly<"consume-shared">}
*/
const CONSUME_SHARED_GENERATOR_TYPE = "consume-shared";
/**
* @type {Readonly<"unknown">}
*/
const UNKNOWN_TYPE = "unknown";
/**
* @typedef {JAVASCRIPT_TYPE |
* RUNTIME_TYPE |
* WEBASSEMBLY_TYPE |
* ASSET_TYPE |
* CSS_TYPE |
* CSS_IMPORT_TYPE |
* CSS_URL_TYPE |
* SHARED_INIT_TYPE |
* REMOTE_GENERATOR_TYPE |
* CONSUME_SHARED_GENERATOR_TYPE |
* UNKNOWN_TYPE} AllTypes
*/
/**
* @type {ReadonlySet<never>}
*/
const NO_TYPES = new Set();
/**
* @type {ReadonlySet<"asset">}
*/
const ASSET_TYPES = new Set([ASSET_TYPE]);
/**
* @type {ReadonlySet<"asset" | "javascript" | "asset">}
*/
const ASSET_AND_JAVASCRIPT_TYPES = new Set([ASSET_TYPE, JAVASCRIPT_TYPE]);
/**
* @type {ReadonlySet<"css-url" | "asset">}
*/
const ASSET_AND_CSS_URL_TYPES = new Set([ASSET_TYPE, CSS_URL_TYPE]);
/**
* @type {ReadonlySet<"javascript" | "css-url" | "asset">}
*/
const ASSET_AND_JAVASCRIPT_AND_CSS_URL_TYPES = new Set([
ASSET_TYPE,
JAVASCRIPT_TYPE,
CSS_URL_TYPE
]);
/**
* @type {ReadonlySet<"javascript">}
*/
const JAVASCRIPT_TYPES = new Set([JAVASCRIPT_TYPE]);
/**
* @type {ReadonlySet<"javascript" | "css-url">}
*/
const JAVASCRIPT_AND_CSS_URL_TYPES = new Set([JAVASCRIPT_TYPE, CSS_URL_TYPE]);
/**
* @type {ReadonlySet<"javascript" | "css">}
*/
const JAVASCRIPT_AND_CSS_TYPES = new Set([JAVASCRIPT_TYPE, CSS_TYPE]);
/**
* @type {ReadonlySet<"css">}
*/
const CSS_TYPES = new Set([CSS_TYPE]);
/**
* @type {ReadonlySet<"css-url">}
*/
const CSS_URL_TYPES = new Set([CSS_URL_TYPE]);
/**
* @type {ReadonlySet<"css-import">}
*/
const CSS_IMPORT_TYPES = new Set([CSS_IMPORT_TYPE]);
/**
* @type {ReadonlySet<"webassembly">}
*/
const WEBASSEMBLY_TYPES = new Set([WEBASSEMBLY_TYPE]);
/**
* @type {ReadonlySet<"runtime">}
*/
const RUNTIME_TYPES = new Set([RUNTIME_TYPE]);
/**
* @type {ReadonlySet<"remote" | "share-init">}
*/
const REMOTE_AND_SHARE_INIT_TYPES = new Set([
REMOTE_GENERATOR_TYPE,
SHARED_INIT_TYPE
]);
/**
* @type {ReadonlySet<"consume-shared">}
*/
const CONSUME_SHARED_TYPES = new Set([CONSUME_SHARED_GENERATOR_TYPE]);
/**
* @type {ReadonlySet<"share-init">}
*/
const SHARED_INIT_TYPES = new Set([SHARED_INIT_TYPE]);
module.exports.ASSET_AND_CSS_URL_TYPES = ASSET_AND_CSS_URL_TYPES;
module.exports.ASSET_AND_JAVASCRIPT_AND_CSS_URL_TYPES =
ASSET_AND_JAVASCRIPT_AND_CSS_URL_TYPES;
module.exports.ASSET_AND_JAVASCRIPT_TYPES = ASSET_AND_JAVASCRIPT_TYPES;
module.exports.ASSET_TYPE = ASSET_TYPE;
module.exports.ASSET_TYPES = ASSET_TYPES;
module.exports.CONSUME_SHARED_TYPES = CONSUME_SHARED_TYPES;
module.exports.CSS_IMPORT_TYPE = CSS_IMPORT_TYPE;
module.exports.CSS_IMPORT_TYPES = CSS_IMPORT_TYPES;
module.exports.CSS_TYPE = CSS_TYPE;
module.exports.CSS_TYPE = CSS_TYPE;
module.exports.CSS_TYPES = CSS_TYPES;
module.exports.CSS_URL_TYPE = CSS_URL_TYPE;
module.exports.CSS_URL_TYPES = CSS_URL_TYPES;
module.exports.JAVASCRIPT_AND_CSS_TYPES = JAVASCRIPT_AND_CSS_TYPES;
module.exports.JAVASCRIPT_AND_CSS_URL_TYPES = JAVASCRIPT_AND_CSS_URL_TYPES;
module.exports.JAVASCRIPT_TYPE = JAVASCRIPT_TYPE;
module.exports.JAVASCRIPT_TYPES = JAVASCRIPT_TYPES;
module.exports.NO_TYPES = NO_TYPES;
module.exports.REMOTE_AND_SHARE_INIT_TYPES = REMOTE_AND_SHARE_INIT_TYPES;
module.exports.RUNTIME_TYPE = RUNTIME_TYPE;
module.exports.RUNTIME_TYPES = RUNTIME_TYPES;
module.exports.SHARED_INIT_TYPE = SHARED_INIT_TYPE;
module.exports.SHARED_INIT_TYPES = SHARED_INIT_TYPES;
module.exports.UNKNOWN_TYPE = UNKNOWN_TYPE;
module.exports.WEBASSEMBLY_TYPE = WEBASSEMBLY_TYPE;
module.exports.WEBASSEMBLY_TYPES = WEBASSEMBLY_TYPES;

View File

@@ -1,117 +0,0 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Akait @alexander-akait
*/
"use strict";
/**
* @type {ReadonlySet<never>}
*/
const NO_TYPES = new Set();
/**
* @type {ReadonlySet<"asset">}
*/
const ASSET_TYPES = new Set(["asset"]);
/**
* @type {ReadonlySet<"asset" | "javascript" | "asset">}
*/
const ASSET_AND_JS_TYPES = new Set(["asset", "javascript"]);
/**
* @type {ReadonlySet<"css-url" | "asset">}
*/
const ASSET_AND_CSS_URL_TYPES = new Set(["asset", "css-url"]);
/**
* @type {ReadonlySet<"javascript" | "css-url" | "asset">}
*/
const ASSET_AND_JS_AND_CSS_URL_TYPES = new Set([
"asset",
"javascript",
"css-url"
]);
/**
* @type {"javascript"}
*/
const JS_TYPE = "javascript";
/**
* @type {ReadonlySet<"javascript">}
*/
const JS_TYPES = new Set(["javascript"]);
/**
* @type {ReadonlySet<"javascript" | "css-url">}
*/
const JS_AND_CSS_URL_TYPES = new Set(["javascript", "css-url"]);
/**
* @type {ReadonlySet<"javascript" | "css">}
*/
const JS_AND_CSS_TYPES = new Set(["javascript", "css"]);
/**
* @type {"css"}
*/
const CSS_TYPE = "css";
/**
* @type {ReadonlySet<"css">}
*/
const CSS_TYPES = new Set(["css"]);
/**
* @type {ReadonlySet<"css-url">}
*/
const CSS_URL_TYPES = new Set(["css-url"]);
/**
* @type {ReadonlySet<"css-import">}
*/
const CSS_IMPORT_TYPES = new Set(["css-import"]);
/**
* @type {ReadonlySet<"webassembly">}
*/
const WEBASSEMBLY_TYPES = new Set(["webassembly"]);
/**
* @type {ReadonlySet<"runtime">}
*/
const RUNTIME_TYPES = new Set(["runtime"]);
/**
* @type {ReadonlySet<"remote" | "share-init">}
*/
const REMOTE_AND_SHARE_INIT_TYPES = new Set(["remote", "share-init"]);
/**
* @type {ReadonlySet<"consume-shared">}
*/
const CONSUME_SHARED_TYPES = new Set(["consume-shared"]);
/**
* @type {ReadonlySet<"share-init">}
*/
const SHARED_INIT_TYPES = new Set(["share-init"]);
module.exports.ASSET_AND_CSS_URL_TYPES = ASSET_AND_CSS_URL_TYPES;
module.exports.ASSET_AND_JS_AND_CSS_URL_TYPES = ASSET_AND_JS_AND_CSS_URL_TYPES;
module.exports.ASSET_AND_JS_TYPES = ASSET_AND_JS_TYPES;
module.exports.ASSET_TYPES = ASSET_TYPES;
module.exports.CONSUME_SHARED_TYPES = CONSUME_SHARED_TYPES;
module.exports.CSS_IMPORT_TYPES = CSS_IMPORT_TYPES;
module.exports.CSS_TYPE = CSS_TYPE;
module.exports.CSS_TYPES = CSS_TYPES;
module.exports.CSS_URL_TYPES = CSS_URL_TYPES;
module.exports.JS_AND_CSS_TYPES = JS_AND_CSS_TYPES;
module.exports.JS_AND_CSS_URL_TYPES = JS_AND_CSS_URL_TYPES;
module.exports.JS_TYPE = JS_TYPE;
module.exports.JS_TYPES = JS_TYPES;
module.exports.NO_TYPES = NO_TYPES;
module.exports.REMOTE_AND_SHARE_INIT_TYPES = REMOTE_AND_SHARE_INIT_TYPES;
module.exports.RUNTIME_TYPES = RUNTIME_TYPES;
module.exports.SHARED_INIT_TYPES = SHARED_INIT_TYPES;
module.exports.WEBASSEMBLY_TYPES = WEBASSEMBLY_TYPES;

View File

@@ -97,7 +97,7 @@ const ASSET_MODULE_TYPE_BYTES = "asset/bytes";
/**
* @type {Readonly<"asset/raw-data-url">}
* TODO: Document what this asset type is for. See css-loader tests for its usage.
* This is the module type used for the ignored asset module.
*/
const ASSET_MODULE_TYPE_RAW_DATA_URL = "asset/raw-data-url";
@@ -110,21 +110,18 @@ const WEBPACK_MODULE_TYPE_RUNTIME = "runtime";
/**
* @type {Readonly<"fallback-module">}
* This is the module type used for the ModuleFederation feature's FallbackModule class.
* TODO: Document this better.
*/
const WEBPACK_MODULE_TYPE_FALLBACK = "fallback-module";
/**
* @type {Readonly<"remote-module">}
* This is the module type used for the ModuleFederation feature's RemoteModule class.
* TODO: Document this better.
*/
const WEBPACK_MODULE_TYPE_REMOTE = "remote-module";
/**
* @type {Readonly<"provide-module">}
* This is the module type used for the ModuleFederation feature's ProvideModule class.
* TODO: Document this better.
*/
const WEBPACK_MODULE_TYPE_PROVIDE = "provide-module";

View File

@@ -15,7 +15,7 @@ const makeSerializable = require("./util/makeSerializable");
class ModuleWarning extends WebpackError {
/**
* @param {Error} warning error thrown
* @param {{from?: string|null}} info additional info
* @param {{from?: string | null}} info additional info
*/
constructor(warning, { from = null } = {}) {
let message = "Module Warning";

View File

@@ -245,45 +245,46 @@ class NodeStuffPlugin {
parser.hooks.expression
.for(expressionName)
.tap(PLUGIN_NAME, (expr) => {
// We use `CachedConstDependency` because of `eval` devtool, there is no `import.meta` inside `eval()`
const { importMetaName, environment, module } =
compilation.outputOptions;
if (
module &&
importMetaName === "import.meta" &&
(expressionName === "import.meta.filename" ||
expressionName === "import.meta.dirname") &&
environment.importMetaDirnameAndFilename
) {
return true;
}
// Generate `import.meta.dirname` and `import.meta.filename` when:
// - they are supported by the environment
// - it is a universal target, because we can't use `import mod from "node:url"; ` at the top file
const dep =
if (
environment.importMetaDirnameAndFilename ||
(compiler.platform.web === null &&
compiler.platform.node === null &&
module)
? new ConstDependency(
`${importMetaName}.${property}`,
/** @type {Range} */
(expr.range)
)
: new ExternalModuleDependency(
"url",
[
{
name: "fileURLToPath",
value: URL_MODULE_CONSTANT_FUNCTION_NAME
}
],
undefined,
`${URL_MODULE_CONSTANT_FUNCTION_NAME}(${value()})`,
/** @type {Range} */ (expr.range),
`__webpack_${property}__`
);
) {
const dep = new CachedConstDependency(
`${importMetaName}.${property}`,
/** @type {Range} */
(expr.range),
`__webpack_${property}__`,
CachedConstDependency.PLACE_CHUNK
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return;
}
const dep = new ExternalModuleDependency(
"url",
[
{
name: "fileURLToPath",
value: URL_MODULE_CONSTANT_FUNCTION_NAME
}
],
undefined,
`${URL_MODULE_CONSTANT_FUNCTION_NAME}(${value()})`,
/** @type {Range} */ (expr.range),
`__webpack_${property}__`,
ExternalModuleDependency.PLACE_CHUNK
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
@@ -300,20 +301,25 @@ class NodeStuffPlugin {
compilation.outputOptions;
if (
module &&
importMetaName === "import.meta" &&
(expressionName === "import.meta.filename" ||
expressionName === "import.meta.dirname") &&
environment.importMetaDirnameAndFilename
environment.importMetaDirnameAndFilename ||
(compiler.platform.web === null &&
compiler.platform.node === null &&
module)
) {
return `${property}: ${importMetaName}.${property},`;
const dep = new CachedConstDependency(
`${importMetaName}.${property}`,
null,
`__webpack_${property}__`,
CachedConstDependency.PLACE_CHUNK
);
dep.loc = /** @type {DependencyLocation} */ (
usingProperty.loc
);
parser.state.module.addPresentationalDependency(dep);
return `${property}: __webpack_${property}__,`;
}
if (environment.importMetaDirnameAndFilename) {
return `${property}: ${importMetaName}.${property},`;
}
const dep = new ExternalModuleInitFragmentDependency(
const dep = new ExternalModuleDependency(
"url",
[
{
@@ -321,13 +327,17 @@ class NodeStuffPlugin {
value: URL_MODULE_CONSTANT_FUNCTION_NAME
}
],
undefined
undefined,
`${URL_MODULE_CONSTANT_FUNCTION_NAME}(${value()})`,
null,
`__webpack_${property}__`,
ExternalModuleDependency.PLACE_CHUNK
);
dep.loc = /** @type {DependencyLocation} */ (usingProperty.loc);
parser.state.module.addPresentationalDependency(dep);
return `${property}: ${URL_MODULE_CONSTANT_FUNCTION_NAME}(${value()}),`;
return `${property}: __webpack_${property}__,`;
}
});
}

View File

@@ -79,7 +79,8 @@ const memoize = require("./util/memoize");
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").SourceType} SourceType */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./Module").UnsafeCacheData} UnsafeCacheData */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
@@ -394,7 +395,7 @@ class NormalModule extends Module {
this._source = null;
/**
* @private
* @type {Map<string | undefined, number> | undefined}
* @type {Map<undefined | SourceType, number> | undefined}
*/
this._sourceSizes = undefined;
/**
@@ -699,7 +700,8 @@ class NormalModule extends Module {
options = parseJson(options);
} catch (err) {
throw new Error(
`Cannot parse string options: ${/** @type {Error} */ (err).message}`
`Cannot parse string options: ${/** @type {Error} */ (err).message}`,
{ cause: err }
);
}
} else {
@@ -1307,7 +1309,7 @@ class NormalModule extends Module {
/** @type {undefined | Set<string>} */
let nonAbsoluteDependencies;
/**
* @param {LazySet<string>} deps deps
* @param {FileSystemDependencies} deps deps
*/
const checkDependencies = (deps) => {
for (const dep of deps) {

View File

@@ -38,6 +38,7 @@ const {
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/** @typedef {import("../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
/** @typedef {import("./Compilation").FileSystemDependencies} FileSystemDependencies */
/** @typedef {import("./Generator")} Generator */
/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
@@ -61,7 +62,7 @@ const {
* @typedef {import("./Compiler").Callback<T>} Callback
*/
/** @typedef {Pick<RuleSetRule, 'type' | 'sideEffects' | 'parser' | 'generator' | 'resolve' | 'layer' | 'extractSourceMap'>} ModuleSettings */
/** @typedef {Pick<RuleSetRule, "type" | "sideEffects" | "parser" | "generator" | "resolve" | "layer" | "extractSourceMap">} ModuleSettings */
/** @typedef {Partial<NormalModuleCreateData & { settings: ModuleSettings }>} CreateData */
/**
@@ -74,9 +75,9 @@ const {
* @property {ModuleDependency[]} dependencies
* @property {string} dependencyType
* @property {CreateData} createData
* @property {LazySet<string>} fileDependencies
* @property {LazySet<string>} missingDependencies
* @property {LazySet<string>} contextDependencies
* @property {FileSystemDependencies} fileDependencies
* @property {FileSystemDependencies} missingDependencies
* @property {FileSystemDependencies} contextDependencies
* @property {Module=} ignoredModule
* @property {boolean} cacheable allow to use the unsafe cache
*/
@@ -296,14 +297,10 @@ const ruleSetCompiler = new RuleSetCompiler([
/** @typedef {import("./css/CssParser")} CssParser */
/** @typedef {import("../declarations/WebpackOptions").CssParserOptions} CssParserOptions */
/** @typedef {import("../declarations/WebpackOptions").CssAutoParserOptions} CssAutoParserOptions */
/** @typedef {import("../declarations/WebpackOptions").CssGlobalParserOptions} CssGlobalParserOptions */
/** @typedef {import("../declarations/WebpackOptions").CssModuleParserOptions} CssModuleParserOptions */
/** @typedef {import("./css/CssGenerator")} CssGenerator */
/** @typedef {import("../declarations/WebpackOptions").CssGeneratorOptions} CssGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").CssGlobalGeneratorOptions} CssGlobalGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */
/**
* @typedef {[
@@ -319,9 +316,9 @@ const ruleSetCompiler = new RuleSetCompiler([
* [WEBASSEMBLY_MODULE_TYPE_ASYNC, AsyncWebAssemblyParser, EmptyParserOptions, Generator, EmptyParserOptions],
* [WEBASSEMBLY_MODULE_TYPE_SYNC, WebAssemblyParser, EmptyParserOptions, Generator, EmptyParserOptions],
* [CSS_MODULE_TYPE, CssParser, CssParserOptions, CssGenerator, CssGeneratorOptions],
* [CSS_MODULE_TYPE_AUTO, CssParser, CssAutoParserOptions, CssGenerator, CssAutoGeneratorOptions],
* [CSS_MODULE_TYPE_AUTO, CssParser, CssModuleParserOptions, CssGenerator, CssModuleGeneratorOptions],
* [CSS_MODULE_TYPE_MODULE, CssParser, CssModuleParserOptions, CssGenerator, CssModuleGeneratorOptions],
* [CSS_MODULE_TYPE_GLOBAL, CssParser, CssGlobalParserOptions, CssGenerator, CssGlobalGeneratorOptions],
* [CSS_MODULE_TYPE_GLOBAL, CssParser, CssModuleParserOptions, CssGenerator, CssModuleGeneratorOptions],
* [string, Parser, ParserOptions, Generator, GeneratorOptions],
* ]} ParsersAndGeneratorsByTypes
*/

2
node_modules/webpack/lib/Parser.js generated vendored
View File

@@ -20,7 +20,7 @@
* @property {WebpackOptions} options
*/
/** @typedef {Record<string, EXPECTED_ANY> & ParserStateBase} ParserState */
/** @typedef {ParserStateBase & Record<string, EXPECTED_ANY>} ParserState */
class Parser {
/* istanbul ignore next */

View File

@@ -7,7 +7,10 @@
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const makeSerializable = require("./util/makeSerializable");
@@ -49,7 +52,7 @@ class RawModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -122,11 +125,11 @@ class RawModule extends Module {
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set(
"javascript",
JAVASCRIPT_TYPE,
new OriginalSource(this.sourceStr, this.identifier())
);
} else {
sources.set("javascript", new RawSource(this.sourceStr));
sources.set(JAVASCRIPT_TYPE, new RawSource(this.sourceStr));
}
return { sources, runtimeRequirements: this.runtimeRequirements };
}

View File

@@ -8,7 +8,7 @@
const { RawSource } = require("webpack-sources");
const OriginalSource = require("webpack-sources").OriginalSource;
const Module = require("./Module");
const { RUNTIME_TYPES } = require("./ModuleSourceTypesConstants");
const { RUNTIME_TYPES } = require("./ModuleSourceTypeConstants");
const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */

View File

@@ -127,6 +127,10 @@ class RuntimeTemplate {
return this.outputOptions.environment.const;
}
supportsMethodShorthand() {
return this.outputOptions.environment.methodShorthand;
}
supportsArrowFunction() {
return this.outputOptions.environment.arrowFunction;
}
@@ -956,7 +960,7 @@ class RuntimeTemplate {
* @param {string} options.request the request
* @param {string | string[]} options.exportName the export name
* @param {Module} options.originModule the origin module
* @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
* @param {boolean | undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
* @param {boolean} options.isCall true, if expression will be called
* @param {boolean | null} options.callContext when false, call context will not be preserved
* @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated

View File

@@ -6,7 +6,7 @@
"use strict";
/**
* @param {number} size the size in bytes
* @param {number=} size the size in bytes
* @returns {string} the formatted size
*/
module.exports.formatSize = (size) => {

View File

@@ -496,7 +496,12 @@ class SourceMapDevToolPlugin {
if (options.debugIds) {
const debugId = generateDebugId(source, sourceMap.file);
sourceMap.debugId = debugId;
currentSourceMappingURLComment = `\n//# debugId=${debugId}${currentSourceMappingURLComment}`;
const debugIdComment = `\n//# debugId=${debugId}`;
currentSourceMappingURLComment =
currentSourceMappingURLComment
? `${debugIdComment}${currentSourceMappingURLComment}`
: debugIdComment;
}
const sourceMapString = JSON.stringify(sourceMap);

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

@@ -280,7 +280,7 @@ class Template {
/**
* @param {ChunkRenderContext} renderContext render context
* @param {Module[]} modules modules to render (should be ordered by identifier)
* @param {(module: Module) => Source | null} renderModule function to render a module
* @param {(module: Module, renderInArray?: boolean) => 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
*/
@@ -290,12 +290,20 @@ class Template {
if (modules.length === 0) {
return null;
}
/** @type {{ id: ModuleId, source: Source | "false" }[]} */
const allModules = modules.map((module) => ({
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
source: renderModule(module) || "false"
/** @type {{ id: ModuleId, module: Module }[]} */
const modulesWithId = modules.map((m) => ({
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(m)),
module: m
}));
const bounds = Template.getModulesArrayBounds(allModules);
const bounds = Template.getModulesArrayBounds(modulesWithId);
const renderInObject = bounds === false;
/** @type {{ id: ModuleId, source: Source | "false" }[]} */
const allModules = modulesWithId.map(({ id, module }) => ({
id,
source: renderModule(module, renderInObject) || "false"
}));
if (bounds) {
// Render a spare array
const minId = bounds[0];
@@ -332,7 +340,9 @@ class Template {
if (i !== 0) {
source.add(",\n");
}
source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
source.add(
`\n/***/ ${JSON.stringify(module.id)}${renderContext.runtimeTemplate.supportsMethodShorthand() && module.source !== "false" ? "" : ":"}\n`
);
source.add(module.source);
}
source.add(`\n\n${prefix}}`);
@@ -363,6 +373,7 @@ class Template {
moduleGraph: renderContext.moduleGraph,
runtimeTemplate: renderContext.runtimeTemplate,
runtime: renderContext.chunk.runtime,
runtimes: [renderContext.chunk.runtime],
codeGenerationResults
});
if (!codeGenResult) continue;

View File

@@ -20,10 +20,7 @@ const { parseResource } = require("./util/identifier");
const REGEXP = /\[\\*([\w:]+)\\*\]/gi;
/**
* @param {string | number} id id
* @returns {string | number} result
*/
/** @type {PathData["prepareId"]} */
const prepareId = (id) => {
if (typeof id !== "string") return id;
@@ -303,7 +300,7 @@ const replacePathVariables = (path, data, assetInfo) => {
const module = data.module;
const idReplacer = replacer(() =>
prepareId(
(data.prepareId || prepareId)(
module instanceof Module
? /** @type {ModuleId} */
(/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
@@ -353,7 +350,9 @@ const replacePathVariables = (path, data, assetInfo) => {
if (typeof data.runtime === "string") {
replacements.set(
"runtime",
replacer(() => prepareId(/** @type {string} */ (data.runtime)))
replacer(() =>
(data.prepareId || prepareId)(/** @type {string} */ (data.runtime))
)
);
} else {
replacements.set("runtime", replacer("_"));

View File

@@ -21,7 +21,6 @@ class WebpackError extends Error {
* @param {{ cause?: unknown }} options error options
*/
constructor(message, options = {}) {
// @ts-expect-error ES2018 doesn't `Error.cause`, but it can be used by developers
super(message, options);
/** @type {string=} */

View File

@@ -111,11 +111,11 @@ class WebpackOptionsApply extends OptionsApply {
const NodeTargetPlugin = require("./node/NodeTargetPlugin");
// Some older versions of Node.js don't support all built-in modules via import, only via `require`,
// but шt seems like there shouldn't be a warning here since these versions are rarely used in real applications
// but it seems like there shouldn't be a warning here since these versions are rarely used in real applications
new NodeTargetPlugin(
options.output.module &&
compiler.platform.node === null &&
compiler.platform.web === null
compiler.platform.node === null &&
compiler.platform.web === null
? "module-import"
: "node-commonjs"
).apply(compiler);
@@ -408,6 +408,39 @@ class WebpackOptionsApply extends OptionsApply {
typeof options.experiments.lazyCompilation === "object"
? options.experiments.lazyCompilation
: {};
const isUniversalTarget =
options.output.module &&
compiler.platform.node === null &&
compiler.platform.web === null;
if (isUniversalTarget) {
const emitter = require.resolve("../hot/emitter-event-target.js");
const NormalModuleReplacementPlugin = require("./NormalModuleReplacementPlugin");
// Override emitter that using `EventEmitter` to `EventTarget`
// TODO webpack6 - migrate to `EventTarget` by default
new NormalModuleReplacementPlugin(/emitter(\.js)?$/, (result) => {
if (
/webpack[/\\]hot|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test(
result.context
)
) {
result.request = emitter;
}
return result;
}).apply(compiler);
}
const backend = require.resolve(
isUniversalTarget
? "../hot/lazy-compilation-universal.js"
: `../hot/lazy-compilation-${
options.externalsPresets.node ? "node" : "web"
}.js`
);
new LazyCompilationPlugin({
backend:
typeof lazyOptions.backend === "function"
@@ -415,12 +448,7 @@ class WebpackOptionsApply extends OptionsApply {
: require("./hmr/lazyCompilationBackend")({
...lazyOptions.backend,
client:
(lazyOptions.backend && lazyOptions.backend.client) ||
require.resolve(
`../hot/lazy-compilation-${
options.externalsPresets.node ? "node" : "web"
}.js`
)
(lazyOptions.backend && lazyOptions.backend.client) || backend
}),
entries: !lazyOptions || lazyOptions.entries !== false,
imports: !lazyOptions || lazyOptions.imports !== false,

26
node_modules/webpack/lib/asset/AssetBytesGenerator.js generated vendored Executable file → Normal file
View File

@@ -9,16 +9,20 @@ const { RawSource } = require("webpack-sources");
const ConcatenationScope = require("../ConcatenationScope");
const Generator = require("../Generator");
const {
CSS_TYPE,
CSS_URL_TYPE,
CSS_URL_TYPES,
JS_AND_CSS_URL_TYPES,
JS_TYPES,
JAVASCRIPT_AND_CSS_URL_TYPES,
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES,
NO_TYPES
} = require("../ModuleSourceTypesConstants");
} = require("../ModuleSourceTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceType} SourceType */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
@@ -46,7 +50,7 @@ class AssetSourceGenerator extends Generator {
const data = getData ? getData() : undefined;
switch (type) {
case "javascript": {
case JAVASCRIPT_TYPE: {
if (!originalSource) {
return new RawSource("");
}
@@ -72,7 +76,7 @@ class AssetSourceGenerator extends Generator {
}
return new RawSource(sourceContent);
}
case "css-url": {
case CSS_URL_TYPE: {
if (!originalSource) {
return null;
}
@@ -99,7 +103,7 @@ class AssetSourceGenerator extends Generator {
*/
generateError(error, module, generateContext) {
switch (generateContext.type) {
case "javascript": {
case JAVASCRIPT_TYPE: {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
@@ -136,12 +140,12 @@ class AssetSourceGenerator extends Generator {
}
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
return JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) {
return JAVASCRIPT_AND_CSS_URL_TYPES;
} else if (sourceTypes.has(CSS_TYPE)) {
return CSS_URL_TYPES;
}
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
return NO_TYPES;
@@ -149,7 +153,7 @@ class AssetSourceGenerator extends Generator {
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {

0
node_modules/webpack/lib/asset/AssetBytesParser.js generated vendored Executable file → Normal file
View File

54
node_modules/webpack/lib/asset/AssetGenerator.js generated vendored Executable file → Normal file
View File

@@ -11,14 +11,17 @@ const ConcatenationScope = require("../ConcatenationScope");
const Generator = require("../Generator");
const {
ASSET_AND_CSS_URL_TYPES,
ASSET_AND_JS_AND_CSS_URL_TYPES,
ASSET_AND_JS_TYPES,
ASSET_AND_JAVASCRIPT_AND_CSS_URL_TYPES,
ASSET_AND_JAVASCRIPT_TYPES,
ASSET_TYPES,
CSS_TYPE,
CSS_URL_TYPE,
CSS_URL_TYPES,
JS_AND_CSS_URL_TYPES,
JS_TYPES,
JAVASCRIPT_AND_CSS_URL_TYPES,
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES,
NO_TYPES
} = require("../ModuleSourceTypesConstants");
} = require("../ModuleSourceTypeConstants");
const { ASSET_MODULE_TYPE } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const CssUrlDependency = require("../dependencies/CssUrlDependency");
@@ -43,6 +46,7 @@ const getMimeTypes = memoize(() => require("mime-types"));
/** @typedef {import("../Module").NameForCondition} NameForCondition */
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceType} SourceType */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
@@ -331,7 +335,7 @@ class AssetGenerator extends Generator {
let assetPath;
if (generatorOptions.publicPath !== undefined && type === "javascript") {
if (generatorOptions.publicPath !== undefined && type === JAVASCRIPT_TYPE) {
const { path, info } = runtimeTemplate.compilation.getAssetPathWithInfo(
generatorOptions.publicPath,
{
@@ -346,7 +350,7 @@ class AssetGenerator extends Generator {
assetPath = JSON.stringify(path + filename);
} else if (
generatorOptions.publicPath !== undefined &&
type === "css-url"
type === CSS_URL_TYPE
) {
const { path, info } = runtimeTemplate.compilation.getAssetPathWithInfo(
generatorOptions.publicPath,
@@ -360,14 +364,14 @@ class AssetGenerator extends Generator {
);
assetInfo = mergeAssetInfo(assetInfo, info);
assetPath = path + filename;
} else if (type === "javascript") {
} else if (type === JAVASCRIPT_TYPE) {
// add __webpack_require__.p
runtimeRequirements.add(RuntimeGlobals.publicPath);
assetPath = runtimeTemplate.concatenation(
{ expr: RuntimeGlobals.publicPath },
filename
);
} else if (type === "css-url") {
} else if (type === CSS_URL_TYPE) {
const compilation = runtimeTemplate.compilation;
const path =
compilation.outputOptions.publicPath === "auto"
@@ -518,7 +522,7 @@ class AssetGenerator extends Generator {
let content;
const needContent = type === "javascript" || type === "css-url";
const needContent = type === JAVASCRIPT_TYPE || type === CSS_URL_TYPE;
const data = getData ? getData() : undefined;
@@ -529,7 +533,9 @@ class AssetGenerator extends Generator {
) {
const encodedSource = this.generateDataUri(module);
content =
type === "javascript" ? JSON.stringify(encodedSource) : encodedSource;
type === JAVASCRIPT_TYPE
? JSON.stringify(encodedSource)
: encodedSource;
if (data) {
data.set("url", { [type]: content, ...data.get("url") });
@@ -570,7 +576,7 @@ class AssetGenerator extends Generator {
contentHash
);
if (data && (type === "javascript" || type === "css-url")) {
if (data && (type === JAVASCRIPT_TYPE || type === CSS_URL_TYPE)) {
data.set("url", { [type]: assetPath, ...data.get("url") });
}
@@ -598,7 +604,7 @@ class AssetGenerator extends Generator {
content = assetPath;
}
if (type === "javascript") {
if (type === JAVASCRIPT_TYPE) {
if (concatenationScope) {
concatenationScope.registerNamespaceExport(
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
@@ -614,7 +620,7 @@ class AssetGenerator extends Generator {
runtimeRequirements.add(RuntimeGlobals.module);
return new RawSource(`${module.moduleArgument}.exports = ${content};`);
} else if (type === "css-url") {
} else if (type === CSS_URL_TYPE) {
return null;
}
@@ -632,7 +638,7 @@ class AssetGenerator extends Generator {
case "asset": {
return new RawSource(error.message);
}
case "javascript": {
case JAVASCRIPT_TYPE: {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
@@ -661,24 +667,24 @@ class AssetGenerator extends Generator {
if ((module.buildInfo && module.buildInfo.dataUrl) || this.emit === false) {
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
return JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) {
return JAVASCRIPT_AND_CSS_URL_TYPES;
} else if (sourceTypes.has(CSS_TYPE)) {
return CSS_URL_TYPES;
}
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
return NO_TYPES;
}
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
return ASSET_AND_JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) {
return ASSET_AND_JAVASCRIPT_AND_CSS_URL_TYPES;
} else if (sourceTypes.has(CSS_TYPE)) {
return ASSET_AND_CSS_URL_TYPES;
}
return ASSET_AND_JS_TYPES;
return ASSET_AND_JAVASCRIPT_TYPES;
}
return ASSET_TYPES;
@@ -686,7 +692,7 @@ class AssetGenerator extends Generator {
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {

0
node_modules/webpack/lib/asset/AssetModulesPlugin.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/asset/AssetParser.js generated vendored Executable file → Normal file
View File

26
node_modules/webpack/lib/asset/AssetSourceGenerator.js generated vendored Executable file → Normal file
View File

@@ -9,16 +9,20 @@ const { RawSource } = require("webpack-sources");
const ConcatenationScope = require("../ConcatenationScope");
const Generator = require("../Generator");
const {
CSS_TYPE,
CSS_URL_TYPE,
CSS_URL_TYPES,
JS_AND_CSS_URL_TYPES,
JS_TYPES,
JAVASCRIPT_AND_CSS_URL_TYPES,
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES,
NO_TYPES
} = require("../ModuleSourceTypesConstants");
} = require("../ModuleSourceTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceType} SourceType */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
@@ -46,7 +50,7 @@ class AssetSourceGenerator extends Generator {
const data = getData ? getData() : undefined;
switch (type) {
case "javascript": {
case JAVASCRIPT_TYPE: {
if (!originalSource) {
return new RawSource("");
}
@@ -71,7 +75,7 @@ class AssetSourceGenerator extends Generator {
}
return new RawSource(sourceContent);
}
case "css-url": {
case CSS_URL_TYPE: {
if (!originalSource) {
return null;
}
@@ -98,7 +102,7 @@ class AssetSourceGenerator extends Generator {
*/
generateError(error, module, generateContext) {
switch (generateContext.type) {
case "javascript": {
case JAVASCRIPT_TYPE: {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
@@ -135,12 +139,12 @@ class AssetSourceGenerator extends Generator {
}
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
return JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) {
return JAVASCRIPT_AND_CSS_URL_TYPES;
} else if (sourceTypes.has(CSS_TYPE)) {
return CSS_URL_TYPES;
}
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
return NO_TYPES;
@@ -148,7 +152,7 @@ class AssetSourceGenerator extends Generator {
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {

0
node_modules/webpack/lib/asset/AssetSourceParser.js generated vendored Executable file → Normal file
View File

View File

@@ -7,7 +7,10 @@
const { RawSource } = require("webpack-sources");
const Module = require("../Module");
const { JS_TYPES } = require("../ModuleSourceTypesConstants");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("../ModuleSourceTypeConstants");
const { ASSET_MODULE_TYPE_RAW_DATA_URL } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const makeSerializable = require("../util/makeSerializable");
@@ -47,7 +50,7 @@ class RawDataUrlModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -113,7 +116,7 @@ class RawDataUrlModule extends Module {
}
const sources = new Map();
sources.set(
"javascript",
JAVASCRIPT_TYPE,
new RawSource(`module.exports = ${JSON.stringify(this.url)};`)
);
const data = new Map();

0
node_modules/webpack/lib/async-modules/AsyncModuleHelpers.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/async-modules/AwaitDependenciesInitFragment.js generated vendored Executable file → Normal file
View File

6
node_modules/webpack/lib/buildChunkGraph.js generated vendored Executable file → Normal file
View File

@@ -352,10 +352,12 @@ const visitModules = (
/** @type {Map<ChunkGroupInfo, Set<DependenciesBlock>>} */
const blocksByChunkGroups = new Map();
/** @type {Map<string, ChunkGroupInfo>} */
/** @typedef {Map<string, ChunkGroupInfo>} NamedChunkGroup */
/** @type {NamedChunkGroup} */
const namedChunkGroups = new Map();
/** @type {Map<string, ChunkGroupInfo>} */
/** @type {NamedChunkGroup} */
const namedAsyncEntrypoints = new Map();
/** @type {Set<ChunkGroupInfo>} */

0
node_modules/webpack/lib/cache/AddBuildDependenciesPlugin.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/lib/cache/AddManagedPathsPlugin.js generated vendored Executable file → Normal file
View File

View File

@@ -18,6 +18,7 @@ const {
} = require("../util/serialization");
/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */
/** @typedef {import("../Compilation").FileSystemDependencies} FileSystemDependencies */
/** @typedef {import("../Cache").Data} Data */
/** @typedef {import("../Cache").Etag} Etag */
/** @typedef {import("../Compiler")} Compiler */
@@ -51,7 +52,7 @@ class PackContainer {
resolveResults,
resolveBuildDependenciesSnapshot
) {
/** @type {Pack | (() => Pack) } */
/** @type {Pack | (() => Pack)} */
this.data = data;
/** @type {string} */
this.version = version;
@@ -395,7 +396,7 @@ class Pack {
return;
}
/** @type {PackContent[] } */
/** @type {PackContent[]} */
const mergedContent = [];
// 3. Remove old content entries
@@ -1109,7 +1110,7 @@ class PackFileCacheStrategy {
compression,
readonly
}) {
/** @type {import("../serialization/Serializer")<PackContainer, null, {}>} */
/** @type {import("../serialization/Serializer")<PackContainer, null, EXPECTED_OBJECT>} */
this.fileSerializer = createFileSerializer(
fs,
/** @type {string | Hash} */
@@ -1140,7 +1141,7 @@ class PackFileCacheStrategy {
this.snapshot = snapshot;
/** @type {BuildDependencies} */
this.buildDependencies = new Set();
/** @type {LazySet<string>} */
/** @type {FileSystemDependencies} */
this.newBuildDependencies = new LazySet();
/** @type {Snapshot | undefined} */
this.resolveBuildDependenciesSnapshot = undefined;
@@ -1364,7 +1365,7 @@ class PackFileCacheStrategy {
}
/**
* @param {LazySet<string> | Iterable<string>} dependencies dependencies to store
* @param {FileSystemDependencies | Iterable<string>} dependencies dependencies to store
*/
storeBuildDependencies(dependencies) {
if (this.readonly) return;

45
node_modules/webpack/lib/cli.js generated vendored Executable file → Normal file
View File

@@ -795,49 +795,8 @@ const init = (open, close, replace) =>
filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace);
/**
* @typedef {{
* reset: PrintFunction
* bold: PrintFunction
* dim: PrintFunction
* italic: PrintFunction
* underline: PrintFunction
* inverse: PrintFunction
* hidden: PrintFunction
* strikethrough: PrintFunction
* black: PrintFunction
* red: PrintFunction
* green: PrintFunction
* yellow: PrintFunction
* blue: PrintFunction
* magenta: PrintFunction
* cyan: PrintFunction
* white: PrintFunction
* gray: PrintFunction
* bgBlack: PrintFunction
* bgRed: PrintFunction
* bgGreen: PrintFunction
* bgYellow: PrintFunction
* bgBlue: PrintFunction
* bgMagenta: PrintFunction
* bgCyan: PrintFunction
* bgWhite: PrintFunction
* blackBright: PrintFunction
* redBright: PrintFunction
* greenBright: PrintFunction
* yellowBright: PrintFunction
* blueBright: PrintFunction
* magentaBright: PrintFunction
* cyanBright: PrintFunction
* whiteBright: PrintFunction
* bgBlackBright: PrintFunction
* bgRedBright: PrintFunction
* bgGreenBright: PrintFunction
* bgYellowBright: PrintFunction
* bgBlueBright: PrintFunction
* bgMagentaBright: PrintFunction
* bgCyanBright: PrintFunction
* bgWhiteBright: PrintFunction
}} Colors */
* @typedef {{ reset: PrintFunction, bold: PrintFunction, dim: PrintFunction, italic: PrintFunction, underline: PrintFunction, inverse: PrintFunction, hidden: PrintFunction, strikethrough: PrintFunction, black: PrintFunction, red: PrintFunction, green: PrintFunction, yellow: PrintFunction, blue: PrintFunction, magenta: PrintFunction, cyan: PrintFunction, white: PrintFunction, gray: PrintFunction, bgBlack: PrintFunction, bgRed: PrintFunction, bgGreen: PrintFunction, bgYellow: PrintFunction, bgBlue: PrintFunction, bgMagenta: PrintFunction, bgCyan: PrintFunction, bgWhite: PrintFunction, blackBright: PrintFunction, redBright: PrintFunction, greenBright: PrintFunction, yellowBright: PrintFunction, blueBright: PrintFunction, magentaBright: PrintFunction, cyanBright: PrintFunction, whiteBright: PrintFunction, bgBlackBright: PrintFunction, bgRedBright: PrintFunction, bgGreenBright: PrintFunction, bgYellowBright: PrintFunction, bgBlueBright: PrintFunction, bgMagentaBright: PrintFunction, bgCyanBright: PrintFunction, bgWhiteBright: PrintFunction }} Colors
*/
/**
* @typedef {object} ColorsOptions

19
node_modules/webpack/lib/config/browserslistTargetHandler.js generated vendored Executable file → Normal file
View File

@@ -118,6 +118,25 @@ const resolve = (browsers) => {
kaios: [2, 5],
node: [6, 0]
}),
methodShorthand: rawChecker({
chrome: 47,
and_chr: 47,
edge: 12,
firefox: 34,
and_ff: 34,
// ie: Not supported,
opera: 34,
op_mob: 34,
safari: 9,
ios_saf: 9,
samsung: 5,
android: 47,
// baidu: Not tracked,
and_qq: [14, 9],
and_uc: [15, 5],
kaios: [2, 5],
node: [4, 9]
}),
arrowFunction: rawChecker({
chrome: 45,
and_chr: 45,

View File

@@ -7,6 +7,11 @@
const fs = require("fs");
const path = require("path");
const {
CSS_TYPE,
JAVASCRIPT_TYPE,
UNKNOWN_TYPE
} = require("../ModuleSourceTypeConstants");
const {
ASSET_MODULE_TYPE,
ASSET_MODULE_TYPE_BYTES,
@@ -52,6 +57,9 @@ const {
/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */
/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */
/** @typedef {import("../../declarations/WebpackOptions").HashSalt} HashSalt */
/** @typedef {import("../../declarations/WebpackOptions").HashSalt} HashDigest */
/** @typedef {import("../../declarations/WebpackOptions").HashDigestLength} HashDigestLength */
/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */
/** @typedef {import("../../declarations/WebpackOptions").OptimizationNormalized} Optimization */
@@ -390,6 +398,15 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
applyModuleDefaults(options.module, {
cache,
hashSalt: /** @type {NonNullable<Output["hashSalt"]>} */ (
options.output.hashSalt
),
hashDigest: /** @type {NonNullable<Output["hashDigest"]>} */ (
options.output.hashDigest
),
hashDigestLength: /** @type {NonNullable<Output["hashDigestLength"]>} */ (
options.output.hashDigestLength
),
syncWebAssembly:
/** @type {NonNullable<ExperimentsNormalized["syncWebAssembly"]>} */
(options.experiments.syncWebAssembly),
@@ -766,11 +783,17 @@ const applyCssGeneratorOptionsDefaults = (
* @param {boolean} options.deferImport is defer import enabled
* @param {TargetProperties | false} options.targetProperties target properties
* @param {Mode | undefined} options.mode mode
* @param {HashSalt} options.hashSalt hash salt
* @param {HashDigest} options.hashDigest hash digest
* @param {HashDigestLength} options.hashDigestLength hash digest length
* @returns {void}
*/
const applyModuleDefaults = (
module,
{
hashSalt,
hashDigest,
hashDigestLength,
cache,
syncWebAssembly,
asyncWebAssembly,
@@ -871,6 +894,51 @@ const applyModuleDefaults = (
true
);
for (const type of [
CSS_MODULE_TYPE_AUTO,
CSS_MODULE_TYPE_MODULE,
CSS_MODULE_TYPE_GLOBAL
]) {
F(module.parser, type, () => ({}));
D(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.parser[type]),
"animation",
true
);
D(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.parser[type]),
"container",
true
);
D(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.parser[type]),
"customIdents",
true
);
D(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.parser[type]),
"dashedIdents",
true
);
D(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.parser[type]),
"function",
true
);
D(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<ParserOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.parser[type]),
"grid",
true
);
}
F(module.generator, CSS_MODULE_TYPE, () => ({}));
applyCssGeneratorOptionsDefaults(
@@ -880,49 +948,58 @@ const applyModuleDefaults = (
);
const localIdentName =
uniqueName.length > 0 ? "[uniqueName]-[id]-[local]" : "[id]-[local]";
mode === "development"
? uniqueName.length > 0
? "[uniqueName]-[id]-[local]"
: "[id]-[local]"
: "[fullhash]";
const localIdentHashSalt = hashSalt;
const localIdentHashDigest = "base64url";
const localIdentHashDigestLength = 6;
const exportsConvention = "as-is";
F(module.generator, CSS_MODULE_TYPE_AUTO, () => ({}));
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]>} */
(module.generator[CSS_MODULE_TYPE_AUTO]),
"localIdentName",
localIdentName
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]>} */
(module.generator[CSS_MODULE_TYPE_AUTO]),
"exportsConvention",
"as-is"
);
for (const type of [
CSS_MODULE_TYPE_AUTO,
CSS_MODULE_TYPE_MODULE,
CSS_MODULE_TYPE_GLOBAL
]) {
F(module.generator, type, () => ({}));
F(module.generator, CSS_MODULE_TYPE_MODULE, () => ({}));
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]>} */
(module.generator[CSS_MODULE_TYPE_MODULE]),
"localIdentName",
localIdentName
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]>} */
(module.generator[CSS_MODULE_TYPE_MODULE]),
"exportsConvention",
"as-is"
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.generator[type]),
"localIdentName",
localIdentName
);
F(module.generator, CSS_MODULE_TYPE_GLOBAL, () => ({}));
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.generator[CSS_MODULE_TYPE_GLOBAL]),
"localIdentName",
localIdentName
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.generator[CSS_MODULE_TYPE_GLOBAL]),
"exportsConvention",
"as-is"
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.generator[type]),
"localIdentHashSalt",
localIdentHashSalt
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]>} */
(module.generator[type]),
"localIdentHashDigest",
localIdentHashDigest
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]>} */
(module.generator[type]),
"localIdentHashDigestLength",
localIdentHashDigestLength
);
D(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_AUTO]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_MODULE]> | NonNullable<GeneratorOptionsByModuleTypeKnown[CSS_MODULE_TYPE_GLOBAL]>} */
(module.generator[type]),
"exportsConvention",
exportsConvention
);
}
}
A(module, "defaultRules", () => {
@@ -1218,6 +1295,12 @@ const applyOutputDefaults = (
"const",
() => tp && optimistic(/** @type {boolean | undefined} */ (tp.const))
);
F(
environment,
"methodShorthand",
() =>
tp && optimistic(/** @type {boolean | undefined} */ (tp.methodShorthand))
);
F(
environment,
"arrowFunction",
@@ -1331,7 +1414,7 @@ const applyOutputDefaults = (
}
return "[id].css";
});
D(output, "assetModuleFilename", "[hash][ext][query]");
D(output, "assetModuleFilename", "[hash][ext][query][fragment]");
D(output, "webassemblyModuleFilename", "[hash].module.wasm");
D(output, "compareBeforeEmit", true);
D(output, "charset", !futureDefaults);
@@ -1516,7 +1599,7 @@ const applyOutputDefaults = (
*/
const forEachEntry = (fn) => {
for (const name of Object.keys(entry)) {
fn(/** @type {{[k: string] : EntryDescription}} */ (entry)[name]);
fn(/** @type {{ [k: string]: EntryDescription }} */ (entry)[name]);
}
};
A(output, "enabledLibraryTypes", () => {
@@ -1792,7 +1875,9 @@ const applyOptimizationDefaults = (
const { splitChunks } = optimization;
if (splitChunks) {
A(splitChunks, "defaultSizeTypes", () =>
css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"]
css
? [JAVASCRIPT_TYPE, CSS_TYPE, UNKNOWN_TYPE]
: [JAVASCRIPT_TYPE, UNKNOWN_TYPE]
);
D(splitChunks, "hidePathInfo", production);
D(splitChunks, "chunks", "async");

View File

@@ -54,7 +54,7 @@ const nestedConfig = (value, fn) =>
/**
* @template T
* @param {T|undefined} value value or not
* @param {T | undefined} value value or not
* @returns {T} result value
*/
const cloneObject = (value) => /** @type {T} */ ({ ...value });
@@ -90,7 +90,7 @@ const optionalNestedArray = (value, fn) =>
/**
* @template T
* @template R
* @param {Record<string, T>|undefined} value value or not
* @param {Record<string, T> | undefined} value value or not
* @param {(value: T) => R} fn nested handler
* @param {Record<string, (value: T) => R>=} customKeys custom nested handler for some keys
* @returns {Record<string, R>} result value

View File

@@ -55,6 +55,7 @@ const getDefaultTarget = (context) => {
* @property {boolean | null} globalThis has globalThis variable available
* @property {boolean | null} bigIntLiteral big int literal syntax is available
* @property {boolean | null} const const and let variable declarations are available
* @property {boolean | null} methodShorthand object method shorthand is available
* @property {boolean | null} arrowFunction arrow functions are available
* @property {boolean | null} forOf for of iteration is available
* @property {boolean | null} destructuring destructuring is available
@@ -192,6 +193,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
const: v(6),
templateLiteral: v(4),
optionalChaining: v(14),
methodShorthand: v(4),
arrowFunction: v(6),
asyncFunction: v(7, 6),
forOf: v(5),
@@ -240,6 +242,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
const: v(1, 1),
templateLiteral: v(1, 1),
optionalChaining: v(8),
methodShorthand: v(1, 1),
arrowFunction: v(1, 1),
asyncFunction: v(1, 7),
forOf: v(0, 36),
@@ -278,6 +281,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
const: v(0, 15),
templateLiteral: v(0, 13),
optionalChaining: v(0, 44),
methodShorthand: v(0, 15),
arrowFunction: v(0, 15),
asyncFunction: v(0, 21),
forOf: v(0, 13),
@@ -300,6 +304,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
const: v >= 2015,
templateLiteral: v >= 2015,
optionalChaining: v >= 2020,
methodShorthand: v >= 2015,
arrowFunction: v >= 2015,
forOf: v >= 2015,
destructuring: v >= 2015,

View File

@@ -8,7 +8,10 @@
const { OriginalSource, RawSource } = require("webpack-sources");
const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
const Module = require("../Module");
const { JS_TYPES } = require("../ModuleSourceTypesConstants");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("../ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
@@ -57,7 +60,7 @@ class ContainerEntryModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -242,7 +245,7 @@ class ContainerEntryModule extends Module {
]);
sources.set(
"javascript",
JAVASCRIPT_TYPE,
this.useSourceMap || this.useSimpleSourceMap
? new OriginalSource(source, "webpack/container-entry")
: new RawSource(source)

View File

@@ -7,7 +7,10 @@
const { RawSource } = require("webpack-sources");
const Module = require("../Module");
const { JS_TYPES } = require("../ModuleSourceTypesConstants");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("../ModuleSourceTypeConstants");
const { WEBPACK_MODULE_TYPE_FALLBACK } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
@@ -122,7 +125,7 @@ class FallbackModule extends Module {
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
/**
@@ -156,7 +159,7 @@ class FallbackModule extends Module {
"module.exports = loop();"
]);
const sources = new Map();
sources.set("javascript", new RawSource(code));
sources.set(JAVASCRIPT_TYPE, new RawSource(code));
return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS };
}

View File

@@ -7,9 +7,7 @@
const { RawSource } = require("webpack-sources");
const Module = require("../Module");
const {
REMOTE_AND_SHARE_INIT_TYPES
} = require("../ModuleSourceTypesConstants");
const { REMOTE_AND_SHARE_INIT_TYPES } = require("../ModuleSourceTypeConstants");
const { WEBPACK_MODULE_TYPE_REMOTE } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const makeSerializable = require("../util/makeSerializable");

View File

@@ -12,10 +12,10 @@ const InitFragment = require("../InitFragment");
const {
CSS_TYPE,
CSS_TYPES,
JS_AND_CSS_TYPES,
JS_TYPE,
JS_TYPES
} = require("../ModuleSourceTypesConstants");
JAVASCRIPT_AND_CSS_TYPES,
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("../ModuleSourceTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const CssImportDependency = require("../dependencies/CssImportDependency");
@@ -23,8 +23,6 @@ const { getUndoPath } = require("../util/identifier");
const memoize = require("../util/memoize");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").CssGlobalGeneratorOptions} CssGlobalGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */
/** @typedef {import("../Compilation").DependencyConstructor} DependencyConstructor */
/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
@@ -36,6 +34,7 @@ const memoize = require("../util/memoize");
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceType} SourceType */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
@@ -51,13 +50,12 @@ const getCssModulesPlugin = memoize(() => require("./CssModulesPlugin"));
class CssGenerator extends Generator {
/**
* @param {CssAutoGeneratorOptions | CssGlobalGeneratorOptions | CssModuleGeneratorOptions} options options
* @param {CssModuleGeneratorOptions} options options
* @param {ModuleGraph} moduleGraph the module graph
*/
constructor(options, moduleGraph) {
super();
this.convention = options.exportsConvention;
this.localIdentName = options.localIdentName;
this.options = options;
this._exportsOnly = options.exportsOnly;
this._esModule = options.esModule;
this._moduleGraph = moduleGraph;
@@ -127,7 +125,7 @@ class CssGenerator extends Generator {
const moduleSourceContent = /** @type {Source} */ (
this.generate(module, {
...generateContext,
type: "css"
type: CSS_TYPE
})
);
@@ -266,7 +264,7 @@ class CssGenerator extends Generator {
generate(module, generateContext) {
const exportType = /** @type {BuildMeta} */ (module.buildMeta).exportType;
const source =
generateContext.type === "javascript"
generateContext.type === JAVASCRIPT_TYPE
? exportType === "link"
? new ReplaceSource(new RawSource(""))
: new ReplaceSource(/** @type {Source} */ (module.originalSource()))
@@ -330,7 +328,7 @@ class CssGenerator extends Generator {
};
switch (generateContext.type) {
case "javascript": {
case JAVASCRIPT_TYPE: {
const isCSSModule = /** @type {BuildMeta} */ (module.buildMeta)
.isCSSModule;
const defaultExport = generateJSDefaultExport();
@@ -374,14 +372,15 @@ class CssGenerator extends Generator {
if (!usedName) {
continue;
}
let identifier = Template.toIdentifier(usedName);
let identifier = Template.toIdentifier(usedName);
if (RESERVED_IDENTIFIER.has(identifier)) {
identifier = `_${identifier}`;
}
const i = 0;
let i = 0;
while (usedIdentifiers.has(identifier)) {
identifier = Template.toIdentifier(name + i);
i += 1;
}
usedIdentifiers.add(identifier);
generateContext.concatenationScope.registerExport(name, identifier);
@@ -428,7 +427,7 @@ class CssGenerator extends Generator {
}.exports = {\n${exports.join(",\n")}\n}${needNsObj ? ")" : ""};`
);
}
case "css": {
case CSS_TYPE: {
if (!this._generatesJsOnly(module)) {
generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules);
}
@@ -448,12 +447,12 @@ class CssGenerator extends Generator {
*/
generateError(error, module, generateContext) {
switch (generateContext.type) {
case "javascript": {
case JAVASCRIPT_TYPE: {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
}
case "css": {
case CSS_TYPE: {
return new RawSource(`/**\n ${error.message} \n**/`);
}
default:
@@ -467,32 +466,35 @@ class CssGenerator extends Generator {
*/
getTypes(module) {
if (this._generatesJsOnly(module)) {
return JS_TYPES;
return JAVASCRIPT_TYPES;
}
const sourceTypes = new Set();
const connections = this._moduleGraph.getIncomingConnections(module);
for (const connection of connections) {
if (connection.dependency instanceof CssImportDependency) {
continue;
}
if (!connection.originModule) {
continue;
}
if (connection.originModule.type.split("/")[0] !== CSS_TYPE) {
sourceTypes.add(JS_TYPE);
sourceTypes.add(JAVASCRIPT_TYPE);
}
}
if (sourceTypes.has(JS_TYPE)) {
return JS_AND_CSS_TYPES;
if (sourceTypes.has(JAVASCRIPT_TYPE)) {
return JAVASCRIPT_AND_CSS_TYPES;
}
return CSS_TYPES;
}
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
switch (type) {
case "javascript": {
case JAVASCRIPT_TYPE: {
const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData;
if (!cssData) {
return 42;
@@ -513,7 +515,7 @@ class CssGenerator extends Generator {
return stringifiedExports.length + 42;
}
case "css": {
case CSS_TYPE: {
const originalSource = module.originalSource();
if (!originalSource) {

View File

@@ -7,6 +7,7 @@
const { SyncWaterfallHook } = require("tapable");
const Compilation = require("../Compilation");
const { CSS_TYPE } = require("../ModuleSourceTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
@@ -86,7 +87,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
* @returns {boolean} true, if the chunk has css
*/
(chunk, chunkGraph) =>
Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, "css"))
Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, CSS_TYPE))
);
const hasCssMatcher = compileBooleanMatcher(conditionMap);
@@ -429,7 +430,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
"while(oldTags.length) {",
Template.indent([
"var oldTag = oldTags.pop();",
"if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"
"if(oldTag && oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"
]),
"}"
])}, apply: ${runtimeTemplate.basicFunction("", [
@@ -451,17 +452,24 @@ class CssLoadingRuntimeModule extends RuntimeModule {
`${
RuntimeGlobals.hmrDownloadUpdateHandlers
}.css = ${runtimeTemplate.basicFunction(
"chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList",
"chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList, css",
[
isNeutralPlatform
? "if (typeof document === 'undefined') return;"
: "",
"applyHandlers.push(applyHandler);",
"// Read CSS removed chunks from update manifest",
"var cssRemovedChunks = css && css.r;",
`chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [
`var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
`var url = ${RuntimeGlobals.publicPath} + filename;`,
"var oldTag = loadStylesheet(chunkId, url);",
"if(!oldTag) return;",
`if(!oldTag && !${withHmr} ) return;`,
"// Skip if CSS was removed",
"if(cssRemovedChunks && cssRemovedChunks.indexOf(chunkId) >= 0) {",
Template.indent(["oldTags.push(oldTag);", "return;"]),
"}",
"",
"// create error before stack unwound to get useful stacktrace later",
"var error = new Error();",
`promises.push(new Promise(${runtimeTemplate.basicFunction(

View File

@@ -17,6 +17,7 @@ const Compilation = require("../Compilation");
const CssModule = require("../CssModule");
const { tryRunOrWebpackError } = require("../HookWebpackError");
const HotUpdateChunk = require("../HotUpdateChunk");
const { CSS_IMPORT_TYPE, CSS_TYPE } = require("../ModuleSourceTypeConstants");
const {
CSS_MODULE_TYPE,
CSS_MODULE_TYPE_AUTO,
@@ -25,15 +26,10 @@ const {
} = require("../ModuleTypeConstants");
const NormalModule = require("../NormalModule");
const RuntimeGlobals = require("../RuntimeGlobals");
const SelfModuleFactory = require("../SelfModuleFactory");
const Template = require("../Template");
const WebpackError = require("../WebpackError");
const CssIcssExportDependency = require("../dependencies/CssIcssExportDependency");
const CssIcssFromIdentifierDependency = require("../dependencies/CssIcssFromIdentifierDependency");
const CssIcssGlobalIdentifierDependency = require("../dependencies/CssIcssGlobalIdentifierDependency");
const CssIcssImportDependency = require("../dependencies/CssIcssImportDependency");
const CssIcssLocalIdentifierDependency = require("../dependencies/CssIcssLocalIdentifierDependency");
const CssIcssSelfLocalIdentifierDependency = require("../dependencies/CssIcssSelfLocalIdentifierDependency");
const CssIcssSymbolDependency = require("../dependencies/CssIcssSymbolDependency");
const CssImportDependency = require("../dependencies/CssImportDependency");
const CssUrlDependency = require("../dependencies/CssUrlDependency");
@@ -130,8 +126,8 @@ const validateGeneratorOptions = {
generatorValidationOptions
),
"css/auto": createSchemaValidation(
require("../../schemas/plugins/css/CssAutoGeneratorOptions.check"),
() => getSchema("CssAutoGeneratorOptions"),
require("../../schemas/plugins/css/CssModuleGeneratorOptions.check"),
() => getSchema("CssModuleGeneratorOptions"),
generatorValidationOptions
),
"css/module": createSchemaValidation(
@@ -140,8 +136,8 @@ const validateGeneratorOptions = {
generatorValidationOptions
),
"css/global": createSchemaValidation(
require("../../schemas/plugins/css/CssGlobalGeneratorOptions.check"),
() => getSchema("CssGlobalGeneratorOptions"),
require("../../schemas/plugins/css/CssModuleGeneratorOptions.check"),
() => getSchema("CssModuleGeneratorOptions"),
generatorValidationOptions
)
};
@@ -157,8 +153,8 @@ const validateParserOptions = {
parserValidationOptions
),
"css/auto": createSchemaValidation(
require("../../schemas/plugins/css/CssAutoParserOptions.check"),
() => getSchema("CssAutoParserOptions"),
require("../../schemas/plugins/css/CssModuleParserOptions.check"),
() => getSchema("CssModuleParserOptions"),
parserValidationOptions
),
"css/module": createSchemaValidation(
@@ -167,8 +163,8 @@ const validateParserOptions = {
parserValidationOptions
),
"css/global": createSchemaValidation(
require("../../schemas/plugins/css/CssGlobalParserOptions.check"),
() => getSchema("CssGlobalParserOptions"),
require("../../schemas/plugins/css/CssModuleParserOptions.check"),
() => getSchema("CssModuleParserOptions"),
parserValidationOptions
)
};
@@ -219,7 +215,6 @@ class CssModulesPlugin {
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
const hooks = CssModulesPlugin.getCompilationHooks(compilation);
const selfFactory = new SelfModuleFactory(compilation.moduleGraph);
compilation.dependencyFactories.set(
CssImportDependency,
normalModuleFactory
@@ -236,18 +231,6 @@ class CssModulesPlugin {
CssUrlDependency,
new CssUrlDependency.Template()
);
compilation.dependencyTemplates.set(
CssIcssLocalIdentifierDependency,
new CssIcssLocalIdentifierDependency.Template()
);
compilation.dependencyFactories.set(
CssIcssSelfLocalIdentifierDependency,
selfFactory
);
compilation.dependencyTemplates.set(
CssIcssSelfLocalIdentifierDependency,
new CssIcssSelfLocalIdentifierDependency.Template()
);
compilation.dependencyFactories.set(
CssIcssImportDependency,
normalModuleFactory
@@ -256,22 +239,6 @@ class CssModulesPlugin {
CssIcssImportDependency,
new CssIcssImportDependency.Template()
);
compilation.dependencyFactories.set(
CssIcssFromIdentifierDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
CssIcssFromIdentifierDependency,
new CssIcssFromIdentifierDependency.Template()
);
compilation.dependencyFactories.set(
CssIcssGlobalIdentifierDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
CssIcssGlobalIdentifierDependency,
new CssIcssGlobalIdentifierDependency.Template()
);
compilation.dependencyTemplates.set(
CssIcssExportDependency,
new CssIcssExportDependency.Template()
@@ -293,45 +260,31 @@ class CssModulesPlugin {
normalModuleFactory.hooks.createParser
.for(type)
.tap(PLUGIN_NAME, (parserOptions) => {
validateParserOptions[type](parserOptions);
const {
url,
import: importOption,
namedExports,
exportType
} = parserOptions;
switch (type) {
case CSS_MODULE_TYPE:
return new CssParser({
importOption,
url,
namedExports,
exportType
});
validateParserOptions[type](parserOptions);
return new CssParser(parserOptions);
case CSS_MODULE_TYPE_GLOBAL:
validateParserOptions[type](parserOptions);
return new CssParser({
defaultMode: "global",
importOption,
url,
namedExports,
exportType
...parserOptions
});
case CSS_MODULE_TYPE_MODULE:
validateParserOptions[type](parserOptions);
return new CssParser({
defaultMode: "local",
importOption,
url,
namedExports,
exportType
...parserOptions
});
case CSS_MODULE_TYPE_AUTO:
validateParserOptions[type](parserOptions);
return new CssParser({
defaultMode: "auto",
importOption,
url,
namedExports,
exportType
...parserOptions
});
}
});
@@ -778,7 +731,7 @@ class CssModulesPlugin {
(
chunkGraph.getOrderedChunkModulesIterableBySourceType(
chunk,
"css-import",
CSS_IMPORT_TYPE,
compareModulesByIdOrIdentifier(chunkGraph)
)
),
@@ -790,7 +743,7 @@ class CssModulesPlugin {
(
chunkGraph.getOrderedChunkModulesIterableBySourceType(
chunk,
"css",
CSS_TYPE,
compareModulesByIdOrIdentifier(chunkGraph)
)
),
@@ -920,8 +873,8 @@ class CssModulesPlugin {
const moduleSourceContent =
/** @type {Source} */
(
codeGenResult.sources.get("css") ||
codeGenResult.sources.get("css-import")
codeGenResult.sources.get(CSS_TYPE) ||
codeGenResult.sources.get(CSS_IMPORT_TYPE)
);
const moduleSource = CssModulesPlugin.renderModule(
module,
@@ -970,9 +923,11 @@ class CssModulesPlugin {
*/
static chunkHasCss(chunk, chunkGraph) {
return (
Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, "css")) ||
Boolean(
chunkGraph.getChunkModulesIterableBySourceType(chunk, "css-import")
chunkGraph.getChunkModulesIterableBySourceType(chunk, CSS_TYPE)
) ||
Boolean(
chunkGraph.getChunkModulesIterableBySourceType(chunk, CSS_IMPORT_TYPE)
)
);
}

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