Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

394
node_modules/webpack/lib/APIPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,394 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
getExternalModuleNodeCommonjsInitFragment
} = require("./ExternalModule");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const ConstDependency = require("./dependencies/ConstDependency");
const ModuleInitFragmentDependency = require("./dependencies/ModuleInitFragmentDependency");
const RuntimeRequirementsDependency = require("./dependencies/RuntimeRequirementsDependency");
const WebpackError = require("./errors/WebpackError");
const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const {
evaluateToString,
toConstantDependency
} = require("./javascript/JavascriptParserHelpers");
const ChunkNameRuntimeModule = require("./runtime/ChunkNameRuntimeModule");
const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/**
* Returns the replacement definitions used for webpack API identifiers.
* @returns {Record<string, { expr: string, req: string[] | null, type?: string, assign: boolean }>} replacements
*/
function getReplacements() {
return {
__webpack_require__: {
expr: RuntimeGlobals.require,
req: [RuntimeGlobals.require],
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],
type: "string",
assign: true
},
__webpack_base_uri__: {
expr: RuntimeGlobals.baseURI,
req: [RuntimeGlobals.baseURI],
type: "string",
assign: true
},
__webpack_modules__: {
expr: RuntimeGlobals.moduleFactories,
req: [RuntimeGlobals.moduleFactories],
type: "object",
assign: false
},
__webpack_chunk_load__: {
expr: RuntimeGlobals.ensureChunk,
req: [RuntimeGlobals.ensureChunk],
type: "function",
assign: true
},
__non_webpack_require__: {
expr: "require",
req: null,
type: undefined, // type is not known, depends on environment
assign: true
},
__webpack_nonce__: {
expr: RuntimeGlobals.scriptNonce,
req: [RuntimeGlobals.scriptNonce],
type: "string",
assign: true
},
__webpack_hash__: {
expr: `${RuntimeGlobals.getFullHash}()`,
req: [RuntimeGlobals.getFullHash],
type: "string",
assign: false
},
__webpack_chunkname__: {
expr: RuntimeGlobals.chunkName,
req: [RuntimeGlobals.chunkName],
type: "string",
assign: false
},
__webpack_get_script_filename__: {
expr: RuntimeGlobals.getChunkScriptFilename,
req: [RuntimeGlobals.getChunkScriptFilename],
type: "function",
assign: true
},
__webpack_runtime_id__: {
expr: RuntimeGlobals.runtimeId,
req: [RuntimeGlobals.runtimeId],
assign: false
},
"require.onError": {
expr: RuntimeGlobals.uncaughtErrorHandler,
req: [RuntimeGlobals.uncaughtErrorHandler],
type: undefined, // type is not known, could be function or undefined
assign: true // is never a pattern
},
__system_context__: {
expr: RuntimeGlobals.systemContext,
req: [RuntimeGlobals.systemContext],
type: "object",
assign: false
},
__webpack_share_scopes__: {
expr: RuntimeGlobals.shareScopeMap,
req: [RuntimeGlobals.shareScopeMap],
type: "object",
assign: false
},
__webpack_init_sharing__: {
expr: RuntimeGlobals.initializeSharing,
req: [RuntimeGlobals.initializeSharing],
type: "function",
assign: true
}
};
}
const PLUGIN_NAME = "APIPlugin";
class APIPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
const moduleOutput = compilation.options.output.module;
const nodeTarget = compiler.platform.node;
const nodeEsm = moduleOutput && nodeTarget;
const REPLACEMENTS = getReplacements();
if (nodeEsm) {
REPLACEMENTS.__non_webpack_require__.expr =
"__WEBPACK_EXTERNAL_createRequire_require";
}
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.dependencyTemplates.set(
ModuleInitFragmentDependency,
new ModuleInitFragmentDependency.Template()
);
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.chunkName)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new ChunkNameRuntimeModule(/** @type {string} */ (chunk.name))
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getFullHash)
.tap(PLUGIN_NAME, (chunk, _set) => {
compilation.addRuntimeModule(chunk, new GetFullHashRuntimeModule());
return true;
});
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModuleContent.tap(
PLUGIN_NAME,
(source, module, renderContext) => {
if (/** @type {BuildInfo} */ (module.buildInfo).needCreateRequire) {
const chunkInitFragments = [
getExternalModuleNodeCommonjsInitFragment(
renderContext.runtimeTemplate
)
];
renderContext.chunkInitFragments.push(...chunkInitFragments);
}
return source;
}
);
/**
* Handles the hook callback for this code path.
* @param {JavascriptParser} parser the parser
*/
const handler = (parser) => {
parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator) => {
if (
parser.scope.topLevelScope === true &&
declarator.id.type === "Identifier" &&
declarator.id.name === "module"
) {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleArgument =
"__webpack_module__";
}
});
parser.hooks.preStatement.tap(PLUGIN_NAME, (statement) => {
if (parser.scope.topLevelScope === true) {
if (
statement.type === "FunctionDeclaration" &&
statement.id &&
statement.id.name === "module"
) {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleArgument =
"__webpack_module__";
} else if (
statement.type === "ClassDeclaration" &&
statement.id &&
statement.id.name === "module"
) {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleArgument =
"__webpack_module__";
}
}
});
for (const key of Object.keys(REPLACEMENTS)) {
const info = REPLACEMENTS[key];
parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expression) => {
const dep = toConstantDependency(parser, info.expr, info.req);
if (key === "__non_webpack_require__" && moduleOutput) {
if (nodeTarget) {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).needCreateRequire = true;
} else {
const warning = new WebpackError(
`${PLUGIN_NAME}\n__non_webpack_require__ is only allowed in target node`
);
warning.loc = /** @type {DependencyLocation} */ (
expression.loc
);
warning.module = parser.state.module;
compilation.warnings.push(warning);
}
}
return dep(expression);
});
if (info.assign === false) {
parser.hooks.assign.for(key).tap(PLUGIN_NAME, (expr) => {
const err = new WebpackError(`${key} must not be assigned`);
err.loc = /** @type {DependencyLocation} */ (expr.loc);
throw err;
});
}
if (info.type) {
parser.hooks.evaluateTypeof
.for(key)
.tap(PLUGIN_NAME, evaluateToString(info.type));
}
}
parser.hooks.expression
.for("__webpack_layer__")
.tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
JSON.stringify(parser.state.module.layer),
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
parser.hooks.evaluateIdentifier
.for("__webpack_layer__")
.tap(PLUGIN_NAME, (expr) =>
(parser.state.module.layer === null
? new BasicEvaluatedExpression().setNull()
: new BasicEvaluatedExpression().setString(
parser.state.module.layer
)
).setRange(/** @type {Range} */ (expr.range))
);
parser.hooks.evaluateTypeof
.for("__webpack_layer__")
.tap(PLUGIN_NAME, (expr) =>
new BasicEvaluatedExpression()
.setString(
parser.state.module.layer === null ? "object" : "string"
)
.setRange(/** @type {Range} */ (expr.range))
);
parser.hooks.expression
.for("__webpack_module__.id")
.tap(PLUGIN_NAME, (expr) => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
"__webpack_module__.id";
const moduleArgument = parser.state.module.moduleArgument;
if (moduleArgument === "__webpack_module__") {
const dep = new RuntimeRequirementsDependency([
RuntimeGlobals.moduleId
]);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
const initDep = new ModuleInitFragmentDependency(
`var __webpack_internal_module_id__ = ${moduleArgument}.id;\n`,
[RuntimeGlobals.moduleId],
"__webpack_internal_module_id__"
);
parser.state.module.addPresentationalDependency(initDep);
const dep = new ConstDependency(
"__webpack_internal_module_id__",
/** @type {Range} */ (expr.range),
[]
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
}
return true;
});
parser.hooks.expression
.for("__webpack_module__")
.tap(PLUGIN_NAME, (expr) => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
"__webpack_module__";
const moduleArgument = parser.state.module.moduleArgument;
if (moduleArgument === "__webpack_module__") {
const dep = new RuntimeRequirementsDependency([
RuntimeGlobals.module
]);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
const initDep = new ModuleInitFragmentDependency(
`var __webpack_internal_module__ = ${moduleArgument};\n`,
[RuntimeGlobals.module],
"__webpack_internal_module__"
);
parser.state.module.addPresentationalDependency(initDep);
const dep = new ConstDependency(
"__webpack_internal_module__",
/** @type {Range} */ (expr.range),
[]
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
}
return true;
});
parser.hooks.evaluateTypeof
.for("__webpack_module__")
.tap(PLUGIN_NAME, evaluateToString("object"));
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = APIPlugin;

131
node_modules/webpack/lib/AsyncDependenciesBlock.js generated vendored Normal file
View File

@@ -0,0 +1,131 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DependenciesBlock = require("./DependenciesBlock");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {(ChunkGroupOptions & { entryOptions?: EntryOptions } & { circular?: boolean })} GroupOptions */
class AsyncDependenciesBlock extends DependenciesBlock {
/**
* @param {GroupOptions | string | null} groupOptions options for the group
* @param {(DependencyLocation | null)=} loc the line of code
* @param {(string | null)=} request the request
*/
constructor(groupOptions, loc, request) {
super();
if (typeof groupOptions === "string") {
groupOptions = { name: groupOptions };
} else if (!groupOptions) {
groupOptions = { name: undefined };
}
if (typeof groupOptions.circular !== "boolean") {
// default allow circular references
groupOptions.circular = true;
}
/** @type {GroupOptions} */
this.groupOptions = groupOptions;
/** @type {DependencyLocation | null | undefined} */
this.loc = loc;
/** @type {string | null | undefined} */
this.request = request;
/** @type {undefined | string} */
this._stringifiedGroupOptions = undefined;
}
/**
* @returns {ChunkGroupOptions["name"]} The name of the chunk
*/
get chunkName() {
return this.groupOptions.name;
}
/**
* @param {string | undefined} value The new chunk name
* @returns {void}
*/
set chunkName(value) {
if (this.groupOptions.name !== value) {
this.groupOptions.name = value;
this._stringifiedGroupOptions = undefined;
}
}
/**
* @returns {boolean} Whether circular references are allowed
*/
get circular() {
return Boolean(this.groupOptions.circular);
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
const { chunkGraph } = context;
if (this._stringifiedGroupOptions === undefined) {
this._stringifiedGroupOptions = JSON.stringify(this.groupOptions);
}
const chunkGroup = chunkGraph.getBlockChunkGroup(this);
hash.update(
`${this._stringifiedGroupOptions}${chunkGroup ? chunkGroup.id : ""}`
);
super.updateHash(hash, context);
}
/**
* Serializes this instance into the provided serializer context.
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.groupOptions);
write(this.loc);
write(this.request);
super.serialize(context);
}
/**
* Restores this instance from the provided deserializer context.
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.groupOptions = read();
this.loc = read();
this.request = read();
super.deserialize(context);
}
}
makeSerializable(AsyncDependenciesBlock, "webpack/lib/AsyncDependenciesBlock");
Object.defineProperty(AsyncDependenciesBlock.prototype, "module", {
get() {
throw new Error(
"module property was removed from AsyncDependenciesBlock (it's not needed)"
);
},
set() {
throw new Error(
"module property was removed from AsyncDependenciesBlock (it's not needed)"
);
}
});
module.exports = AsyncDependenciesBlock;

71
node_modules/webpack/lib/AutomaticPrefetchPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,71 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const NormalModule = require("./NormalModule");
const PrefetchDependency = require("./dependencies/PrefetchDependency");
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "AutomaticPrefetchPlugin";
/**
* Records modules from one compilation and adds them back as prefetch
* dependencies in the next compilation.
*/
class AutomaticPrefetchPlugin {
/**
* Registers hooks that remember previously built normal modules and enqueue
* them as `PrefetchDependency` requests during the next make phase.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
PrefetchDependency,
normalModuleFactory
);
}
);
/** @type {{ context: string | null, request: string }[] | null} */
let lastModules = null;
compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {
lastModules = [];
for (const m of compilation.modules) {
if (m instanceof NormalModule) {
lastModules.push({
context: m.context,
request: m.request
});
}
}
});
compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
if (!lastModules) return callback();
asyncLib.each(
lastModules,
(m, callback) => {
compilation.addModuleChain(
m.context || compiler.context,
new PrefetchDependency(`!!${m.request}`),
callback
);
},
(err) => {
lastModules = null;
callback(err);
}
);
});
}
}
module.exports = AutomaticPrefetchPlugin;

146
node_modules/webpack/lib/BannerPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,146 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource } = require("webpack-sources");
const Compilation = require("./Compilation");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const Template = require("./Template");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
/** @typedef {import("./Compilation").PathDataChunk} PathDataChunk */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {(data: { hash?: string, chunk: Chunk, filename: string }) => string} BannerFunction */
/**
* Wraps banner text in a JavaScript block comment, preserving multi-line
* formatting and escaping accidental comment terminators.
* @param {string} str string to wrap
* @returns {string} wrapped string
*/
const wrapComment = (str) => {
if (!str.includes("\n")) {
return Template.toComment(str);
}
return `/*!\n * ${str
.replace(/\*\//g, "* /")
.split("\n")
.join("\n * ")
.replace(/\s+\n/g, "\n")
.trimEnd()}\n */`;
};
const PLUGIN_NAME = "BannerPlugin";
/**
* Prepends or appends banner text to emitted assets that match the configured
* file filters.
*/
class BannerPlugin {
/**
* Normalizes banner options and compiles the configured banner source into a
* function that can render per-asset banner text.
* @param {BannerPluginArgument} options options object
*/
constructor(options) {
if (typeof options === "string" || typeof options === "function") {
options = {
banner: options
};
}
/** @type {BannerPluginOptions} */
this.options = options;
const bannerOption = options.banner;
if (typeof bannerOption === "function") {
const getBanner = bannerOption;
/** @type {BannerFunction} */
this.banner = this.options.raw
? getBanner
: /** @type {BannerFunction} */ (data) => wrapComment(getBanner(data));
} else {
const banner = this.options.raw
? bannerOption
: wrapComment(bannerOption);
/** @type {BannerFunction} */
this.banner = () => banner;
}
}
/**
* Validates the configured options and injects rendered banner comments into
* matching compilation assets at the configured process-assets stage.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
() => require("../schemas/plugins/BannerPlugin.json"),
this.options,
{
name: "Banner Plugin",
baseDataPath: "options"
},
(options) => require("../schemas/plugins/BannerPlugin.check")(options)
);
});
const options = this.options;
const banner = this.banner;
const matchObject = ModuleFilenameHelpers.matchObject.bind(
undefined,
options
);
/** @type {WeakMap<Source, { source: ConcatSource, comment: string }>} */
const cache = new WeakMap();
const stage =
this.options.stage || Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, () => {
for (const chunk of compilation.chunks) {
if (options.entryOnly && !chunk.canBeInitial()) {
continue;
}
for (const file of chunk.files) {
if (!matchObject(file)) {
continue;
}
/** @type {PathDataChunk} */
const data = { chunk, filename: file };
const comment = compilation.getPath(
/** @type {string | import("./TemplatedPathPlugin").TemplatePathFn<PathDataChunk>} */
(banner),
data
);
compilation.updateAsset(file, (old) => {
const cached = cache.get(old);
if (!cached || cached.comment !== comment) {
const source = options.footer
? new ConcatSource(old, "\n", comment)
: new ConcatSource(comment, "\n", old);
cache.set(old, { source, comment });
return source;
}
return cached.source;
});
}
}
});
});
}
}
module.exports = BannerPlugin;

190
node_modules/webpack/lib/Cache.js generated vendored Normal file
View File

@@ -0,0 +1,190 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = require("tapable");
const {
makeWebpackError,
makeWebpackErrorCallback
} = require("./errors/HookWebpackError");
/**
* Cache validation token whose string representation identifies the build
* inputs associated with a cached value.
* @typedef {object} Etag
* @property {() => string} toString
*/
/**
* Completion callback used by cache operations that either fail with a `Error` or resolve with a typed result.
* @template T
* @callback CallbackCache
* @param {Error | null} err
* @param {T=} result
* @returns {void}
*/
/** @typedef {EXPECTED_ANY} Data */
/**
* Handler invoked after a cache read succeeds so additional cache layers can
* react to the retrieved value.
* @template T
* @callback GotHandler
* @param {T} result
* @param {() => void} callback
* @returns {void}
*/
/**
* Creates a callback wrapper that waits for a fixed number of completions and
* forwards the first error immediately.
* @param {number} times times
* @param {(err?: Error | null) => void} callback callback
* @returns {(err?: Error | null) => void} callback
*/
const needCalls = (times, callback) => (err) => {
if (--times === 0) {
return callback(err);
}
if (err && times > 0) {
times = 0;
return callback(err);
}
};
/**
* Abstract cache interface backed by tapable hooks for reading, writing, idle
* transitions, and shutdown across webpack cache implementations.
*/
class Cache {
/**
* Initializes the cache lifecycle hooks implemented by cache backends.
*/
constructor() {
this.hooks = {
/** @type {AsyncSeriesBailHook<[string, Etag | null, GotHandler<EXPECTED_ANY>[]], Data>} */
get: new AsyncSeriesBailHook(["identifier", "etag", "gotHandlers"]),
/** @type {AsyncParallelHook<[string, Etag | null, Data]>} */
store: new AsyncParallelHook(["identifier", "etag", "data"]),
/** @type {AsyncParallelHook<[Iterable<string>]>} */
storeBuildDependencies: new AsyncParallelHook(["dependencies"]),
/** @type {SyncHook<[]>} */
beginIdle: new SyncHook([]),
/** @type {AsyncParallelHook<[]>} */
endIdle: new AsyncParallelHook([]),
/** @type {AsyncParallelHook<[]>} */
shutdown: new AsyncParallelHook([])
};
}
/**
* Retrieves a cached value and lets registered `gotHandlers` observe the
* result before the caller receives it.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(identifier, etag, callback) {
/** @type {GotHandler<T>[]} */
const gotHandlers = [];
this.hooks.get.callAsync(identifier, etag, gotHandlers, (err, result) => {
if (err) {
callback(makeWebpackError(err, "Cache.hooks.get"));
return;
}
if (result === null) {
result = undefined;
}
if (gotHandlers.length > 1) {
const innerCallback = needCalls(gotHandlers.length, () =>
callback(null, result)
);
for (const gotHandler of gotHandlers) {
gotHandler(result, innerCallback);
}
} else if (gotHandlers.length === 1) {
gotHandlers[0](result, () => callback(null, result));
} else {
callback(null, result);
}
});
}
/**
* Stores a cache entry for the identifier and etag through the registered
* cache backend hooks.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(identifier, etag, data, callback) {
this.hooks.store.callAsync(
identifier,
etag,
data,
makeWebpackErrorCallback(callback, "Cache.hooks.store")
);
}
/**
* Persists the set of build dependencies required to determine whether the
* cache can be restored in a future compilation.
* @param {Iterable<string>} dependencies list of all build dependencies
* @param {CallbackCache<void>} callback signals when the dependencies are stored
* @returns {void}
*/
storeBuildDependencies(dependencies, callback) {
this.hooks.storeBuildDependencies.callAsync(
dependencies,
makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies")
);
}
/**
* Signals that webpack is entering an idle phase and cache backends may flush
* or compact pending work.
* @returns {void}
*/
beginIdle() {
this.hooks.beginIdle.call();
}
/**
* Signals that webpack is leaving the idle phase and waits for cache
* backends to finish any asynchronous resume work.
* @param {CallbackCache<void>} callback signals when the call finishes
* @returns {void}
*/
endIdle(callback) {
this.hooks.endIdle.callAsync(
makeWebpackErrorCallback(callback, "Cache.hooks.endIdle")
);
}
/**
* Shuts down every registered cache backend and waits for cleanup to finish.
* @param {CallbackCache<void>} callback signals when the call finishes
* @returns {void}
*/
shutdown(callback) {
this.hooks.shutdown.callAsync(
makeWebpackErrorCallback(callback, "Cache.hooks.shutdown")
);
}
}
Cache.STAGE_MEMORY = -10;
Cache.STAGE_DEFAULT = 0;
Cache.STAGE_DISK = 10;
Cache.STAGE_NETWORK = 20;
module.exports = Cache;

375
node_modules/webpack/lib/CacheFacade.js generated vendored Normal file
View File

@@ -0,0 +1,375 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { forEachBail } = require("enhanced-resolve");
const asyncLib = require("neo-async");
const getLazyHashedEtag = require("./cache/getLazyHashedEtag");
const mergeEtags = require("./cache/mergeEtags");
/** @typedef {import("./Cache")} Cache */
/** @typedef {import("./Cache").Etag} Etag */
/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */
/** @typedef {import("./util/Hash").HashFunction} HashFunction */
/**
* Defines the callback cache callback.
* @template T
* @callback CallbackCache
* @param {(Error | null)=} err
* @param {(T | null)=} result
* @returns {void}
*/
/**
* Defines the callback normal error cache callback.
* @template T
* @callback CallbackNormalErrorCache
* @param {(Error | null)=} err
* @param {T=} result
* @returns {void}
*/
class MultiItemCache {
/**
* Creates an instance of MultiItemCache.
* @param {ItemCacheFacade[]} items item caches
*/
constructor(items) {
this._items = items;
// @ts-expect-error expected - returns the single ItemCacheFacade when passed an array of length 1
// eslint-disable-next-line no-constructor-return
if (items.length === 1) return /** @type {ItemCacheFacade} */ (items[0]);
}
/**
* Returns value.
* @template T
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(callback) {
forEachBail(this._items, (item, callback) => item.get(callback), callback);
}
/**
* Returns promise with the data.
* @template T
* @returns {Promise<T>} promise with the data
*/
getPromise() {
/**
* Returns promise with the data.
* @param {number} i index
* @returns {Promise<T>} promise with the data
*/
const next = (i) =>
this._items[i].getPromise().then((result) => {
if (result !== undefined) return result;
if (++i < this._items.length) return next(i);
});
return next(0);
}
/**
* Processes the provided data.
* @template T
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(data, callback) {
asyncLib.each(
this._items,
(item, callback) => item.store(data, callback),
callback
);
}
/**
* Stores the provided data.
* @template T
* @param {T} data the value to store
* @returns {Promise<void>} promise signals when the value is stored
*/
storePromise(data) {
return Promise.all(this._items.map((item) => item.storePromise(data))).then(
() => {}
);
}
}
class ItemCacheFacade {
/**
* Creates an instance of ItemCacheFacade.
* @param {Cache} cache the root cache
* @param {string} name the child cache item name
* @param {Etag | null} etag the etag
*/
constructor(cache, name, etag) {
this._cache = cache;
this._name = name;
this._etag = etag;
}
/**
* Returns value.
* @template T
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(callback) {
this._cache.get(this._name, this._etag, callback);
}
/**
* Returns promise with the data.
* @template T
* @returns {Promise<T>} promise with the data
*/
getPromise() {
return new Promise((resolve, reject) => {
this._cache.get(this._name, this._etag, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
/**
* Processes the provided data.
* @template T
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(data, callback) {
this._cache.store(this._name, this._etag, data, callback);
}
/**
* Stores the provided data.
* @template T
* @param {T} data the value to store
* @returns {Promise<void>} promise signals when the value is stored
*/
storePromise(data) {
return new Promise((resolve, reject) => {
this._cache.store(this._name, this._etag, data, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* Processes the provided computer.
* @template T
* @param {(callback: CallbackNormalErrorCache<T>) => void} computer function to compute the value if not cached
* @param {CallbackNormalErrorCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
provide(computer, callback) {
this.get((err, cacheEntry) => {
if (err) return callback(err);
if (cacheEntry !== undefined) return cacheEntry;
computer((err, result) => {
if (err) return callback(err);
this.store(result, (err) => {
if (err) return callback(err);
callback(null, result);
});
});
});
}
/**
* Returns promise with the data.
* @template T
* @param {() => Promise<T> | T} computer function to compute the value if not cached
* @returns {Promise<T>} promise with the data
*/
async providePromise(computer) {
const cacheEntry = await this.getPromise();
if (cacheEntry !== undefined) return cacheEntry;
const result = await computer();
await this.storePromise(result);
return result;
}
}
class CacheFacade {
/**
* Creates an instance of CacheFacade.
* @param {Cache} cache the root cache
* @param {string} name the child cache name
* @param {HashFunction=} hashFunction the hash function to use
*/
constructor(cache, name, hashFunction) {
this._cache = cache;
this._name = name;
this._hashFunction = hashFunction;
}
/**
* Returns child cache.
* @param {string} name the child cache name#
* @returns {CacheFacade} child cache
*/
getChildCache(name) {
return new CacheFacade(
this._cache,
`${this._name}|${name}`,
this._hashFunction
);
}
/**
* Returns item cache.
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @returns {ItemCacheFacade} item cache
*/
getItemCache(identifier, etag) {
return new ItemCacheFacade(
this._cache,
`${this._name}|${identifier}`,
etag
);
}
/**
* Gets lazy hashed etag.
* @param {HashableObject} obj an hashable object
* @returns {Etag} an etag that is lazy hashed
*/
getLazyHashedEtag(obj) {
return getLazyHashedEtag(obj, this._hashFunction);
}
/**
* Merges the provided values into a single result.
* @param {Etag} a an etag
* @param {Etag} b another etag
* @returns {Etag} an etag that represents both
*/
mergeEtags(a, b) {
return mergeEtags(a, b);
}
/**
* Returns value.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(identifier, etag, callback) {
this._cache.get(`${this._name}|${identifier}`, etag, callback);
}
/**
* Returns promise with the data.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @returns {Promise<T>} promise with the data
*/
getPromise(identifier, etag) {
return new Promise((resolve, reject) => {
this._cache.get(`${this._name}|${identifier}`, etag, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
/**
* Processes the provided identifier.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(identifier, etag, data, callback) {
this._cache.store(`${this._name}|${identifier}`, etag, data, callback);
}
/**
* Stores the provided identifier.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {T} data the value to store
* @returns {Promise<void>} promise signals when the value is stored
*/
storePromise(identifier, etag, data) {
return new Promise((resolve, reject) => {
this._cache.store(`${this._name}|${identifier}`, etag, data, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* Processes the provided identifier.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {(callback: CallbackNormalErrorCache<T>) => void} computer function to compute the value if not cached
* @param {CallbackNormalErrorCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
provide(identifier, etag, computer, callback) {
this.get(identifier, etag, (err, cacheEntry) => {
if (err) return callback(err);
if (cacheEntry !== undefined) return cacheEntry;
computer((err, result) => {
if (err) return callback(err);
this.store(identifier, etag, result, (err) => {
if (err) return callback(err);
callback(null, result);
});
});
});
}
/**
* Returns promise with the data.
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {() => Promise<T> | T} computer function to compute the value if not cached
* @returns {Promise<T>} promise with the data
*/
async providePromise(identifier, etag, computer) {
const cacheEntry = await this.getPromise(identifier, etag);
if (cacheEntry !== undefined) return cacheEntry;
const result = await computer();
await this.storePromise(identifier, etag, result);
return result;
}
}
module.exports = CacheFacade;
module.exports.ItemCacheFacade = ItemCacheFacade;
module.exports.MultiItemCache = MultiItemCache;

966
node_modules/webpack/lib/Chunk.js generated vendored Normal file
View File

@@ -0,0 +1,966 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ChunkGraph = require("./ChunkGraph");
const Entrypoint = require("./Entrypoint");
const { intersect } = require("./util/SetHelpers");
const SortableSet = require("./util/SortableSet");
const StringXor = require("./util/StringXor");
const {
compareChunkGroupsByIndex,
compareModulesById,
compareModulesByIdentifier
} = require("./util/comparators");
const { createArrayToSetDeprecationSet } = require("./util/deprecation");
const { mergeRuntime } = require("./util/runtime");
/** @typedef {import("./ChunkGraph").ChunkFilterPredicate} ChunkFilterPredicate */
/** @typedef {import("./ChunkGraph").ChunkSizeOptions} ChunkSizeOptions */
/** @typedef {import("./ChunkGraph").ModuleFilterPredicate} ModuleFilterPredicate */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Compilation").PathDataChunk} PathDataChunk */
/** @typedef {import("./TemplatedPathPlugin").TemplatePathFn<PathDataChunk>} ChunkFilenameTemplateFn */
/** @typedef {string | ChunkFilenameTemplateFn} ChunkFilenameTemplate */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {string | null} ChunkName */
/** @typedef {string | number} ChunkId */
/** @typedef {SortableSet<string>} IdNameHints */
const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files");
/**
* Defines the chunk maps type used by this module.
* @deprecated
* @typedef {object} ChunkMaps
* @property {Record<ChunkId, string>} hash
* @property {Record<ChunkId, Record<string, string>>} contentHash
* @property {Record<ChunkId, string>} name
*/
/**
* Defines the chunk module id map type used by this module.
* @deprecated
* @typedef {Record<ChunkId, ChunkId[]>} ChunkModuleIdMap
*/
/**
* Defines the chunk module hash map type used by this module.
* @deprecated
* @typedef {Record<ModuleId, string>} chunkModuleHashMap
*/
/**
* Defines the chunk module maps type used by this module.
* @deprecated
* @typedef {object} ChunkModuleMaps
* @property {ChunkModuleIdMap} id
* @property {chunkModuleHashMap} hash
*/
/** @typedef {Set<Chunk>} Chunks */
/** @typedef {Set<Entrypoint>} Entrypoints */
/** @typedef {Set<ChunkGroup>} Queue */
/** @typedef {SortableSet<ChunkGroup>} SortableChunkGroups */
/** @typedef {Record<string, ChunkId[]>} ChunkChildIdsByOrdersMap */
/** @typedef {Record<string, ChunkChildIdsByOrdersMap>} ChunkChildIdsByOrdersMapByData */
/** @typedef {{ onChunks: Chunk[], chunks: Chunks }} ChunkChildOfTypeInOrder */
let debugId = 1000;
/**
* A Chunk is a unit of encapsulation for Modules.
* Chunks are "rendered" into bundles that get emitted when the build completes.
*/
class Chunk {
/**
* Creates an instance of Chunk.
* @param {ChunkName=} name of chunk being created, is optional (for subclasses)
* @param {boolean} backCompat enable backward-compatibility
*/
constructor(name, backCompat = true) {
/** @type {ChunkId | null} */
this.id = null;
/** @type {ChunkId[] | null} */
this.ids = null;
/** @type {number} */
this.debugId = debugId++;
/** @type {ChunkName | undefined} */
this.name = name;
/** @type {IdNameHints} */
this.idNameHints = new SortableSet();
/** @type {boolean} */
this.preventIntegration = false;
/** @type {ChunkFilenameTemplate | undefined} */
this.filenameTemplate = undefined;
/** @type {ChunkFilenameTemplate | undefined} */
this.cssFilenameTemplate = undefined;
/**
* @private
* @type {SortableChunkGroups}
*/
this._groups = new SortableSet(undefined, compareChunkGroupsByIndex);
/** @type {RuntimeSpec} */
this.runtime = undefined;
/** @type {Set<string>} */
this.files = backCompat ? new ChunkFilesSet() : new Set();
/** @type {Set<string>} */
this.auxiliaryFiles = new Set();
/** @type {boolean} */
this.rendered = false;
/** @type {string=} */
this.hash = undefined;
/** @type {Record<string, string>} */
this.contentHash = Object.create(null);
/** @type {string=} */
this.renderedHash = undefined;
/** @type {string=} */
this.chunkReason = undefined;
/** @type {boolean} */
this.extraAsync = false;
}
// TODO remove in webpack 6
// BACKWARD-COMPAT START
/**
* Returns entry module.
* @deprecated
* @returns {Module | undefined} entry module
*/
get entryModule() {
const entryModules = [
...ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.entryModule",
"DEP_WEBPACK_CHUNK_ENTRY_MODULE"
).getChunkEntryModulesIterable(this)
];
if (entryModules.length === 0) {
return undefined;
} else if (entryModules.length === 1) {
return entryModules[0];
}
throw new Error(
"Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API)"
);
}
/**
* Checks whether this chunk has an entry module.
* @deprecated
* @returns {boolean} true, if the chunk contains an entry module
*/
hasEntryModule() {
return (
ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.hasEntryModule",
"DEP_WEBPACK_CHUNK_HAS_ENTRY_MODULE"
).getNumberOfEntryModules(this) > 0
);
}
/**
* Adds the provided module to the chunk.
* @deprecated
* @param {Module} module the module
* @returns {boolean} true, if the chunk could be added
*/
addModule(module) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.addModule",
"DEP_WEBPACK_CHUNK_ADD_MODULE"
);
if (chunkGraph.isModuleInChunk(module, this)) return false;
chunkGraph.connectChunkAndModule(this, module);
return true;
}
/**
* Removes the provided module from the chunk.
* @deprecated
* @param {Module} module the module
* @returns {void}
*/
removeModule(module) {
ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.removeModule",
"DEP_WEBPACK_CHUNK_REMOVE_MODULE"
).disconnectChunkAndModule(this, module);
}
/**
* Gets the number of modules in this chunk.
* @deprecated
* @returns {number} the number of module which are contained in this chunk
*/
getNumberOfModules() {
return ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.getNumberOfModules",
"DEP_WEBPACK_CHUNK_GET_NUMBER_OF_MODULES"
).getNumberOfChunkModules(this);
}
/**
* @deprecated
* @returns {Iterable<Module>} modules
*/
get modulesIterable() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.modulesIterable",
"DEP_WEBPACK_CHUNK_MODULES_ITERABLE"
);
return chunkGraph.getOrderedChunkModulesIterable(
this,
compareModulesByIdentifier
);
}
/**
* Compares this chunk with another chunk.
* @deprecated
* @param {Chunk} otherChunk the chunk to compare with
* @returns {-1 | 0 | 1} the comparison result
*/
compareTo(otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.compareTo",
"DEP_WEBPACK_CHUNK_COMPARE_TO"
);
return chunkGraph.compareChunks(this, otherChunk);
}
/**
* Checks whether this chunk contains the module.
* @deprecated
* @param {Module} module the module
* @returns {boolean} true, if the chunk contains the module
*/
containsModule(module) {
return ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.containsModule",
"DEP_WEBPACK_CHUNK_CONTAINS_MODULE"
).isModuleInChunk(module, this);
}
/**
* Returns the modules for this chunk.
* @deprecated
* @returns {Module[]} the modules for this chunk
*/
getModules() {
return ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.getModules",
"DEP_WEBPACK_CHUNK_GET_MODULES"
).getChunkModules(this);
}
/**
* Removes this chunk from the chunk graph and chunk groups.
* @deprecated
* @returns {void}
*/
remove() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.remove",
"DEP_WEBPACK_CHUNK_REMOVE"
);
chunkGraph.disconnectChunk(this);
this.disconnectFromGroups();
}
/**
* Moves a module from this chunk to another chunk.
* @deprecated
* @param {Module} module the module
* @param {Chunk} otherChunk the target chunk
* @returns {void}
*/
moveModule(module, otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.moveModule",
"DEP_WEBPACK_CHUNK_MOVE_MODULE"
);
chunkGraph.disconnectChunkAndModule(this, module);
chunkGraph.connectChunkAndModule(otherChunk, module);
}
/**
* Integrates another chunk into this chunk when possible.
* @deprecated
* @param {Chunk} otherChunk the other chunk
* @returns {boolean} true, if the specified chunk has been integrated
*/
integrate(otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.integrate",
"DEP_WEBPACK_CHUNK_INTEGRATE"
);
if (chunkGraph.canChunksBeIntegrated(this, otherChunk)) {
chunkGraph.integrateChunks(this, otherChunk);
return true;
}
return false;
}
/**
* Checks whether this chunk can be integrated with another chunk.
* @deprecated
* @param {Chunk} otherChunk the other chunk
* @returns {boolean} true, if chunks could be integrated
*/
canBeIntegrated(otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.canBeIntegrated",
"DEP_WEBPACK_CHUNK_CAN_BE_INTEGRATED"
);
return chunkGraph.canChunksBeIntegrated(this, otherChunk);
}
/**
* Checks whether this chunk is empty.
* @deprecated
* @returns {boolean} true, if this chunk contains no module
*/
isEmpty() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.isEmpty",
"DEP_WEBPACK_CHUNK_IS_EMPTY"
);
return chunkGraph.getNumberOfChunkModules(this) === 0;
}
/**
* Returns the total size of all modules in this chunk.
* @deprecated
* @returns {number} total size of all modules in this chunk
*/
modulesSize() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.modulesSize",
"DEP_WEBPACK_CHUNK_MODULES_SIZE"
);
return chunkGraph.getChunkModulesSize(this);
}
/**
* Returns the estimated size for the requested source type.
* @deprecated
* @param {ChunkSizeOptions} options options object
* @returns {number} total size of this chunk
*/
size(options = {}) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.size",
"DEP_WEBPACK_CHUNK_SIZE"
);
return chunkGraph.getChunkSize(this, options);
}
/**
* Returns the integrated size with another chunk.
* @deprecated
* @param {Chunk} otherChunk the other chunk
* @param {ChunkSizeOptions} options options object
* @returns {number} total size of the chunk or false if the chunk can't be integrated
*/
integratedSize(otherChunk, options) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.integratedSize",
"DEP_WEBPACK_CHUNK_INTEGRATED_SIZE"
);
return chunkGraph.getIntegratedChunksSize(this, otherChunk, options);
}
/**
* Gets chunk module maps.
* @deprecated
* @param {ModuleFilterPredicate} filterFn function used to filter modules
* @returns {ChunkModuleMaps} module map information
*/
getChunkModuleMaps(filterFn) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.getChunkModuleMaps",
"DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS"
);
/** @type {ChunkModuleIdMap} */
const chunkModuleIdMap = Object.create(null);
/** @type {chunkModuleHashMap} */
const chunkModuleHashMap = Object.create(null);
for (const asyncChunk of this.getAllAsyncChunks()) {
/** @type {ChunkId[] | undefined} */
let array;
for (const module of chunkGraph.getOrderedChunkModulesIterable(
asyncChunk,
compareModulesById(chunkGraph)
)) {
if (filterFn(module)) {
if (array === undefined) {
array = [];
chunkModuleIdMap[/** @type {ChunkId} */ (asyncChunk.id)] = array;
}
const moduleId =
/** @type {ModuleId} */
(chunkGraph.getModuleId(module));
array.push(moduleId);
chunkModuleHashMap[moduleId] = chunkGraph.getRenderedModuleHash(
module,
undefined
);
}
}
}
return {
id: chunkModuleIdMap,
hash: chunkModuleHashMap
};
}
/**
* Checks whether this chunk contains a matching module in the graph.
* @deprecated
* @param {ModuleFilterPredicate} filterFn predicate function used to filter modules
* @param {ChunkFilterPredicate=} filterChunkFn predicate function used to filter chunks
* @returns {boolean} return true if module exists in graph
*/
hasModuleInGraph(filterFn, filterChunkFn) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.hasModuleInGraph",
"DEP_WEBPACK_CHUNK_HAS_MODULE_IN_GRAPH"
);
return chunkGraph.hasModuleInGraph(this, filterFn, filterChunkFn);
}
/**
* Returns the chunk map information.
* @deprecated
* @param {boolean} realHash whether the full hash or the rendered hash is to be used
* @returns {ChunkMaps} the chunk map information
*/
getChunkMaps(realHash) {
/** @type {Record<ChunkId, string>} */
const chunkHashMap = Object.create(null);
/** @type {Record<string, Record<ChunkId, string>>} */
const chunkContentHashMap = Object.create(null);
/** @type {Record<ChunkId, string>} */
const chunkNameMap = Object.create(null);
for (const chunk of this.getAllAsyncChunks()) {
const id = /** @type {ChunkId} */ (chunk.id);
chunkHashMap[id] =
/** @type {string} */
(realHash ? chunk.hash : chunk.renderedHash);
for (const key of Object.keys(chunk.contentHash)) {
if (!chunkContentHashMap[key]) {
chunkContentHashMap[key] = Object.create(null);
}
chunkContentHashMap[key][id] = chunk.contentHash[key];
}
if (chunk.name) {
chunkNameMap[id] = chunk.name;
}
}
return {
hash: chunkHashMap,
contentHash: chunkContentHashMap,
name: chunkNameMap
};
}
// BACKWARD-COMPAT END
/**
* Checks whether this chunk has runtime.
* @returns {boolean} whether or not the Chunk will have a runtime
*/
hasRuntime() {
for (const chunkGroup of this._groups) {
if (
chunkGroup instanceof Entrypoint &&
chunkGroup.getRuntimeChunk() === this
) {
return true;
}
}
return false;
}
/**
* Checks whether it can be initial.
* @returns {boolean} whether or not this chunk can be an initial chunk
*/
canBeInitial() {
for (const chunkGroup of this._groups) {
if (chunkGroup.isInitial()) return true;
}
return false;
}
/**
* Checks whether this chunk is only initial.
* @returns {boolean} whether this chunk can only be an initial chunk
*/
isOnlyInitial() {
if (this._groups.size <= 0) return false;
for (const chunkGroup of this._groups) {
if (!chunkGroup.isInitial()) return false;
}
return true;
}
/**
* Gets entry options.
* @returns {EntryOptions | undefined} the entry options for this chunk
*/
getEntryOptions() {
for (const chunkGroup of this._groups) {
if (chunkGroup instanceof Entrypoint) {
return chunkGroup.options;
}
}
return undefined;
}
/**
* Adds the provided chunk group to the chunk.
* @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added
* @returns {void}
*/
addGroup(chunkGroup) {
this._groups.add(chunkGroup);
}
/**
* Removes the provided chunk group from the chunk.
* @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from
* @returns {void}
*/
removeGroup(chunkGroup) {
this._groups.delete(chunkGroup);
}
/**
* Checks whether this chunk is in group.
* @param {ChunkGroup} chunkGroup the chunkGroup to check
* @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup
*/
isInGroup(chunkGroup) {
return this._groups.has(chunkGroup);
}
/**
* Gets number of groups.
* @returns {number} the amount of groups that the said chunk is in
*/
getNumberOfGroups() {
return this._groups.size;
}
/**
* Gets groups iterable.
* @returns {SortableChunkGroups} the chunkGroups that the said chunk is referenced in
*/
get groupsIterable() {
this._groups.sort();
return this._groups;
}
/**
* Disconnects from groups.
* @returns {void}
*/
disconnectFromGroups() {
for (const chunkGroup of this._groups) {
chunkGroup.removeChunk(this);
}
}
/**
* Processes the provided new chunk.
* @param {Chunk} newChunk the new chunk that will be split out of
* @returns {void}
*/
split(newChunk) {
for (const chunkGroup of this._groups) {
chunkGroup.insertChunk(newChunk, this);
newChunk.addGroup(chunkGroup);
}
for (const idHint of this.idNameHints) {
newChunk.idNameHints.add(idHint);
}
newChunk.runtime = mergeRuntime(newChunk.runtime, this.runtime);
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash hash (will be modified)
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {void}
*/
updateHash(hash, chunkGraph) {
hash.update(
`${this.id} ${this.ids ? this.ids.join() : ""} ${this.name || ""} `
);
const xor = new StringXor();
for (const m of chunkGraph.getChunkModulesIterable(this)) {
xor.add(chunkGraph.getModuleHash(m, this.runtime));
}
xor.updateHash(hash);
const entryModules =
chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this);
for (const [m, chunkGroup] of entryModules) {
hash.update(
`entry${chunkGraph.getModuleId(m)}${
/** @type {ChunkGroup} */ (chunkGroup).id
}`
);
}
}
/**
* Gets all async chunks.
* @returns {Chunks} a set of all the async chunks
*/
getAllAsyncChunks() {
/** @type {Queue} */
const queue = new Set();
/** @type {Chunks} */
const chunks = new Set();
const initialChunks = intersect(
Array.from(this.groupsIterable, (g) => new Set(g.chunks))
);
/** @type {Queue} */
const initialQueue = new Set(this.groupsIterable);
for (const chunkGroup of initialQueue) {
for (const child of chunkGroup.childrenIterable) {
if (child instanceof Entrypoint) {
initialQueue.add(child);
} else {
queue.add(child);
}
}
}
for (const chunkGroup of queue) {
for (const chunk of chunkGroup.chunks) {
if (!initialChunks.has(chunk)) {
chunks.add(chunk);
}
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return chunks;
}
/**
* Gets all initial chunks.
* @returns {Chunks} a set of all the initial chunks (including itself)
*/
getAllInitialChunks() {
/** @type {Chunks} */
const chunks = new Set();
/** @type {Queue} */
const queue = new Set(this.groupsIterable);
for (const group of queue) {
if (group.isInitial()) {
for (const c of group.chunks) chunks.add(c);
for (const g of group.childrenIterable) queue.add(g);
}
}
return chunks;
}
/**
* Gets all referenced chunks.
* @returns {Chunks} a set of all the referenced chunks (including itself)
*/
getAllReferencedChunks() {
/** @type {Queue} */
const queue = new Set(this.groupsIterable);
/** @type {Chunks} */
const chunks = new Set();
for (const chunkGroup of queue) {
for (const chunk of chunkGroup.chunks) {
chunks.add(chunk);
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return chunks;
}
/**
* Gets all referenced async entrypoints.
* @returns {Entrypoints} a set of all the referenced entrypoints
*/
getAllReferencedAsyncEntrypoints() {
/** @type {Queue} */
const queue = new Set(this.groupsIterable);
/** @type {Entrypoints} */
const entrypoints = new Set();
for (const chunkGroup of queue) {
for (const entrypoint of chunkGroup.asyncEntrypointsIterable) {
entrypoints.add(/** @type {Entrypoint} */ (entrypoint));
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return entrypoints;
}
/**
* Checks whether this chunk has async chunks.
* @returns {boolean} true, if the chunk references async chunks
*/
hasAsyncChunks() {
/** @type {Queue} */
const queue = new Set();
const initialChunks = intersect(
Array.from(this.groupsIterable, (g) => new Set(g.chunks))
);
for (const chunkGroup of this.groupsIterable) {
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
for (const chunkGroup of queue) {
for (const chunk of chunkGroup.chunks) {
if (!initialChunks.has(chunk)) {
return true;
}
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return false;
}
/**
* Gets child ids by orders.
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {ChunkFilterPredicate=} filterFn function used to filter chunks
* @returns {Record<string, ChunkId[]>} a record object of names to lists of child ids(?)
*/
getChildIdsByOrders(chunkGraph, filterFn) {
/** @type {Map<string, { order: number, group: ChunkGroup }[]>} */
const lists = new Map();
for (const group of this.groupsIterable) {
if (group.chunks[group.chunks.length - 1] === this) {
for (const childGroup of group.childrenIterable) {
const edgeOptions = group.getChildOrderOptions(
childGroup,
chunkGraph
);
for (const key of Object.keys(edgeOptions)) {
const name = key.slice(0, key.length - "Order".length);
let list = lists.get(name);
if (list === undefined) {
list = [];
lists.set(name, list);
}
list.push({
order: edgeOptions[key],
group: childGroup
});
}
}
}
}
/** @type {Record<string, ChunkId[]>} */
const result = Object.create(null);
for (const [name, list] of lists) {
list.sort((a, b) => {
const cmp = b.order - a.order;
if (cmp !== 0) return cmp;
return a.group.compareTo(chunkGraph, b.group);
});
/** @type {Set<ChunkId>} */
const chunkIdSet = new Set();
for (const item of list) {
for (const chunk of item.group.chunks) {
if (filterFn && !filterFn(chunk, chunkGraph)) continue;
chunkIdSet.add(/** @type {ChunkId} */ (chunk.id));
}
}
if (chunkIdSet.size > 0) {
result[name] = [...chunkIdSet];
}
}
return result;
}
/**
* Gets children of type in order.
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {string} type option name
* @returns {ChunkChildOfTypeInOrder[] | undefined} referenced chunks for a specific type
*/
getChildrenOfTypeInOrder(chunkGraph, type) {
/** @type {{ order: number, group: ChunkGroup, childGroup: ChunkGroup }[]} */
const list = [];
for (const group of this.groupsIterable) {
for (const childGroup of group.childrenIterable) {
const edgeOptions = group.getChildOrderOptions(childGroup, chunkGraph);
const order = edgeOptions[type];
if (order === undefined) continue;
list.push({
order,
group,
childGroup
});
}
}
if (list.length === 0) return;
list.sort((a, b) => {
const cmp = b.order - a.order;
if (cmp !== 0) return cmp;
return a.group.compareTo(chunkGraph, b.group);
});
/** @type {ChunkChildOfTypeInOrder[]} */
const result = [];
/** @type {undefined | ChunkChildOfTypeInOrder} */
let lastEntry;
for (const { group, childGroup } of list) {
if (lastEntry && lastEntry.onChunks === group.chunks) {
for (const chunk of childGroup.chunks) {
lastEntry.chunks.add(chunk);
}
} else {
result.push(
(lastEntry = {
onChunks: group.chunks,
chunks: new Set(childGroup.chunks)
})
);
}
}
return result;
}
/**
* Gets child ids by orders map.
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {boolean=} includeDirectChildren include direct children (by default only children of async children are included)
* @param {ChunkFilterPredicate=} filterFn function used to filter chunks
* @returns {ChunkChildIdsByOrdersMapByData} a record object of names to lists of child ids(?) by chunk id
*/
getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) {
/** @type {ChunkChildIdsByOrdersMapByData} */
const chunkMaps = Object.create(null);
/**
* Adds child ids by orders to map.
* @param {Chunk} chunk a chunk
* @returns {void}
*/
const addChildIdsByOrdersToMap = (chunk) => {
const data = chunk.getChildIdsByOrders(chunkGraph, filterFn);
for (const key of Object.keys(data)) {
let chunkMap = chunkMaps[key];
if (chunkMap === undefined) {
chunkMaps[key] = chunkMap = Object.create(null);
}
chunkMap[/** @type {ChunkId} */ (chunk.id)] = data[key];
}
};
if (includeDirectChildren) {
/** @type {Chunks} */
const chunks = new Set();
for (const chunkGroup of this.groupsIterable) {
for (const chunk of chunkGroup.chunks) {
chunks.add(chunk);
}
}
for (const chunk of chunks) {
addChildIdsByOrdersToMap(chunk);
}
}
for (const chunk of this.getAllAsyncChunks()) {
addChildIdsByOrdersToMap(chunk);
}
return chunkMaps;
}
/**
* Checks whether this chunk contains the chunk graph.
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {string} type option name
* @param {boolean=} includeDirectChildren include direct children (by default only children of async children are included)
* @param {ChunkFilterPredicate=} filterFn function used to filter chunks
* @returns {boolean} true when the child is of type order, otherwise false
*/
hasChildByOrder(chunkGraph, type, includeDirectChildren, filterFn) {
if (includeDirectChildren) {
/** @type {Chunks} */
const chunks = new Set();
for (const chunkGroup of this.groupsIterable) {
for (const chunk of chunkGroup.chunks) {
chunks.add(chunk);
}
}
for (const chunk of chunks) {
const data = chunk.getChildIdsByOrders(chunkGraph, filterFn);
if (data[type] !== undefined) return true;
}
}
for (const chunk of this.getAllAsyncChunks()) {
const data = chunk.getChildIdsByOrders(chunkGraph, filterFn);
if (data[type] !== undefined) return true;
}
return false;
}
}
module.exports = Chunk;

2083
node_modules/webpack/lib/ChunkGraph.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

701
node_modules/webpack/lib/ChunkGroup.js generated vendored Normal file
View File

@@ -0,0 +1,701 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const SortableSet = require("./util/SortableSet");
const {
compareChunks,
compareIterables,
compareLocations
} = require("./util/comparators");
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Entrypoint")} Entrypoint */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {{ module: Module | null, loc: DependencyLocation, request: string }} OriginRecord */
/**
* Describes the scheduling hints that can be attached to a chunk group.
* These values influence how child groups are ordered for preload/prefetch
* and how their fetch priority is exposed to runtime code.
* @typedef {object} RawChunkGroupOptions
* @property {number=} preloadOrder
* @property {number=} prefetchOrder
* @property {("low" | "high" | "auto")=} fetchPriority
*/
/** @typedef {RawChunkGroupOptions & { name?: string | null }} ChunkGroupOptions */
let debugId = 5000;
/**
* Materializes a sortable set as an array without changing its current order.
* Used with `SortableSet` caches that expect a stable array result.
* @template T
* @param {SortableSet<T>} set set to convert to array.
* @returns {T[]} the array format of existing set
*/
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
*/
const sortById = (a, b) => {
if (a.id < b.id) return -1;
if (b.id < a.id) return 1;
return 0;
};
/**
* Orders origin records by referencing module and then by source location.
* This keeps origin metadata deterministic for hashing and diagnostics.
* @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
*/
const sortOrigin = (a, b) => {
const aIdent = a.module ? a.module.identifier() : "";
const bIdent = b.module ? b.module.identifier() : "";
if (aIdent < bIdent) return -1;
if (aIdent > bIdent) return 1;
return compareLocations(a.loc, b.loc);
};
/**
* Represents a connected group of chunks along with the parent/child
* relationships, async blocks, and traversal metadata webpack tracks for it.
*/
class ChunkGroup {
/**
* Creates a chunk group and initializes the relationship sets and ordering
* metadata used while building and optimizing the chunk graph.
* @param {string | ChunkGroupOptions=} options chunk group options passed to chunkGroup
*/
constructor(options) {
if (typeof options === "string") {
options = { name: options };
} else if (!options) {
options = { name: undefined };
}
/** @type {number} */
this.groupDebugId = debugId++;
/** @type {ChunkGroupOptions} */
this.options = options;
/** @type {SortableSet<ChunkGroup>} */
this._children = new SortableSet(undefined, sortById);
/** @type {SortableSet<ChunkGroup>} */
this._parents = new SortableSet(undefined, sortById);
/** @type {SortableSet<ChunkGroup>} */
this._asyncEntrypoints = new SortableSet(undefined, sortById);
/** @type {SortableSet<AsyncDependenciesBlock>} */
this._blocks = new SortableSet();
/** @type {Chunk[]} */
this.chunks = [];
/** @type {OriginRecord[]} */
this.origins = [];
/** @typedef {Map<Module, number>} OrderIndices */
/** Indices in top-down order */
/**
* @private
* @type {OrderIndices}
*/
this._modulePreOrderIndices = new Map();
/** Indices in bottom-up order */
/**
* @private
* @type {OrderIndices}
*/
this._modulePostOrderIndices = new Map();
/** @type {number | undefined} */
this.index = undefined;
}
/**
* Merges additional options into the chunk group.
* Order-based options are combined by taking the higher priority, while
* unsupported conflicts surface as an explicit error.
* @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions
* @returns {void}
*/
addOptions(options) {
for (const key of /** @type {(keyof ChunkGroupOptions)[]} */ (
Object.keys(options)
)) {
if (this.options[key] === undefined) {
/** @type {ChunkGroupOptions[keyof ChunkGroupOptions]} */
(this.options[key]) = options[key];
} else if (this.options[key] !== options[key]) {
if (key.endsWith("Order")) {
const orderKey =
/** @type {Exclude<keyof ChunkGroupOptions, "name" | "fetchPriority">} */
(key);
this.options[orderKey] = Math.max(
/** @type {number} */
(this.options[orderKey]),
/** @type {number} */
(options[orderKey])
);
} else {
throw new Error(
`ChunkGroup.addOptions: No option merge strategy for ${key}`
);
}
}
}
}
/**
* Returns the configured name of the chunk group, if one was assigned.
* @returns {ChunkGroupOptions["name"]} returns the ChunkGroup name
*/
get name() {
return this.options.name;
}
/**
* Updates the configured name of the chunk group.
* @param {string | undefined} value the new name for ChunkGroup
* @returns {void}
*/
set name(value) {
this.options.name = value;
}
/* istanbul ignore next */
/**
* Returns a debug-only identifier derived from the group's member chunk
* debug ids. This is primarily useful in diagnostics and assertions.
* @returns {string} a unique concatenation of chunk debugId's
*/
get debugId() {
return Array.from(this.chunks, (x) => x.debugId).join("+");
}
/**
* Returns an identifier derived from the ids of the chunks currently in
* the group.
* @returns {string} a unique concatenation of chunk ids
*/
get id() {
return Array.from(this.chunks, (x) => x.id).join("+");
}
/**
* Moves a chunk to the front of the group or inserts it when it is not
* already present.
* @param {Chunk} chunk chunk being unshifted
* @returns {boolean} returns true if attempted chunk shift is accepted
*/
unshiftChunk(chunk) {
const oldIdx = this.chunks.indexOf(chunk);
if (oldIdx > 0) {
this.chunks.splice(oldIdx, 1);
this.chunks.unshift(chunk);
} else if (oldIdx < 0) {
this.chunks.unshift(chunk);
return true;
}
return false;
}
/**
* Inserts a chunk directly before another chunk that already belongs to the
* group, preserving the rest of the ordering.
* @param {Chunk} chunk Chunk being inserted
* @param {Chunk} before Placeholder/target chunk marking new chunk insertion point
* @returns {boolean} return true if insertion was successful
*/
insertChunk(chunk, before) {
const oldIdx = this.chunks.indexOf(chunk);
const idx = this.chunks.indexOf(before);
if (idx < 0) {
throw new Error("before chunk not found");
}
if (oldIdx >= 0 && oldIdx > idx) {
this.chunks.splice(oldIdx, 1);
this.chunks.splice(idx, 0, chunk);
} else if (oldIdx < 0) {
this.chunks.splice(idx, 0, chunk);
return true;
}
return false;
}
/**
* Appends a chunk to the group when it is not already a member.
* @param {Chunk} chunk chunk being pushed into ChunkGroupS
* @returns {boolean} returns true if chunk addition was successful.
*/
pushChunk(chunk) {
const oldIdx = this.chunks.indexOf(chunk);
if (oldIdx >= 0) {
return false;
}
this.chunks.push(chunk);
return true;
}
/**
* Replaces one member chunk with another while preserving the group's
* ordering and avoiding duplicates.
* @param {Chunk} oldChunk chunk to be replaced
* @param {Chunk} newChunk New chunk that will be replaced with
* @returns {boolean | undefined} returns true if the replacement was successful
*/
replaceChunk(oldChunk, newChunk) {
const oldIdx = this.chunks.indexOf(oldChunk);
if (oldIdx < 0) return false;
const newIdx = this.chunks.indexOf(newChunk);
if (newIdx < 0) {
this.chunks[oldIdx] = newChunk;
return true;
}
if (newIdx < oldIdx) {
this.chunks.splice(oldIdx, 1);
return true;
} else if (newIdx !== oldIdx) {
this.chunks[oldIdx] = newChunk;
this.chunks.splice(newIdx, 1);
return true;
}
}
/**
* Removes a chunk from this group.
* @param {Chunk} chunk chunk to remove
* @returns {boolean} returns true if chunk was removed
*/
removeChunk(chunk) {
const idx = this.chunks.indexOf(chunk);
if (idx >= 0) {
this.chunks.splice(idx, 1);
return true;
}
return false;
}
/**
* Indicates whether this chunk group is loaded as part of the initial page
* load instead of being created lazily.
* @returns {boolean} true, when this chunk group will be loaded on initial page load
*/
isInitial() {
return false;
}
/**
* Adds a child chunk group to the current group.
* @param {ChunkGroup} group chunk group to add
* @returns {boolean} returns true if chunk group was added
*/
addChild(group) {
const size = this._children.size;
this._children.add(group);
return size !== this._children.size;
}
/**
* Returns the child chunk groups reachable from this group.
* @returns {ChunkGroup[]} returns the children of this group
*/
getChildren() {
return this._children.getFromCache(getArray);
}
getNumberOfChildren() {
return this._children.size;
}
get childrenIterable() {
return this._children;
}
/**
* Removes a child chunk group and clears the corresponding parent link on
* the removed child.
* @param {ChunkGroup} group the chunk group to remove
* @returns {boolean} returns true if the chunk group was removed
*/
removeChild(group) {
if (!this._children.has(group)) {
return false;
}
this._children.delete(group);
group.removeParent(this);
return true;
}
/**
* Records a parent chunk group relationship.
* @param {ChunkGroup} parentChunk the parent group to be added into
* @returns {boolean} returns true if this chunk group was added to the parent group
*/
addParent(parentChunk) {
if (!this._parents.has(parentChunk)) {
this._parents.add(parentChunk);
return true;
}
return false;
}
/**
* Returns the parent chunk groups that can lead to this group.
* @returns {ChunkGroup[]} returns the parents of this group
*/
getParents() {
return this._parents.getFromCache(getArray);
}
getNumberOfParents() {
return this._parents.size;
}
/**
* Checks whether the provided group is registered as a parent.
* @param {ChunkGroup} parent the parent group
* @returns {boolean} returns true if the parent group contains this group
*/
hasParent(parent) {
return this._parents.has(parent);
}
get parentsIterable() {
return this._parents;
}
/**
* Removes a parent chunk group and clears the reverse child relationship.
* @param {ChunkGroup} chunkGroup the parent group
* @returns {boolean} returns true if this group has been removed from the parent
*/
removeParent(chunkGroup) {
if (this._parents.delete(chunkGroup)) {
chunkGroup.removeChild(this);
return true;
}
return false;
}
/**
* Registers an async entrypoint that is rooted in this chunk group.
* @param {Entrypoint} entrypoint entrypoint to add
* @returns {boolean} returns true if entrypoint was added
*/
addAsyncEntrypoint(entrypoint) {
const size = this._asyncEntrypoints.size;
this._asyncEntrypoints.add(entrypoint);
return size !== this._asyncEntrypoints.size;
}
get asyncEntrypointsIterable() {
return this._asyncEntrypoints;
}
/**
* Returns the async dependency blocks that create or reference this group.
* @returns {AsyncDependenciesBlock[]} an array containing the blocks
*/
getBlocks() {
return this._blocks.getFromCache(getArray);
}
getNumberOfBlocks() {
return this._blocks.size;
}
/**
* Checks whether an async dependency block is associated with this group.
* @param {AsyncDependenciesBlock} block block
* @returns {boolean} true, if block exists
*/
hasBlock(block) {
return this._blocks.has(block);
}
/**
* Exposes the group's async dependency blocks as an iterable.
* @returns {Iterable<AsyncDependenciesBlock>} blocks
*/
get blocksIterable() {
return this._blocks;
}
/**
* Associates an async dependency block with this chunk group.
* @param {AsyncDependenciesBlock} block a block
* @returns {boolean} false, if block was already added
*/
addBlock(block) {
if (!this._blocks.has(block)) {
this._blocks.add(block);
return true;
}
return false;
}
/**
* Records where this chunk group originated from in user code.
* The origin is used for diagnostics, ordering, and reporting.
* @param {Module | null} module origin module
* @param {DependencyLocation} loc location of the reference in the origin module
* @param {string} request request name of the reference
* @returns {void}
*/
addOrigin(module, loc, request) {
this.origins.push({
module,
loc,
request
});
}
/**
* Collects the emitted files produced by every chunk in the group.
* @returns {string[]} the files contained this chunk group
*/
getFiles() {
/** @type {Set<string>} */
const files = new Set();
for (const chunk of this.chunks) {
for (const file of chunk.files) {
files.add(file);
}
}
return [...files];
}
/**
* Disconnects this group from its parents, children, and chunks.
* Child groups are reconnected to this group's parents so the surrounding
* graph remains intact after removal.
* @returns {void}
*/
remove() {
// cleanup parents
for (const parentChunkGroup of this._parents) {
// remove this chunk from its parents
parentChunkGroup._children.delete(this);
// cleanup "sub chunks"
for (const chunkGroup of this._children) {
/**
* remove this chunk as "intermediary" and connect
* it "sub chunks" and parents directly
*/
// add parent to each "sub chunk"
chunkGroup.addParent(parentChunkGroup);
// add "sub chunk" to parent
parentChunkGroup.addChild(chunkGroup);
}
}
/**
* we need to iterate again over the children
* to remove this from the child's parents.
* This can not be done in the above loop
* as it is not guaranteed that `this._parents` contains anything.
*/
for (const chunkGroup of this._children) {
// remove this as parent of every "sub chunk"
chunkGroup._parents.delete(this);
}
// remove chunks
for (const chunk of this.chunks) {
chunk.removeGroup(this);
}
}
sortItems() {
this.origins.sort(sortOrigin);
}
/**
* Sorting predicate which allows current ChunkGroup to be compared against another.
* Sorting values are based off of number of chunks in ChunkGroup.
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {ChunkGroup} otherGroup the chunkGroup to compare this against
* @returns {-1 | 0 | 1} sort position for comparison
*/
compareTo(chunkGraph, otherGroup) {
if (this.chunks.length > otherGroup.chunks.length) return -1;
if (this.chunks.length < otherGroup.chunks.length) return 1;
return compareIterables(compareChunks(chunkGraph))(
this.chunks,
otherGroup.chunks
);
}
/**
* Aggregates per-block `*Order` options for the blocks that bridge this
* chunk group to the given child chunk group. `*Order` options are tied to
* the originating `import()` call and must not be sourced from the child's
* shared options, otherwise a webpackPrefetch/Preload directive from one
* parent would leak into other parents that share the child by name.
* @param {ChunkGroup} childGroup the child chunk group
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {Record<string, number>} merged `*Order` options for the edge from this group to `childGroup`
*/
getChildOrderOptions(childGroup, chunkGraph) {
/** @type {Record<string, number>} */
const result = Object.create(null);
let bridged = false;
for (const block of childGroup.blocksIterable) {
const rootModule = /** @type {Module} */ (block.getRootBlock());
if (!chunkGraph.isModuleInChunkGroup(rootModule, this)) continue;
bridged = true;
const opts = block.groupOptions;
if (!opts) continue;
for (const key of Object.keys(opts)) {
if (!key.endsWith("Order")) continue;
const value =
/** @type {number} */
(opts[/** @type {keyof ChunkGroupOptions} */ (key)]);
if (typeof value !== "number") continue;
if (result[key] === undefined || value > result[key]) {
result[key] = value;
}
}
}
// Fall back to the child's own options only when no block bridges
// this edge (e.g. a chunk group created by APIs that don't go through
// an AsyncDependenciesBlock). Otherwise we'd reintroduce the leak.
if (!bridged) {
for (const key of Object.keys(childGroup.options)) {
if (!key.endsWith("Order")) continue;
const value =
childGroup.options[/** @type {keyof ChunkGroupOptions} */ (key)];
if (typeof value === "number") {
result[key] = value;
}
}
}
return result;
}
/**
* Groups child chunk groups by their `*Order` options and sorts each group
* by descending order and deterministic chunk-group comparison.
* @param {ModuleGraph} moduleGraph the module graph
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {Record<string, ChunkGroup[]>} mapping from children type to ordered list of ChunkGroups
*/
getChildrenByOrders(moduleGraph, chunkGraph) {
/** @type {Map<string, { order: number, group: ChunkGroup }[]>} */
const lists = new Map();
for (const childGroup of this._children) {
const edgeOptions = this.getChildOrderOptions(childGroup, chunkGraph);
for (const key of Object.keys(edgeOptions)) {
const name = key.slice(0, key.length - "Order".length);
let list = lists.get(name);
if (list === undefined) {
lists.set(name, (list = []));
}
list.push({
order: edgeOptions[key],
group: childGroup
});
}
}
/** @type {Record<string, ChunkGroup[]>} */
const result = Object.create(null);
for (const [name, list] of lists) {
list.sort((a, b) => {
const cmp = b.order - a.order;
if (cmp !== 0) return cmp;
return a.group.compareTo(chunkGraph, b.group);
});
result[name] = list.map((i) => i.group);
}
return result;
}
/**
* Stores the module's top-down traversal index within this group.
* @param {Module} module module for which the index should be set
* @param {number} index the index of the module
* @returns {void}
*/
setModulePreOrderIndex(module, index) {
this._modulePreOrderIndices.set(module, index);
}
/**
* Returns the module's top-down traversal index within this group.
* @param {Module} module the module
* @returns {number | undefined} index
*/
getModulePreOrderIndex(module) {
return this._modulePreOrderIndices.get(module);
}
/**
* Stores the module's bottom-up traversal index within this group.
* @param {Module} module module for which the index should be set
* @param {number} index the index of the module
* @returns {void}
*/
setModulePostOrderIndex(module, index) {
this._modulePostOrderIndices.set(module, index);
}
/**
* Returns the module's bottom-up traversal index within this group.
* @param {Module} module the module
* @returns {number | undefined} index
*/
getModulePostOrderIndex(module) {
return this._modulePostOrderIndices.get(module);
}
/* istanbul ignore next */
checkConstraints() {
const chunk = this;
for (const child of chunk._children) {
if (!child._parents.has(chunk)) {
throw new Error(
`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`
);
}
}
for (const parentChunk of chunk._parents) {
if (!parentChunk._children.has(chunk)) {
throw new Error(
`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`
);
}
}
}
}
ChunkGroup.prototype.getModuleIndex = util.deprecate(
ChunkGroup.prototype.getModulePreOrderIndex,
"ChunkGroup.getModuleIndex was renamed to getModulePreOrderIndex",
"DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX"
);
ChunkGroup.prototype.getModuleIndex2 = util.deprecate(
ChunkGroup.prototype.getModulePostOrderIndex,
"ChunkGroup.getModuleIndex2 was renamed to getModulePostOrderIndex",
"DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX_2"
);
module.exports = ChunkGroup;

190
node_modules/webpack/lib/ChunkTemplate.js generated vendored Normal file
View File

@@ -0,0 +1,190 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").ChunkHashContext} ChunkHashContext */
/** @typedef {import("./Compilation").Hash} Hash */
/** @typedef {import("./Compilation").RenderManifestEntry} RenderManifestEntry */
/** @typedef {import("./Compilation").RenderManifestOptions} RenderManifestOptions */
/** @typedef {import("./Compilation").Source} Source */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
/**
* Defines the if set type used by this module.
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
// TODO webpack 6 remove this class
class ChunkTemplate {
/**
* Creates an instance of ChunkTemplate.
* @param {OutputOptions} outputOptions output options
* @param {Compilation} compilation the compilation
*/
constructor(outputOptions, compilation) {
this._outputOptions = outputOptions || {};
this.hooks = Object.freeze({
renderManifest: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(renderManifestEntries: RenderManifestEntry[], renderManifestOptions: RenderManifestOptions) => RenderManifestEntry[]} fn function
*/
(options, fn) => {
compilation.hooks.renderManifest.tap(
options,
(entries, options) => {
if (options.chunk.hasRuntime()) return entries;
return fn(entries, options);
}
);
},
"ChunkTemplate.hooks.renderManifest is deprecated (use Compilation.hooks.renderManifest instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_RENDER_MANIFEST"
)
},
modules: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, moduleTemplate: ModuleTemplate, renderContext: RenderContext) => Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderChunk.tap(options, (source, renderContext) =>
fn(
source,
compilation.moduleTemplates.javascript,
renderContext
)
);
},
"ChunkTemplate.hooks.modules is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderChunk instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_MODULES"
)
},
render: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, moduleTemplate: ModuleTemplate, renderContext: RenderContext) => Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderChunk.tap(options, (source, renderContext) =>
fn(
source,
compilation.moduleTemplates.javascript,
renderContext
)
);
},
"ChunkTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderChunk instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_RENDER"
)
},
renderWithEntry: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, chunk: Chunk) => Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.render.tap(options, (source, renderContext) => {
if (
renderContext.chunkGraph.getNumberOfEntryModules(
renderContext.chunk
) === 0 ||
renderContext.chunk.hasRuntime()
) {
return source;
}
return fn(source, renderContext.chunk);
});
},
"ChunkTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_RENDER_WITH_ENTRY"
)
},
hash: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(hash: Hash) => void} fn function
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
"ChunkTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_HASH"
)
},
hashForChunk: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(hash: Hash, chunk: Chunk, chunkHashContext: ChunkHashContext) => void} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.chunkHash.tap(options, (chunk, hash, context) => {
if (chunk.hasRuntime()) return;
fn(hash, chunk, context);
});
},
"ChunkTemplate.hooks.hashForChunk is deprecated (use JavascriptModulesPlugin.getCompilationHooks().chunkHash instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_HASH_FOR_CHUNK"
)
}
});
}
}
Object.defineProperty(ChunkTemplate.prototype, "outputOptions", {
get: util.deprecate(
/**
* Returns output options.
* @this {ChunkTemplate}
* @returns {OutputOptions} output options
*/
function outputOptions() {
return this._outputOptions;
},
"ChunkTemplate.outputOptions is deprecated (use Compilation.outputOptions instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS"
)
});
module.exports = ChunkTemplate;

511
node_modules/webpack/lib/CleanPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,511 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
const path = require("path");
const asyncLib = require("neo-async");
const { SyncBailHook } = require("tapable");
const Compilation = require("./Compilation");
const { join } = require("./util/fs");
const processAsyncTree = require("./util/processAsyncTree");
/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/fs").IStats} IStats */
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
/** @typedef {import("./util/fs").StatsCallback} StatsCallback */
/** @typedef {Map<string, number>} Assets */
/**
* Defines the clean plugin compilation hooks type used by this module.
* @typedef {object} CleanPluginCompilationHooks
* @property {SyncBailHook<[string], boolean | void>} keep when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config
*/
/**
* Defines the keep fn callback.
* @callback KeepFn
* @param {string} path path
* @returns {boolean | undefined} true, if the path should be kept
*/
const _10sec = 10 * 1000;
/**
* merge assets map 2 into map 1
* @param {Assets} as1 assets
* @param {Assets} as2 assets
* @returns {void}
*/
const mergeAssets = (as1, as2) => {
for (const [key, value1] of as2) {
const value2 = as1.get(key);
if (!value2 || value1 > value2) as1.set(key, value1);
}
};
/** @typedef {Map<string, number>} CurrentAssets */
/**
* Returns set of directory paths.
* @param {CurrentAssets} assets current assets
* @returns {Set<string>} Set of directory paths
*/
function getDirectories(assets) {
/** @type {Set<string>} */
const directories = new Set();
/**
* Adds the provided filename to this object.
* @param {string} filename asset filename
*/
const addDirectory = (filename) => {
directories.add(path.dirname(filename));
};
// get directories of assets
for (const [asset] of assets) {
addDirectory(asset);
}
// and all parent directories
for (const directory of directories) {
addDirectory(directory);
}
return directories;
}
/** @typedef {Set<string>} Diff */
/**
* Returns diff to fs.
* @param {OutputFileSystem} fs filesystem
* @param {string} outputPath output path
* @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,
10,
(directory, callback) => {
/** @type {NonNullable<OutputFileSystem["readdir"]>} */
(fs.readdir)(join(fs, outputPath, directory), (err, entries) => {
if (err) {
if (err.code === "ENOENT") return callback();
if (err.code === "ENOTDIR") {
diff.add(directory);
return callback();
}
return callback(err);
}
for (const entry of /** @type {string[]} */ (entries)) {
const file = entry;
// Since path.normalize("./file") === path.normalize("file"),
// return file directly when directory === "."
const filename =
directory && directory !== "." ? `${directory}/${file}` : file;
if (!directories.has(filename) && !currentAssets.has(filename)) {
diff.add(filename);
}
}
callback();
});
},
(err) => {
if (err) return callback(err);
callback(null, diff);
}
);
};
/**
* Gets diff to old assets.
* @param {Assets} currentAssets assets list
* @param {Assets} oldAssets old assets list
* @returns {Diff} diff
*/
const getDiffToOldAssets = (currentAssets, oldAssets) => {
/** @type {Diff} */
const diff = new Set();
const now = Date.now();
for (const [asset, ts] of oldAssets) {
if (ts >= now) continue;
if (!currentAssets.has(asset)) diff.add(asset);
}
return diff;
};
/**
* Processes the provided f.
* @param {OutputFileSystem} fs filesystem
* @param {string} filename path to file
* @param {StatsCallback} callback callback for provided filename
* @returns {void}
*/
const doStat = (fs, filename, callback) => {
if ("lstat" in fs) {
/** @type {NonNullable<OutputFileSystem["lstat"]>} */
(fs.lstat)(filename, callback);
} else {
fs.stat(filename, callback);
}
};
/**
* Processes the provided f.
* @param {OutputFileSystem} fs filesystem
* @param {string} outputPath output path
* @param {boolean} dry only log instead of fs modification
* @param {Logger} logger logger
* @param {Diff} diff filenames of the assets that shouldn't be there
* @param {KeepFn} isKept check if the entry is ignored
* @param {(err?: Error, assets?: Assets) => void} callback callback
* @returns {void}
*/
const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
/**
* Processes the provided msg.
* @param {string} msg message
*/
const log = (msg) => {
if (dry) {
logger.info(msg);
} else {
logger.log(msg);
}
};
/** @typedef {{ type: "check" | "unlink" | "rmdir", filename: string, parent: { remaining: number, job: Job } | undefined }} Job */
/** @type {Job[]} */
const jobs = Array.from(diff.keys(), (filename) => ({
type: "check",
filename,
parent: undefined
}));
/** @type {Assets} */
const keptAssets = new Map();
processAsyncTree(
jobs,
10,
({ type, filename, parent }, push, callback) => {
const path = join(fs, outputPath, filename);
/**
* Describes how this handle error operation behaves.
* @param {Error & { code?: string }} err error
* @returns {void}
*/
const handleError = (err) => {
const isAlreadyRemoved = () =>
new Promise((resolve) => {
if (err.code === "ENOENT") {
resolve(true);
} else if (err.code === "EPERM") {
// https://github.com/isaacs/rimraf/blob/main/src/fix-eperm.ts#L37
// fs.existsSync(path) === false https://github.com/webpack/webpack/actions/runs/15493412975/job/43624272783?pr=19586
doStat(fs, path, (err) => {
if (err) {
resolve(err.code === "ENOENT");
} else {
resolve(false);
}
});
} else {
resolve(false);
}
});
isAlreadyRemoved().then((isRemoved) => {
if (isRemoved) {
log(`${filename} was removed during cleaning by something else`);
handleParent();
return callback();
}
return callback(err);
});
};
const handleParent = () => {
if (parent && --parent.remaining === 0) push(parent.job);
};
switch (type) {
case "check":
if (isKept(filename)) {
keptAssets.set(filename, 0);
// do not decrement parent entry as we don't want to delete the parent
log(`${filename} will be kept`);
return process.nextTick(callback);
}
doStat(fs, path, (err, stats) => {
if (err) return handleError(err);
if (!(/** @type {IStats} */ (stats).isDirectory())) {
push({
type: "unlink",
filename,
parent
});
return callback();
}
/** @type {NonNullable<OutputFileSystem["readdir"]>} */
(fs.readdir)(path, (err, _entries) => {
if (err) return handleError(err);
/** @type {Job} */
const deleteJob = {
type: "rmdir",
filename,
parent
};
const entries = /** @type {string[]} */ (_entries);
if (entries.length === 0) {
push(deleteJob);
} else {
const parentToken = {
remaining: entries.length,
job: deleteJob
};
for (const entry of entries) {
const file = /** @type {string} */ (entry);
if (file.startsWith(".")) {
log(
`${filename} will be kept (dot-files will never be removed)`
);
continue;
}
push({
type: "check",
filename: `${filename}/${file}`,
parent: parentToken
});
}
}
return callback();
});
});
break;
case "rmdir":
log(`${filename} will be removed`);
if (dry) {
handleParent();
return process.nextTick(callback);
}
if (!fs.rmdir) {
logger.warn(
`${filename} can't be removed because output file system doesn't support removing directories (rmdir)`
);
return process.nextTick(callback);
}
fs.rmdir(path, (err) => {
if (err) return handleError(err);
handleParent();
callback();
});
break;
case "unlink":
log(`${filename} will be removed`);
if (dry) {
handleParent();
return process.nextTick(callback);
}
if (!fs.unlink) {
logger.warn(
`${filename} can't be removed because output file system doesn't support removing files (rmdir)`
);
return process.nextTick(callback);
}
fs.unlink(path, (err) => {
if (err) return handleError(err);
handleParent();
callback();
});
break;
}
},
(err) => {
if (err) return callback(err);
callback(undefined, keptAssets);
}
);
};
/** @type {WeakMap<Compilation, CleanPluginCompilationHooks>} */
const compilationHooksMap = new WeakMap();
const PLUGIN_NAME = "CleanPlugin";
class CleanPlugin {
/**
* Returns the attached hooks.
* @param {Compilation} compilation the compilation
* @returns {CleanPluginCompilationHooks} the attached hooks
*/
static getCompilationHooks(compilation) {
if (!(compilation instanceof Compilation)) {
throw new TypeError(
"The 'compilation' argument must be an instance of Compilation"
);
}
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
keep: new SyncBailHook(["ignore"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/** @param {CleanOptions} options options */
constructor(options = {}) {
/** @type {CleanOptions} */
this.options = options;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
() => {
const { definitions } = require("../schemas/WebpackOptions.json");
return {
definitions,
oneOf: [{ $ref: "#/definitions/CleanOptions" }]
};
},
this.options,
{
name: "Clean Plugin",
baseDataPath: "options"
}
);
});
const { keep } = this.options;
/** @type {boolean} */
const dry = this.options.dry || false;
/** @type {KeepFn} */
const keepFn =
typeof keep === "function"
? keep
: typeof keep === "string"
? (path) => path.startsWith(keep)
: typeof keep === "object" && keep.test
? (path) => keep.test(path)
: () => false;
// 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} */
let oldAssets;
compiler.hooks.emit.tapAsync(
{
name: PLUGIN_NAME,
stage: 100
},
(compilation, callback) => {
const hooks = CleanPlugin.getCompilationHooks(compilation);
const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`);
const fs = /** @type {OutputFileSystem} */ (compiler.outputFileSystem);
if (!fs.readdir) {
return callback(
new Error(
`${PLUGIN_NAME}: Output filesystem doesn't support listing directories (readdir)`
)
);
}
/** @type {Assets} */
const currentAssets = new Map();
const now = Date.now();
for (const asset of Object.keys(compilation.assets)) {
if (/^[a-z]:\\|^\/|^\\\\/i.test(asset)) continue;
/** @type {string} */
let normalizedAsset;
let newNormalizedAsset = asset.replace(/\\/g, "/");
do {
normalizedAsset = newNormalizedAsset;
newNormalizedAsset = normalizedAsset.replace(
/(^|\/)(?!\.\.)[^/]+\/\.\.\//g,
"$1"
);
} while (newNormalizedAsset !== normalizedAsset);
if (normalizedAsset.startsWith("../")) continue;
const assetInfo = compilation.assetsInfo.get(asset);
if (assetInfo && assetInfo.hotModuleReplacement) {
currentAssets.set(normalizedAsset, now + _10sec);
} else {
currentAssets.set(normalizedAsset, 0);
}
}
const outputPath = compilation.getPath(compiler.outputPath, {});
/**
* Checks whether this clean plugin is kept.
* @param {string} path path
* @returns {boolean | undefined} true, if needs to be kept
*/
const isKept = (path) => {
const result = hooks.keep.call(path);
if (result !== undefined) return result;
return keepFn(path);
};
/**
* Processes the provided err.
* @param {(Error | null)=} err err
* @param {Diff=} diff diff
*/
const diffCallback = (err, diff) => {
if (err) {
oldAssets = undefined;
callback(err);
return;
}
applyDiff(
fs,
outputPath,
dry,
logger,
/** @type {Diff} */ (diff),
isKept,
(err, keptAssets) => {
if (err) {
oldAssets = undefined;
} else {
if (oldAssets) mergeAssets(currentAssets, oldAssets);
oldAssets = currentAssets;
if (keptAssets) mergeAssets(oldAssets, keptAssets);
}
callback(err);
}
);
};
if (oldAssets) {
diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets));
} else {
getDiffToFs(fs, outputPath, currentAssets, diffCallback);
}
}
);
}
}
module.exports = CleanPlugin;
module.exports._getDirectories = getDirectories;

186
node_modules/webpack/lib/CodeGenerationResults.js generated vendored Normal file
View File

@@ -0,0 +1,186 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { DEFAULTS } = require("./config/defaults");
const { getOrInsert } = require("./util/MapHelpers");
const { first } = require("./util/SetHelpers");
const createHash = require("./util/createHash");
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 */
/** @typedef {import("./util/Hash").HashFunction} HashFunction */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* Stores code generation results keyed by module and runtime so later stages
* can retrieve emitted sources, metadata, and derived hashes.
*/
class CodeGenerationResults {
/**
* Initializes an empty result store and remembers which hash function should
* be used when a result hash needs to be derived lazily.
* @param {HashFunction} hashFunction the hash function to use
*/
constructor(hashFunction = DEFAULTS.HASH_FUNCTION) {
/** @type {Map<Module, RuntimeSpecMap<CodeGenerationResult>>} */
this.map = new Map();
/** @type {HashFunction} */
this._hashFunction = hashFunction;
}
/**
* Returns the code generation result for a module/runtime pair, rejecting
* ambiguous lookups where no unique runtime-independent result exists.
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {CodeGenerationResult} the CodeGenerationResult
*/
get(module, runtime) {
const entry = this.map.get(module);
if (entry === undefined) {
throw new Error(
`No code generation entry for ${module.identifier()} (existing entries: ${Array.from(
this.map.keys(),
(m) => m.identifier()
).join(", ")})`
);
}
if (runtime === undefined) {
if (entry.size > 1) {
const results = new Set(entry.values());
if (results.size !== 1) {
throw new Error(
`No unique code generation entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from(
entry.keys(),
(r) => runtimeToString(r)
).join(", ")}).
Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").`
);
}
return /** @type {CodeGenerationResult} */ (first(results));
}
return /** @type {CodeGenerationResult} */ (entry.values().next().value);
}
const result = entry.get(runtime);
if (result === undefined) {
throw new Error(
`No code generation entry for runtime ${runtimeToString(
runtime
)} for ${module.identifier()} (existing runtimes: ${Array.from(
entry.keys(),
(r) => runtimeToString(r)
).join(", ")})`
);
}
return result;
}
/**
* Reports whether a module has a stored result for the requested runtime, or
* a single unambiguous result when no runtime is specified.
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {boolean} true, when we have data for this
*/
has(module, runtime) {
const entry = this.map.get(module);
if (entry === undefined) {
return false;
}
if (runtime !== undefined) {
return entry.has(runtime);
} else if (entry.size > 1) {
const results = new Set(entry.values());
return results.size === 1;
}
return entry.size === 1;
}
/**
* Returns a generated source of the requested source type from a stored code
* generation result.
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {SourceType} sourceType the source type
* @returns {Source} a source
*/
getSource(module, runtime, sourceType) {
return /** @type {Source} */ (
this.get(module, runtime).sources.get(sourceType)
);
}
/**
* Returns the runtime requirements captured during code generation for the
* requested module/runtime pair.
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {ReadOnlyRuntimeRequirements | null} runtime requirements
*/
getRuntimeRequirements(module, runtime) {
return this.get(module, runtime).runtimeRequirements;
}
/**
* Returns an arbitrary metadata entry recorded during code generation.
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {string} key data key
* @returns {ReturnType<CodeGenerationResultData["get"]>} data generated by code generation
*/
getData(module, runtime, key) {
const data = this.get(module, runtime).data;
return data === undefined ? undefined : data.get(key);
}
/**
* Returns a stable hash for the generated sources and runtime requirements,
* computing and caching it on first access.
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {string} hash of the code generation
*/
getHash(module, runtime) {
const info = this.get(module, runtime);
if (info.hash !== undefined) return info.hash;
const hash = createHash(this._hashFunction);
for (const [type, source] of info.sources) {
hash.update(type);
source.updateHash(hash);
}
if (info.runtimeRequirements) {
for (const rr of info.runtimeRequirements) hash.update(rr);
}
return (info.hash = hash.digest("hex"));
}
/**
* Stores a code generation result for a module/runtime pair, creating the
* per-module runtime map when needed.
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {CodeGenerationResult} result result from module
* @returns {void}
*/
add(module, runtime, result) {
const map = getOrInsert(
this.map,
module,
() =>
/** @type {RuntimeSpecMap<CodeGenerationResult>} */
new RuntimeSpecMap()
);
map.set(runtime, result);
}
}
module.exports = CodeGenerationResults;

255
node_modules/webpack/lib/CompatibilityPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,255 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const ConstDependency = require("./dependencies/ConstDependency");
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/**
* Captures the source range of a renamed compatibility binding so it can be
* rewritten exactly once.
* @typedef {object} CompatibilitySettingsDeclaration
* @property {boolean} updated
* @property {DependencyLocation} loc
* @property {Range} range
*/
/**
* Stores the replacement variable name and the declaration metadata tracked
* for a compatibility rewrite.
* @typedef {object} CompatibilitySettings
* @property {string} name
* @property {CompatibilitySettingsDeclaration} declaration
*/
const nestedWebpackIdentifierTag = Symbol("nested webpack identifier");
const PLUGIN_NAME = "CompatibilityPlugin";
/**
* Adds parser-time compatibility rewrites for legacy runtime patterns that
* webpack still needs to recognize in user and generated code.
*/
class CompatibilityPlugin {
/**
* Installs parser hooks that preserve compatibility with legacy patterns
* such as nested `__webpack_require__` bindings and hashbang handling.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, (parser, parserOptions) => {
if (
parserOptions.browserify !== undefined &&
!parserOptions.browserify
) {
return;
}
parser.hooks.call.for("require").tap(
PLUGIN_NAME,
/**
* Rewrites browserify-style delegated `require` calls into a
* plain webpack require reference and removes the synthetic
* context dependency created for the delegator pattern.
* @param {CallExpression} expr call expression
* @returns {boolean | void} true when need to handle
*/
(expr) => {
// support for browserify style require delegator: "require(o, !0)"
if (expr.arguments.length !== 2) return;
const second = parser.evaluateExpression(expr.arguments[1]);
if (!second.isBoolean()) return;
if (second.asBool() !== true) return;
const dep = new ConstDependency(
"require",
/** @type {Range} */ (expr.callee.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
if (parser.state.current.dependencies.length > 0) {
const last =
/** @type {ContextDependency} */
(
parser.state.current.dependencies[
parser.state.current.dependencies.length - 1
]
);
if (
last.critical &&
last.options &&
last.options.request === "." &&
last.userRequest === "." &&
last.options.recursive
) {
parser.state.current.dependencies.pop();
}
}
parser.state.module.addPresentationalDependency(dep);
return true;
}
);
});
/**
* Attaches the compatibility rewrites for a JavaScript parser
* instance.
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const handler = (parser) => {
// Handle nested requires
parser.hooks.preStatement.tap(PLUGIN_NAME, (statement) => {
if (
statement.type === "FunctionDeclaration" &&
statement.id &&
statement.id.name === RuntimeGlobals.require
) {
const newName = `__nested_webpack_require_${
/** @type {Range} */
(statement.range)[0]
}__`;
parser.tagVariable(
statement.id.name,
nestedWebpackIdentifierTag,
{
name: newName,
declaration: {
updated: false,
loc: /** @type {DependencyLocation} */ (statement.id.loc),
range: /** @type {Range} */ (statement.id.range)
}
}
);
return true;
}
});
parser.hooks.pattern
.for(RuntimeGlobals.require)
.tap(PLUGIN_NAME, (pattern) => {
const newName = `__nested_webpack_require_${
/** @type {Range} */ (pattern.range)[0]
}__`;
parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, {
name: newName,
declaration: {
updated: false,
loc: /** @type {DependencyLocation} */ (pattern.loc),
range: /** @type {Range} */ (pattern.range)
}
});
if (parser.scope.topLevelScope !== true) {
return true;
}
});
parser.hooks.pattern
.for(RuntimeGlobals.exports)
.tap(PLUGIN_NAME, (pattern) => {
const newName = "__nested_webpack_exports__";
parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, {
name: newName,
declaration: {
updated: false,
loc: /** @type {DependencyLocation} */ (pattern.loc),
range: /** @type {Range} */ (pattern.range)
}
});
return true;
});
// Update single `var __webpack_require__ = {};` and `var __webpack_exports__ = {};` without expression
parser.hooks.declarator.tap(PLUGIN_NAME, (declarator) => {
if (
declarator.id.type === "Identifier" &&
(declarator.id.name === RuntimeGlobals.exports ||
declarator.id.name === RuntimeGlobals.require)
) {
const tagData = /** @type {CompatibilitySettings | undefined} */ (
parser.getTagData(
declarator.id.name,
nestedWebpackIdentifierTag
)
);
if (!tagData) return;
const { name, declaration } = tagData;
if (!declaration.updated) {
const dep = new ConstDependency(name, declaration.range);
dep.loc = declaration.loc;
parser.state.module.addPresentationalDependency(dep);
declaration.updated = true;
}
}
});
parser.hooks.expression
.for(nestedWebpackIdentifierTag)
.tap(PLUGIN_NAME, (expr) => {
const { name, declaration } =
/** @type {CompatibilitySettings} */
(parser.currentTagData);
if (!declaration.updated) {
const dep = new ConstDependency(name, declaration.range);
dep.loc = declaration.loc;
parser.state.module.addPresentationalDependency(dep);
declaration.updated = true;
}
const dep = new ConstDependency(
name,
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
// Handle hashbang
parser.hooks.program.tap(PLUGIN_NAME, (program, comments) => {
if (comments.length === 0) return;
const c = comments[0];
if (c.type === "Line" && /** @type {Range} */ (c.range)[0] === 0) {
if (parser.state.source.slice(0, 2).toString() !== "#!") return;
// this is a hashbang comment
const dep = new ConstDependency("//", 0);
dep.loc = /** @type {DependencyLocation} */ (c.loc);
parser.state.module.addPresentationalDependency(dep);
}
});
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = CompatibilityPlugin;
module.exports.nestedWebpackIdentifierTag = nestedWebpackIdentifierTag;

6055
node_modules/webpack/lib/Compilation.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1519
node_modules/webpack/lib/Compiler.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

204
node_modules/webpack/lib/ConcatenationScope.js generated vendored Normal file
View File

@@ -0,0 +1,204 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
DEFAULT_EXPORT,
NAMESPACE_OBJECT_EXPORT
} = require("./util/concatenate");
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */
/** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */
/** @typedef {import("./optimize/ConcatenatedModule").ExportName} Ids */
const MODULE_REFERENCE_REGEXP =
/^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(_deferredImport)?(?:_asiSafe(\d))?__$/;
/**
* Encodes how a concatenated module reference should be interpreted when it is
* later reconstructed from its placeholder identifier.
* @typedef {object} ModuleReferenceOptions
* @property {Ids} ids the properties or exports selected from the referenced module
* @property {boolean} call true, when this referenced export is called
* @property {boolean} directImport true, when this referenced export is directly imported (not via property access)
* @property {boolean} deferredImport true, when this referenced export is deferred
* @property {boolean | undefined} asiSafe if the position is ASI safe or unknown
*/
/**
* Tracks the symbols and cross-module references needed while rendering a
* concatenated module.
*/
class ConcatenationScope {
/**
* Creates the mutable scope object used while rendering a concatenated
* module and its cross-module references.
* @param {ModuleInfo[] | Map<Module, ModuleInfo>} modulesMap all module info by module
* @param {ConcatenatedModuleInfo} currentModule the current module info
* @param {Set<string>} usedNames all used names
*/
constructor(modulesMap, currentModule, usedNames) {
this._currentModule = currentModule;
if (Array.isArray(modulesMap)) {
/** @type {Map<Module, ConcatenatedModuleInfo>} */
const map = new Map();
for (const info of modulesMap) {
map.set(info.module, /** @type {ConcatenatedModuleInfo} */ (info));
}
modulesMap = map;
}
this.usedNames = usedNames;
this._modulesMap = modulesMap;
}
/**
* Checks whether a module participates in the current concatenation scope.
* @param {Module} module the referenced module
* @returns {boolean} true, when it's in the scope
*/
isModuleInScope(module) {
return this._modulesMap.has(module);
}
/**
* Records the symbol that should be used when the current module exports a
* named binding.
* @param {string} exportName name of the export
* @param {string} symbol identifier of the export in source code
*/
registerExport(exportName, symbol) {
if (!this._currentModule.exportMap) {
this._currentModule.exportMap = new Map();
}
if (!this._currentModule.exportMap.has(exportName)) {
this._currentModule.exportMap.set(exportName, symbol);
}
}
/**
* Records a raw expression that can be used to reference an export without
* going through the normal symbol map.
* @param {string} exportName name of the export
* @param {string} expression expression to be used
*/
registerRawExport(exportName, expression) {
if (!this._currentModule.rawExportMap) {
this._currentModule.rawExportMap = new Map();
}
if (!this._currentModule.rawExportMap.has(exportName)) {
this._currentModule.rawExportMap.set(exportName, expression);
}
}
/**
* Returns the raw expression registered for an export, if one exists.
* @param {string} exportName name of the export
* @returns {string | undefined} the expression of the export
*/
getRawExport(exportName) {
if (!this._currentModule.rawExportMap) {
return undefined;
}
return this._currentModule.rawExportMap.get(exportName);
}
/**
* Replaces the raw expression for an export only when that export already
* has an entry in the raw export map.
* @param {string} exportName name of the export
* @param {string} expression expression to be used
*/
setRawExportMap(exportName, expression) {
if (!this._currentModule.rawExportMap) {
this._currentModule.rawExportMap = new Map();
}
if (this._currentModule.rawExportMap.has(exportName)) {
this._currentModule.rawExportMap.set(exportName, expression);
}
}
/**
* Records the symbol that should be used for the synthetic namespace export.
* @param {string} symbol identifier of the export in source code
*/
registerNamespaceExport(symbol) {
this._currentModule.namespaceExportSymbol = symbol;
}
/**
* Encodes a reference to another concatenated module as a placeholder
* identifier that can be parsed later during code generation.
* @param {Module} module the referenced module
* @param {Partial<ModuleReferenceOptions>} options options
* @returns {string} the reference as identifier
*/
createModuleReference(
module,
{
ids = undefined,
call = false,
directImport = false,
deferredImport = false,
asiSafe = false
}
) {
const info = /** @type {ModuleInfo} */ (this._modulesMap.get(module));
const callFlag = call ? "_call" : "";
const directImportFlag = directImport ? "_directImport" : "";
const deferredImportFlag = deferredImport ? "_deferredImport" : "";
const asiSafeFlag = asiSafe
? "_asiSafe1"
: asiSafe === false
? "_asiSafe0"
: "";
const exportData = ids
? Buffer.from(JSON.stringify(ids), "utf8").toString("hex")
: "ns";
// a "._" is appended to allow "delete ...", which would cause a SyntaxError in strict mode
return `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${directImportFlag}${deferredImportFlag}${asiSafeFlag}__._`;
}
/**
* Checks whether an identifier is one of webpack's encoded concatenation
* module references.
* @param {string} name the identifier
* @returns {boolean} true, when it's an module reference
*/
static isModuleReference(name) {
return MODULE_REFERENCE_REGEXP.test(name);
}
/**
* Parses an encoded module reference back into its module index and
* reference flags.
* @param {string} name the identifier
* @returns {ModuleReferenceOptions & { index: number } | null} parsed options and index
*/
static matchModuleReference(name) {
const match = MODULE_REFERENCE_REGEXP.exec(name);
if (!match) return null;
const index = Number(match[1]);
const asiSafe = match[6];
return {
index,
ids:
match[2] === "ns"
? []
: JSON.parse(Buffer.from(match[2], "hex").toString("utf8")),
call: Boolean(match[3]),
directImport: Boolean(match[4]),
deferredImport: Boolean(match[5]),
asiSafe: asiSafe ? asiSafe === "1" : undefined
};
}
}
ConcatenationScope.DEFAULT_EXPORT = DEFAULT_EXPORT;
ConcatenationScope.NAMESPACE_OBJECT_EXPORT = NAMESPACE_OBJECT_EXPORT;
module.exports = ConcatenationScope;

126
node_modules/webpack/lib/ConditionalInitFragment.js generated vendored Normal file
View File

@@ -0,0 +1,126 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, PrefixSource } = require("webpack-sources");
const InitFragment = require("./InitFragment");
const Template = require("./Template");
const { mergeRuntime } = require("./util/runtime");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* Returns wrapped source.
* @param {string} condition condition
* @param {string | Source} source source
* @returns {string | Source} wrapped source
*/
const wrapInCondition = (condition, source) => {
if (typeof source === "string") {
return Template.asString([
`if (${condition}) {`,
Template.indent(source),
"}",
""
]);
}
return new ConcatSource(
`if (${condition}) {\n`,
new PrefixSource("\t", source),
"}\n"
);
};
/**
* Represents ConditionalInitFragment.
* @extends {InitFragment<GenerateContext>}
*/
class ConditionalInitFragment extends InitFragment {
/**
* Creates an instance of ConditionalInitFragment.
* @param {string | Source | undefined} content the source code that will be included as initialization code
* @param {number} stage category of initialization code (contribute to order)
* @param {number} position position in the category (contribute to order)
* @param {string | undefined} key unique key to avoid emitting the same initialization code twice
* @param {RuntimeSpec | boolean} runtimeCondition in which runtime this fragment should be executed
* @param {string | Source=} endContent the source code that will be included at the end of the module
*/
constructor(
content,
stage,
position,
key,
runtimeCondition = true,
endContent = undefined
) {
super(content, stage, position, key, endContent);
this.runtimeCondition = runtimeCondition;
}
/**
* Returns the source code that will be included as initialization code.
* @param {GenerateContext} context context
* @returns {string | Source | undefined} the source code that will be included as initialization code
*/
getContent(context) {
if (this.runtimeCondition === false || !this.content) return "";
if (this.runtimeCondition === true) return this.content;
const expr = context.runtimeTemplate.runtimeConditionExpression({
chunkGraph: context.chunkGraph,
runtimeRequirements: context.runtimeRequirements,
runtime: context.runtime,
runtimeCondition: this.runtimeCondition
});
if (expr === "true") return this.content;
return wrapInCondition(expr, this.content);
}
/**
* Returns the source code that will be included at the end of the module.
* @param {GenerateContext} context context
* @returns {string | Source | undefined} the source code that will be included at the end of the module
*/
getEndContent(context) {
if (this.runtimeCondition === false || !this.endContent) return "";
if (this.runtimeCondition === true) return this.endContent;
const expr = context.runtimeTemplate.runtimeConditionExpression({
chunkGraph: context.chunkGraph,
runtimeRequirements: context.runtimeRequirements,
runtime: context.runtime,
runtimeCondition: this.runtimeCondition
});
if (expr === "true") return this.endContent;
return wrapInCondition(expr, this.endContent);
}
/**
* Returns merged fragment.
* @param {ConditionalInitFragment} other fragment to merge with
* @returns {ConditionalInitFragment} merged fragment
*/
merge(other) {
if (this.runtimeCondition === true) return this;
if (other.runtimeCondition === true) return other;
if (this.runtimeCondition === false) return other;
if (other.runtimeCondition === false) return this;
const runtimeCondition = mergeRuntime(
this.runtimeCondition,
other.runtimeCondition
);
return new ConditionalInitFragment(
this.content,
this.stage,
this.position,
this.key,
runtimeCondition,
this.endContent
);
}
}
module.exports = ConditionalInitFragment;

570
node_modules/webpack/lib/ConstPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,570 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const CachedConstDependency = require("./dependencies/CachedConstDependency");
const ConstDependency = require("./dependencies/ConstDependency");
const { evaluateToString } = require("./javascript/JavascriptParserHelpers");
const { parseResource } = require("./util/identifier");
/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").Identifier} Identifier */
/** @typedef {import("estree").Pattern} Pattern */
/** @typedef {import("estree").SourceLocation} SourceLocation */
/** @typedef {import("estree").Statement} Statement */
/** @typedef {import("estree").Super} Super */
/** @typedef {import("estree").VariableDeclaration} VariableDeclaration */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {Set<string>} Declarations */
/**
* Collect declaration.
* @param {Declarations} declarations set of declarations
* @param {Identifier | Pattern} pattern pattern to collect declarations from
*/
const collectDeclaration = (declarations, pattern) => {
const stack = [pattern];
while (stack.length > 0) {
const node = /** @type {Pattern} */ (stack.pop());
switch (node.type) {
case "Identifier":
declarations.add(node.name);
break;
case "ArrayPattern":
for (const element of node.elements) {
if (element) {
stack.push(element);
}
}
break;
case "AssignmentPattern":
stack.push(node.left);
break;
case "ObjectPattern":
for (const property of node.properties) {
stack.push(/** @type {AssignmentProperty} */ (property).value);
}
break;
case "RestElement":
stack.push(node.argument);
break;
}
}
};
/**
* Gets hoisted declarations.
* @param {Statement} branch branch to get hoisted declarations from
* @param {boolean} includeFunctionDeclarations whether to include function declarations
* @returns {string[]} hoisted declarations
*/
const getHoistedDeclarations = (branch, includeFunctionDeclarations) => {
/** @type {Declarations} */
const declarations = new Set();
/** @type {(Statement | null | undefined)[]} */
const stack = [branch];
while (stack.length > 0) {
const node = stack.pop();
// Some node could be `null` or `undefined`.
if (!node) continue;
switch (node.type) {
// Walk through control statements to look for hoisted declarations.
// Some branches are skipped since they do not allow declarations.
case "BlockStatement":
for (const stmt of node.body) {
stack.push(stmt);
}
break;
case "IfStatement":
stack.push(node.consequent);
stack.push(node.alternate);
break;
case "ForStatement":
stack.push(/** @type {VariableDeclaration} */ (node.init));
stack.push(node.body);
break;
case "ForInStatement":
case "ForOfStatement":
stack.push(/** @type {VariableDeclaration} */ (node.left));
stack.push(node.body);
break;
case "DoWhileStatement":
case "WhileStatement":
case "LabeledStatement":
stack.push(node.body);
break;
case "SwitchStatement":
for (const cs of node.cases) {
for (const consequent of cs.consequent) {
stack.push(consequent);
}
}
break;
case "TryStatement":
stack.push(node.block);
if (node.handler) {
stack.push(node.handler.body);
}
stack.push(node.finalizer);
break;
case "FunctionDeclaration":
if (includeFunctionDeclarations) {
collectDeclaration(declarations, /** @type {Identifier} */ (node.id));
}
break;
case "VariableDeclaration":
if (node.kind === "var") {
for (const decl of node.declarations) {
collectDeclaration(declarations, decl.id);
}
}
break;
}
}
return [...declarations];
};
const PLUGIN_NAME = "ConstPlugin";
class ConstPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const cachedParseResource = parseResource.bindCache(compiler.root);
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.dependencyTemplates.set(
CachedConstDependency,
new CachedConstDependency.Template()
);
/**
* Handles the hook callback for this code path.
* @param {JavascriptParser} parser the parser
*/
const handler = (parser) => {
parser.hooks.terminate.tap(PLUGIN_NAME, (_statement) => true);
parser.hooks.statementIf.tap(PLUGIN_NAME, (statement) => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(statement.test);
const bool = param.asBool();
if (typeof bool === "boolean") {
if (!param.couldHaveSideEffects()) {
const dep = new ConstDependency(
`${bool}`,
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (statement.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
parser.walkExpression(statement.test);
}
const branchToRemove = bool
? statement.alternate
: statement.consequent;
if (branchToRemove) {
this.eliminateUnusedStatement(parser, branchToRemove, true);
}
return bool;
}
});
parser.hooks.unusedStatement.tap(PLUGIN_NAME, (statement) => {
if (
parser.scope.isAsmJs ||
// Check top level scope here again
parser.scope.topLevelScope === true
) {
return;
}
this.eliminateUnusedStatement(parser, statement, false);
return true;
});
parser.hooks.expressionConditionalOperator.tap(
PLUGIN_NAME,
(expression) => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(expression.test);
const bool = param.asBool();
if (typeof bool === "boolean") {
if (!param.couldHaveSideEffects()) {
const dep = new ConstDependency(
` ${bool}`,
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
parser.walkExpression(expression.test);
}
// Expressions do not hoist.
// It is safe to remove the dead branch.
//
// Given the following code:
//
// false ? someExpression() : otherExpression();
//
// the generated code is:
//
// false ? 0 : otherExpression();
//
const branchToRemove = bool
? expression.alternate
: expression.consequent;
const dep = new ConstDependency(
"0",
/** @type {Range} */ (branchToRemove.range)
);
dep.loc = /** @type {SourceLocation} */ (branchToRemove.loc);
parser.state.module.addPresentationalDependency(dep);
return bool;
}
}
);
parser.hooks.expressionLogicalOperator.tap(
PLUGIN_NAME,
(expression) => {
if (parser.scope.isAsmJs) return;
if (
expression.operator === "&&" ||
expression.operator === "||"
) {
const param = parser.evaluateExpression(expression.left);
const bool = param.asBool();
if (typeof bool === "boolean") {
// Expressions do not hoist.
// It is safe to remove the dead branch.
//
// ------------------------------------------
//
// Given the following code:
//
// falsyExpression() && someExpression();
//
// the generated code is:
//
// falsyExpression() && false;
//
// ------------------------------------------
//
// Given the following code:
//
// truthyExpression() && someExpression();
//
// the generated code is:
//
// true && someExpression();
//
// ------------------------------------------
//
// Given the following code:
//
// truthyExpression() || someExpression();
//
// the generated code is:
//
// truthyExpression() || false;
//
// ------------------------------------------
//
// Given the following code:
//
// falsyExpression() || someExpression();
//
// the generated code is:
//
// false && someExpression();
//
const keepRight =
(expression.operator === "&&" && bool) ||
(expression.operator === "||" && !bool);
if (
!param.couldHaveSideEffects() &&
(param.isBoolean() || keepRight)
) {
// for case like
//
// return'development'===process.env.NODE_ENV&&'foo'
//
// we need a space before the bool to prevent result like
//
// returnfalse&&'foo'
//
const dep = new ConstDependency(
` ${bool}`,
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
parser.walkExpression(expression.left);
}
if (!keepRight) {
const dep = new ConstDependency(
"0",
/** @type {Range} */ (expression.right.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
}
return keepRight;
}
} else if (expression.operator === "??") {
const param = parser.evaluateExpression(expression.left);
const keepRight = param.asNullish();
if (typeof keepRight === "boolean") {
// ------------------------------------------
//
// Given the following code:
//
// nonNullish ?? someExpression();
//
// the generated code is:
//
// nonNullish ?? 0;
//
// ------------------------------------------
//
// Given the following code:
//
// nullish ?? someExpression();
//
// the generated code is:
//
// null ?? someExpression();
//
if (!param.couldHaveSideEffects() && keepRight) {
// cspell:word returnnull
// for case like
//
// return('development'===process.env.NODE_ENV&&null)??'foo'
//
// we need a space before the bool to prevent result like
//
// returnnull??'foo'
//
const dep = new ConstDependency(
" null",
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
const dep = new ConstDependency(
"0",
/** @type {Range} */ (expression.right.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
parser.walkExpression(expression.left);
}
return keepRight;
}
}
}
);
parser.hooks.optionalChaining.tap(PLUGIN_NAME, (expr) => {
/** @type {Expression[]} */
const optionalExpressionsStack = [];
/** @type {Expression | Super} */
let next = expr.expression;
while (
next.type === "MemberExpression" ||
next.type === "CallExpression"
) {
if (next.type === "MemberExpression") {
if (next.optional) {
// SuperNode can not be optional
optionalExpressionsStack.push(
/** @type {Expression} */ (next.object)
);
}
next = next.object;
} else {
if (next.optional) {
// SuperNode can not be optional
optionalExpressionsStack.push(
/** @type {Expression} */ (next.callee)
);
}
next = next.callee;
}
}
while (optionalExpressionsStack.length) {
const expression = optionalExpressionsStack.pop();
const evaluated = parser.evaluateExpression(
/** @type {Expression} */ (expression)
);
if (evaluated.asNullish()) {
// ------------------------------------------
//
// Given the following code:
//
// nullishMemberChain?.a.b();
//
// the generated code is:
//
// undefined;
//
// ------------------------------------------
//
const dep = new ConstDependency(
" undefined",
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {SourceLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
}
}
});
parser.hooks.evaluateIdentifier
.for("__resourceQuery")
.tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
return evaluateToString(
cachedParseResource(parser.state.module.resource).query
)(expr);
});
parser.hooks.expression
.for("__resourceQuery")
.tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
const dep = new CachedConstDependency(
JSON.stringify(
cachedParseResource(parser.state.module.resource).query
),
/** @type {Range} */ (expr.range),
"__resourceQuery"
);
dep.loc = /** @type {SourceLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
parser.hooks.evaluateIdentifier
.for("__resourceFragment")
.tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
return evaluateToString(
cachedParseResource(parser.state.module.resource).fragment
)(expr);
});
parser.hooks.expression
.for("__resourceFragment")
.tap(PLUGIN_NAME, (expr) => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
const dep = new CachedConstDependency(
JSON.stringify(
cachedParseResource(parser.state.module.resource).fragment
),
/** @type {Range} */ (expr.range),
"__resourceFragment"
);
dep.loc = /** @type {SourceLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
/**
* Eliminate an unused statement.
* @param {JavascriptParser} parser the parser
* @param {Statement} statement the statement to remove
* @param {boolean} alwaysInBlock whether to always generate curly brackets
* @returns {void}
*/
eliminateUnusedStatement(parser, statement, alwaysInBlock) {
// Before removing the unused branch, the hoisted declarations
// must be collected.
//
// Given the following code:
//
// if (true) f() else g()
// if (false) {
// function f() {}
// const g = function g() {}
// if (someTest) {
// let a = 1
// var x, {y, z} = obj
// }
// } else {
// …
// }
//
// the generated code is:
//
// if (true) f() else {}
// if (false) {
// var f, x, y, z; (in loose mode)
// var x, y, z; (in strict mode)
// } else {
// …
// }
//
// NOTE: When code runs in strict mode, `var` declarations
// are hoisted but `function` declarations don't.
//
const declarations = parser.scope.isStrict
? getHoistedDeclarations(statement, false)
: getHoistedDeclarations(statement, true);
const inBlock = alwaysInBlock || statement.type === "BlockStatement";
let replacement = inBlock ? "{" : "";
replacement +=
declarations.length > 0 ? ` var ${declarations.join(", ")}; ` : "";
replacement += inBlock ? "}" : "";
const dep = new ConstDependency(
`// removed by dead control flow\n${replacement}`,
/** @type {Range} */ (statement.range)
);
dep.loc = /** @type {SourceLocation} */ (statement.loc);
parser.state.module.addPresentationalDependency(dep);
}
}
module.exports = ConstPlugin;

34
node_modules/webpack/lib/ContextExclusionPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "ContextExclusionPlugin";
class ContextExclusionPlugin {
/**
* Creates an instance of ContextExclusionPlugin.
* @param {RegExp} negativeMatcher Matcher regular expression
*/
constructor(negativeMatcher) {
this.negativeMatcher = negativeMatcher;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => {
cmf.hooks.contextModuleFiles.tap(PLUGIN_NAME, (files) =>
files.filter((filePath) => !this.negativeMatcher.test(filePath))
);
});
}
}
module.exports = ContextExclusionPlugin;

1423
node_modules/webpack/lib/ContextModule.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

531
node_modules/webpack/lib/ContextModuleFactory.js generated vendored Normal file
View File

@@ -0,0 +1,531 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = require("tapable");
const ContextModule = require("./ContextModule");
const ModuleFactory = require("./ModuleFactory");
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const LazySet = require("./util/LazySet");
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 */
/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */
/** @typedef {import("./ResolverFactory")} ResolverFactory */
/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
/** @typedef {import("./dependencies/ContextDependency").ContextOptions} ContextOptions */
/**
* Defines the shared type used by this module.
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
*/
/** @typedef {import("./util/fs").IStats} IStats */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {{ context: string, request: string }} ContextAlternativeRequest */
/**
* Defines the context resolve data type used by this module.
* @typedef {object} ContextResolveData
* @property {string} context
* @property {string} request
* @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions
* @property {FileSystemDependencies} fileDependencies
* @property {FileSystemDependencies} missingDependencies
* @property {FileSystemDependencies} contextDependencies
* @property {ContextDependency[]} dependencies
*/
/** @typedef {ContextResolveData & ContextOptions} BeforeContextResolveData */
/** @typedef {BeforeContextResolveData & { resource: string | string[], resourceQuery: string | undefined, resourceFragment: string | undefined, resolveDependencies: ContextModuleFactory["resolveDependencies"] }} AfterContextResolveData */
const EMPTY_RESOLVE_OPTIONS = {};
class ContextModuleFactory extends ModuleFactory {
/**
* Creates an instance of ContextModuleFactory.
* @param {ResolverFactory} resolverFactory resolverFactory
*/
constructor(resolverFactory) {
super();
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[], ContextModuleOptions]>} */
const alternativeRequests = new AsyncSeriesWaterfallHook([
"modules",
"options"
]);
this.hooks = Object.freeze({
/** @type {AsyncSeriesWaterfallHook<[BeforeContextResolveData], BeforeContextResolveData | false | void>} */
beforeResolve: new AsyncSeriesWaterfallHook(["data"]),
/** @type {AsyncSeriesWaterfallHook<[AfterContextResolveData], AfterContextResolveData | false | void>} */
afterResolve: new AsyncSeriesWaterfallHook(["data"]),
/** @type {SyncWaterfallHook<[string[]]>} */
contextModuleFiles: new SyncWaterfallHook(["files"]),
/** @type {FakeHook<Pick<AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
alternatives: createFakeHook(
{
name: "alternatives",
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["intercept"]} */
intercept: (interceptor) => {
throw new Error(
"Intercepting fake hook ContextModuleFactory.hooks.alternatives is not possible, use ContextModuleFactory.hooks.alternativeRequests instead"
);
},
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tap"]} */
tap: (options, fn) => {
alternativeRequests.tap(options, fn);
},
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapAsync"]} */
tapAsync: (options, fn) => {
alternativeRequests.tapAsync(options, (items, _options, callback) =>
fn(items, callback)
);
},
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapPromise"]} */
tapPromise: (options, fn) => {
alternativeRequests.tapPromise(options, fn);
}
},
"ContextModuleFactory.hooks.alternatives has deprecated in favor of ContextModuleFactory.hooks.alternativeRequests with an additional options argument.",
"DEP_WEBPACK_CONTEXT_MODULE_FACTORY_ALTERNATIVES"
),
alternativeRequests
});
/** @type {ResolverFactory} */
this.resolverFactory = resolverFactory;
}
/**
* Processes the provided data.
* @param {ModuleFactoryCreateData} data data object
* @param {ModuleFactoryCallback} callback callback
* @returns {void}
*/
create(data, callback) {
const context = data.context;
const dependencies = /** @type {ContextDependency[]} */ (data.dependencies);
const resolveOptions = data.resolveOptions;
const dependency = dependencies[0];
/** @type {FileSystemDependencies} */
const fileDependencies = new LazySet();
/** @type {FileSystemDependencies} */
const missingDependencies = new LazySet();
/** @type {FileSystemDependencies} */
const contextDependencies = new LazySet();
this.hooks.beforeResolve.callAsync(
{
context,
dependencies,
layer: data.contextInfo.issuerLayer,
resolveOptions,
fileDependencies,
missingDependencies,
contextDependencies,
...dependency.options
},
(err, beforeResolveResult) => {
if (err) {
return callback(err, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
// Ignored
if (!beforeResolveResult) {
return callback(null, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
const context = beforeResolveResult.context;
const request = beforeResolveResult.request;
const resolveOptions = beforeResolveResult.resolveOptions;
/** @type {undefined | string[]} */
let loaders;
/** @type {undefined | string} */
let resource;
let loadersPrefix = "";
const idx = request.lastIndexOf("!");
if (idx >= 0) {
let loadersRequest = request.slice(0, idx + 1);
/** @type {number} */
let i;
for (
i = 0;
i < loadersRequest.length && loadersRequest[i] === "!";
i++
) {
loadersPrefix += "!";
}
loadersRequest = loadersRequest
.slice(i)
.replace(/!+$/, "")
.replace(/!{2,}/g, "!");
loaders = loadersRequest === "" ? [] : loadersRequest.split("!");
resource = request.slice(idx + 1);
} else {
loaders = [];
resource = request;
}
const contextResolver = this.resolverFactory.get(
"context",
dependencies.length > 0
? cachedSetProperty(
resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType",
dependencies[0].category
)
: resolveOptions
);
const loaderResolver = this.resolverFactory.get("loader");
asyncLib.parallel(
[
(callback) => {
const results = /** @type {ResolveRequest[]} */ ([]);
/**
* Processes the provided obj.
* @param {ResolveRequest} obj obj
* @returns {void}
*/
const yield_ = (obj) => {
results.push(obj);
};
contextResolver.resolve(
{},
context,
resource,
{
fileDependencies,
missingDependencies,
contextDependencies,
yield: yield_
},
(err) => {
if (err) return callback(err);
callback(null, results);
}
);
},
(callback) => {
asyncLib.map(
loaders,
(loader, callback) => {
loaderResolver.resolve(
{},
context,
loader,
{
fileDependencies,
missingDependencies,
contextDependencies
},
(err, result) => {
if (err) return callback(err);
callback(null, result);
}
);
},
callback
);
}
],
(err, result) => {
if (err) {
return callback(err, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
let [contextResult, loaderResult] =
/** @type {[ResolveRequest[], string[]]} */ (result);
if (contextResult.length > 1) {
const first = contextResult[0];
contextResult = contextResult.filter((r) => r.path);
if (contextResult.length === 0) contextResult.push(first);
}
this.hooks.afterResolve.callAsync(
{
addon:
loadersPrefix +
loaderResult.join("!") +
(loaderResult.length > 0 ? "!" : ""),
resource:
contextResult.length > 1
? /** @type {string[]} */ (contextResult.map((r) => r.path))
: /** @type {string} */ (contextResult[0].path),
resolveDependencies: this.resolveDependencies.bind(this),
resourceQuery: contextResult[0].query,
resourceFragment: contextResult[0].fragment,
...beforeResolveResult
},
(err, result) => {
if (err) {
return callback(err, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
// Ignored
if (!result) {
return callback(null, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
return callback(null, {
module: new ContextModule(result.resolveDependencies, result),
fileDependencies,
missingDependencies,
contextDependencies
});
}
);
}
);
}
);
}
/**
* Resolves dependencies.
* @param {InputFileSystem} fs file system
* @param {ContextModuleOptions} options options
* @param {ResolveDependenciesCallback} callback callback function
* @returns {void}
*/
resolveDependencies(fs, options, callback) {
const cmf = this;
const {
resource,
resourceQuery,
resourceFragment,
recursive,
regExp,
include,
exclude,
referencedExports,
category,
typePrefix,
attributes
} = options;
if (!regExp || !resource) return callback(null, []);
/**
* Adds directory checked.
* @param {string} ctx context
* @param {string} directory directory
* @param {Set<string>} visited visited
* @param {ResolveDependenciesCallback} callback callback
*/
const addDirectoryChecked = (ctx, directory, visited, callback) => {
/** @type {NonNullable<InputFileSystem["realpath"]>} */
(fs.realpath)(directory, (err, _realPath) => {
if (err) return callback(err);
const realPath = /** @type {string} */ (_realPath);
if (visited.has(realPath)) return callback(null, []);
/** @type {Set<string> | undefined} */
let recursionStack;
addDirectory(
ctx,
directory,
(_, dir, callback) => {
if (recursionStack === undefined) {
recursionStack = new Set(visited);
recursionStack.add(realPath);
}
addDirectoryChecked(ctx, dir, recursionStack, callback);
},
callback
);
});
};
/**
* Adds the provided ctx to the context module factory.
* @param {string} ctx context
* @param {string} directory directory
* @param {(context: string, subResource: string, callback: () => void) => void} addSubDirectory addSubDirectoryFn
* @param {ResolveDependenciesCallback} callback callback
* @returns {void}
*/
const addDirectory = (ctx, directory, addSubDirectory, callback) => {
fs.readdir(directory, (err, files) => {
if (err) return callback(err);
const processedFiles = cmf.hooks.contextModuleFiles.call(
/** @type {string[]} */ (files).map((file) => file.normalize("NFC"))
);
if (!processedFiles || processedFiles.length === 0) {
return callback(null, []);
}
/** @type {ContextAlternativeRequest[]} */
const fileObjs = [];
asyncLib.map(
processedFiles.filter((p) => p.indexOf(".") !== 0),
(segment, callback) => {
const subResource = join(fs, directory, segment);
if (!exclude || !exclude.test(subResource)) {
fs.stat(subResource, (err, _stat) => {
if (err) {
if (err.code === "ENOENT") {
// ENOENT is ok here because the file may have been deleted between
// the readdir and stat calls.
return callback();
}
return callback(err);
}
const stat = /** @type {IStats} */ (_stat);
if (stat.isDirectory()) {
if (!recursive) return callback();
addSubDirectory(ctx, subResource, callback);
} else if (
stat.isFile() &&
(!include || include.test(subResource))
) {
// Collect for a single batched alternativeRequests call
// per directory below. Calling the hook once per file
// would pay per-call overhead (closure, resolverFactory
// lookup, array allocations) for every file in the
// context — which is the bulk of work on rebuilds.
fileObjs.push({
context: ctx,
request: `.${subResource.slice(ctx.length).replace(/\\/g, "/")}`
});
callback();
} else {
callback();
}
});
} else {
callback();
}
},
(err, result) => {
if (err) return callback(err);
/** @type {ContextElementDependency[]} */
const flattenedResult = [];
if (result) {
for (const item of result) {
if (item) flattenedResult.push(...item);
}
}
if (fileObjs.length === 0) {
return callback(null, flattenedResult);
}
this.hooks.alternativeRequests.callAsync(
fileObjs,
options,
(err, alternatives) => {
if (err) return callback(err);
for (const alt of /** @type {ContextAlternativeRequest[]} */ (
alternatives
)) {
if (!regExp.test(/** @type {string} */ (alt.request))) {
continue;
}
const dep = new ContextElementDependency(
`${alt.request}${resourceQuery}${resourceFragment}`,
alt.request,
typePrefix,
/** @type {string} */
(category),
referencedExports,
alt.context,
attributes
);
dep.optional = true;
flattenedResult.push(dep);
}
callback(null, flattenedResult);
}
);
}
);
});
};
/**
* Adds sub directory.
* @param {string} ctx context
* @param {string} dir dir
* @param {ResolveDependenciesCallback} callback callback
* @returns {void}
*/
const addSubDirectory = (ctx, dir, callback) =>
addDirectory(ctx, dir, addSubDirectory, callback);
/**
* Processes the provided resource.
* @param {string} resource resource
* @param {ResolveDependenciesCallback} callback callback
*/
const visitResource = (resource, callback) => {
if (typeof fs.realpath === "function") {
addDirectoryChecked(
resource,
resource,
/** @type {Set<string>} */
new Set(),
callback
);
} else {
addDirectory(resource, resource, addSubDirectory, callback);
}
};
if (typeof resource === "string") {
visitResource(resource, callback);
} else {
asyncLib.map(resource, visitResource, (err, _result) => {
if (err) return callback(err);
const result = /** @type {ContextElementDependency[][]} */ (_result);
// result dependencies should have unique userRequest
// ordered by resolve result
/** @type {Set<string>} */
const temp = new Set();
/** @type {ContextElementDependency[]} */
const res = [];
for (let i = 0; i < result.length; i++) {
const inner = result[i];
for (const el of inner) {
if (temp.has(el.userRequest)) continue;
res.push(el);
temp.add(el.userRequest);
}
}
callback(null, res);
});
}
}
}
module.exports = ContextModuleFactory;

230
node_modules/webpack/lib/ContextReplacementPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,230 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const { join } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */
/** @typedef {import("./ContextModuleFactory").BeforeContextResolveData} BeforeContextResolveData */
/** @typedef {import("./ContextModuleFactory").AfterContextResolveData} AfterContextResolveData */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {Record<string, string>} NewContentCreateContextMap */
const PLUGIN_NAME = "ContextReplacementPlugin";
class ContextReplacementPlugin {
/**
* Creates an instance of ContextReplacementPlugin.
* @param {RegExp} resourceRegExp A regular expression that determines which files will be selected
* @param {(string | ((context: BeforeContextResolveData | AfterContextResolveData) => void) | RegExp | boolean)=} newContentResource A new resource to replace the match
* @param {(boolean | NewContentCreateContextMap | RegExp)=} newContentRecursive If true, all subdirectories are searched for matches
* @param {RegExp=} newContentRegExp A regular expression that determines which files will be selected
*/
constructor(
resourceRegExp,
newContentResource,
newContentRecursive,
newContentRegExp
) {
this.resourceRegExp = resourceRegExp;
// new webpack.ContextReplacementPlugin(/selector/, (context) => { /* Logic */ });
if (typeof newContentResource === "function") {
this.newContentCallback = newContentResource;
}
// new ContextReplacementPlugin(/selector/, './folder', { './request': './request' });
else if (
typeof newContentResource === "string" &&
typeof newContentRecursive === "object"
) {
this.newContentResource = newContentResource;
/**
* Stores new content create context map.
* @param {InputFileSystem} fs input file system
* @param {(err: null | Error, newContentRecursive: NewContentCreateContextMap) => void} callback callback
*/
this.newContentCreateContextMap = (fs, callback) => {
callback(
null,
/** @type {NewContentCreateContextMap} */ (newContentRecursive)
);
};
}
// new ContextReplacementPlugin(/selector/, './folder', (context) => { /* Logic */ });
else if (
typeof newContentResource === "string" &&
typeof newContentRecursive === "function"
) {
this.newContentResource = newContentResource;
this.newContentCreateContextMap = newContentRecursive;
} else {
// new webpack.ContextReplacementPlugin(/selector/, false, /reg-exp/);
if (typeof newContentResource !== "string") {
newContentRegExp = /** @type {RegExp} */ (newContentRecursive);
newContentRecursive = /** @type {boolean} */ (newContentResource);
newContentResource = undefined;
}
// new webpack.ContextReplacementPlugin(/selector/, /de|fr|hu/);
if (typeof newContentRecursive !== "boolean") {
newContentRegExp = /** @type {RegExp} */ (newContentRecursive);
newContentRecursive = undefined;
}
// new webpack.ContextReplacementPlugin(/selector/, './folder', false, /selector/);
this.newContentResource =
/** @type {string | undefined} */
(newContentResource);
this.newContentRecursive =
/** @type {boolean | undefined} */
(newContentRecursive);
this.newContentRegExp =
/** @type {RegExp | undefined} */
(newContentRegExp);
}
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newContentCallback = this.newContentCallback;
const newContentResource = this.newContentResource;
const newContentRecursive = this.newContentRecursive;
const newContentRegExp = this.newContentRegExp;
const newContentCreateContextMap = this.newContentCreateContextMap;
compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => {
cmf.hooks.beforeResolve.tap(PLUGIN_NAME, (result) => {
if (!result) return;
if (resourceRegExp.test(result.request)) {
if (newContentResource !== undefined) {
result.request = newContentResource;
}
if (newContentRecursive !== undefined) {
result.recursive = newContentRecursive;
}
if (newContentRegExp !== undefined) {
result.regExp = newContentRegExp;
}
if (typeof newContentCallback === "function") {
newContentCallback(result);
} else {
for (const d of result.dependencies) {
if (d.critical) d.critical = false;
}
}
}
return result;
});
cmf.hooks.afterResolve.tap(PLUGIN_NAME, (result) => {
if (!result) return;
const isMatchResourceRegExp = () => {
if (Array.isArray(result.resource)) {
return result.resource.some((item) => resourceRegExp.test(item));
}
return resourceRegExp.test(result.resource);
};
if (isMatchResourceRegExp()) {
if (newContentResource !== undefined) {
if (
newContentResource.startsWith("/") ||
(newContentResource.length > 1 && newContentResource[1] === ":")
) {
result.resource = newContentResource;
} else {
const rootPath =
typeof result.resource === "string"
? result.resource
: /** @type {string} */
(result.resource.find((item) => resourceRegExp.test(item)));
result.resource = join(
/** @type {InputFileSystem} */
(compiler.inputFileSystem),
rootPath,
newContentResource
);
}
}
if (newContentRecursive !== undefined) {
result.recursive = newContentRecursive;
}
if (newContentRegExp !== undefined) {
result.regExp = newContentRegExp;
}
if (typeof newContentCreateContextMap === "function") {
result.resolveDependencies =
createResolveDependenciesFromContextMap(
newContentCreateContextMap
);
}
if (typeof newContentCallback === "function") {
const origResource = result.resource;
newContentCallback(result);
if (result.resource !== origResource) {
const newResource = Array.isArray(result.resource)
? result.resource
: [result.resource];
for (let i = 0; i < newResource.length; i++) {
if (
!newResource[i].startsWith("/") &&
(newResource[i].length <= 1 || newResource[i][1] !== ":")
) {
// When the function changed it to an relative path
newResource[i] = join(
/** @type {InputFileSystem} */
(compiler.inputFileSystem),
origResource[i],
newResource[i]
);
}
}
result.resource = newResource;
}
} else {
for (const d of result.dependencies) {
if (d.critical) d.critical = false;
}
}
}
return result;
});
});
}
}
/**
* Creates a resolve dependencies from context map.
* @param {(fs: InputFileSystem, callback: (err: null | Error, map: NewContentCreateContextMap) => void) => void} createContextMap create context map function
* @returns {(fs: InputFileSystem, options: ContextModuleOptions, callback: (err: null | Error, dependencies?: ContextElementDependency[]) => void) => void} resolve resolve dependencies from context map function
*/
const createResolveDependenciesFromContextMap =
(createContextMap) => (fs, options, callback) => {
createContextMap(fs, (err, map) => {
if (err) return callback(err);
const dependencies = Object.keys(map).map(
(key) =>
new ContextElementDependency(
map[key] + options.resourceQuery + options.resourceFragment,
key,
options.typePrefix,
/** @type {string} */
(options.category),
options.referencedExports
)
);
callback(null, dependencies);
});
};
module.exports = ContextReplacementPlugin;

891
node_modules/webpack/lib/DefinePlugin.js generated vendored Normal file
View File

@@ -0,0 +1,891 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncWaterfallHook } = require("tapable");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const ConstDependency = require("./dependencies/ConstDependency");
const WebpackError = require("./errors/WebpackError");
const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
const { VariableInfo } = require("./javascript/JavascriptParser");
const {
evaluateToString,
toConstantDependency
} = require("./javascript/JavascriptParserHelpers");
const createHash = require("./util/createHash");
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").ValueCacheVersion} ValueCacheVersion */
/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @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 */
/**
* Defines the runtime value options type used by this module.
* @typedef {object} RuntimeValueOptions
* @property {string[]=} fileDependencies
* @property {string[]=} contextDependencies
* @property {string[]=} missingDependencies
* @property {string[]=} buildDependencies
* @property {string | (() => string)=} version
*/
/** @typedef {(value: { module: NormalModule, key: string, readonly version: ValueCacheVersion }) => CodeValuePrimitive} GeneratorFn */
class RuntimeValue {
/**
* Creates an instance of RuntimeValue.
* @param {GeneratorFn} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
*/
constructor(fn, options) {
/** @type {GeneratorFn} */
this.fn = fn;
if (Array.isArray(options)) {
options = {
fileDependencies: options
};
}
/** @type {true | RuntimeValueOptions} */
this.options = options || {};
}
get fileDependencies() {
return this.options === true ? true : this.options.fileDependencies;
}
/**
* Returns code.
* @param {JavascriptParser} parser the parser
* @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @returns {CodeValuePrimitive} code
*/
exec(parser, valueCacheVersions, key) {
const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo);
if (this.options === true) {
buildInfo.cacheable = false;
} else {
if (this.options.fileDependencies) {
for (const dep of this.options.fileDependencies) {
/** @type {NonNullable<BuildInfo["fileDependencies"]>} */
(buildInfo.fileDependencies).add(dep);
}
}
if (this.options.contextDependencies) {
for (const dep of this.options.contextDependencies) {
/** @type {NonNullable<BuildInfo["contextDependencies"]>} */
(buildInfo.contextDependencies).add(dep);
}
}
if (this.options.missingDependencies) {
for (const dep of this.options.missingDependencies) {
/** @type {NonNullable<BuildInfo["missingDependencies"]>} */
(buildInfo.missingDependencies).add(dep);
}
}
if (this.options.buildDependencies) {
for (const dep of this.options.buildDependencies) {
/** @type {NonNullable<BuildInfo["buildDependencies"]>} */
(buildInfo.buildDependencies).add(dep);
}
}
}
return this.fn({
module: parser.state.module,
key,
get version() {
return /** @type {ValueCacheVersion} */ (
valueCacheVersions.get(VALUE_DEP_PREFIX + key)
);
}
});
}
getCacheVersion() {
return this.options === true
? undefined
: (typeof this.options.version === "function"
? this.options.version()
: this.options.version) || "unset";
}
}
/**
* Returns used keys.
* @param {DestructuringAssignmentProperties | undefined} properties properties
* @returns {Set<string> | undefined} used keys
*/
function getObjKeys(properties) {
if (!properties) return;
return new Set([...properties].map((p) => p.id));
}
/** @typedef {Set<string> | null} ObjKeys */
/** @typedef {boolean | undefined | null} AsiSafe */
/**
* Returns code converted to string that evaluates.
* @param {EXPECTED_ANY[] | { [k: string]: EXPECTED_ANY }} obj obj
* @param {JavascriptParser} parser Parser
* @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Logger} logger the logger object
* @param {AsiSafe=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {ObjKeys=} objKeys used keys
* @returns {string} code converted to string that evaluates
*/
const stringifyObj = (
obj,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe,
objKeys
) => {
/** @type {string} */
let code;
const arr = Array.isArray(obj);
if (arr) {
code = `[${obj
.map((code) =>
toCode(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)
)
.join(",")}]`;
} else {
let keys = Object.keys(obj);
if (objKeys) {
keys = objKeys.size === 0 ? [] : keys.filter((k) => objKeys.has(k));
}
code = `{${keys
.map((key) => {
const code = obj[key];
return `${key === "__proto__" ? '["__proto__"]' : JSON.stringify(key)}:${toCode(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)}`;
})
.join(",")}}`;
}
switch (asiSafe) {
case null:
return code;
case true:
return arr ? code : `(${code})`;
case false:
return arr ? `;${code}` : `;(${code})`;
default:
return `/*#__PURE__*/Object(${code})`;
}
};
/**
* Convert code to a string that evaluates
* @param {CodeValue} code Code to evaluate
* @param {JavascriptParser} parser Parser
* @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Logger} logger the logger object
* @param {boolean | undefined | null=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {ObjKeys=} objKeys used keys
* @returns {string} code converted to string that evaluates
*/
const toCode = (
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe,
objKeys
) => {
const transformToCode = () => {
if (code === null) {
return "null";
}
if (code === undefined) {
return "undefined";
}
if (Object.is(code, -0)) {
return "-0";
}
if (code instanceof RuntimeValue) {
return toCode(
code.exec(parser, valueCacheVersions, key),
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe
);
}
if (code instanceof RegExp && code.toString) {
return code.toString();
}
if (typeof code === "function" && code.toString) {
return `(${code.toString()})`;
}
if (typeof code === "object") {
return stringifyObj(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe,
objKeys
);
}
if (typeof code === "bigint") {
return runtimeTemplate.supportsBigIntLiteral()
? `${code}n`
: `BigInt("${code}")`;
}
return `${code}`;
};
const strCode = transformToCode();
logger.debug(`Replaced "${key}" with "${strCode}"`);
return strCode;
};
/**
* Returns result.
* @param {CodeValue} code code
* @returns {string | undefined} result
*/
const toCacheVersion = (code) => {
if (code === null) {
return "null";
}
if (code === undefined) {
return "undefined";
}
if (Object.is(code, -0)) {
return "-0";
}
if (code instanceof RuntimeValue) {
return code.getCacheVersion();
}
if (code instanceof RegExp && code.toString) {
return code.toString();
}
if (typeof code === "function" && code.toString) {
return `(${code.toString()})`;
}
if (typeof code === "object") {
const items = Object.keys(code).map((key) => ({
key,
value: toCacheVersion(
/** @type {Record<string, CodeValue>} */
(code)[key]
)
}));
if (items.some(({ value }) => value === undefined)) return;
return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
}
if (typeof code === "bigint") {
return `${code}n`;
}
return `${code}`;
};
const PLUGIN_NAME = "DefinePlugin";
const VALUE_DEP_PREFIX = `webpack/${PLUGIN_NAME} `;
const VALUE_DEP_MAIN = `webpack/${PLUGIN_NAME}_hash`;
const TYPEOF_OPERATOR_REGEXP = /^typeof\s+/;
const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp(
`${RuntimeGlobals.require}\\s*(!?\\.)`
);
const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require);
/**
* Defines the define plugin hooks type used by this module.
* @typedef {object} DefinePluginHooks
* @property {SyncWaterfallHook<[Record<string, CodeValue>]>} definitions
*/
/** @typedef {Record<string, CodeValue>} Definitions */
/** @type {WeakMap<Compilation, DefinePluginHooks>} */
const compilationHooksMap = new WeakMap();
class DefinePlugin {
/**
* Returns the attached hooks.
* @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 {Definitions} definitions A map of global object definitions
*/
constructor(definitions) {
/** @type {Definitions} */
this.definitions = definitions;
}
/**
* Returns runtime value.
* @param {GeneratorFn} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
* @returns {RuntimeValue} runtime value
*/
static runtimeValue(fn, options) {
return new RuntimeValue(fn, options);
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
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>>}
*/
const finalByNestedKey = new Map();
/**
* @type {Map<string, Set<string>>}
*/
const nestedByFinalKey = new Map();
const logger = compilation.getLogger("webpack.DefinePlugin");
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
const { runtimeTemplate } = compilation;
const mainHash = createHash(compilation.outputOptions.hashFunction);
mainHash.update(
/** @type {string} */
(compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
);
/**
* Handles the hook callback for this code path.
* @param {JavascriptParser} parser Parser
* @returns {void}
*/
const handler = (parser) => {
/** @type {Set<string>} */
const hooked = new Set();
const mainValue =
/** @type {ValueCacheVersion} */
(compilation.valueCacheVersions.get(VALUE_DEP_MAIN));
parser.hooks.program.tap(PLUGIN_NAME, () => {
const buildInfo = /** @type {BuildInfo} */ (
parser.state.module.buildInfo
);
if (!buildInfo.valueDependencies) {
buildInfo.valueDependencies = new Map();
}
buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
});
/**
* Adds value dependency.
* @param {string} key key
*/
const addValueDependency = (key) => {
const buildInfo =
/** @type {BuildInfo} */
(parser.state.module.buildInfo);
/** @type {NonNullable<BuildInfo["valueDependencies"]>} */
(buildInfo.valueDependencies).set(
VALUE_DEP_PREFIX + key,
/** @type {ValueCacheVersion} */
(compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key))
);
};
/**
* With value dependency.
* @template T
* @param {string} key key
* @param {(expression: Expression) => T} fn fn
* @returns {(expression: Expression) => T} result
*/
const withValueDependency =
(key, fn) =>
(...args) => {
addValueDependency(key);
return fn(...args);
};
/**
* Processes the provided definition.
* @param {Definitions} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
const walkDefinitions = (definitions, prefix) => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
if (
code &&
typeof code === "object" &&
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
walkDefinitions(
/** @type {Definitions} */ (code),
`${prefix + key}.`
);
applyObjectDefine(prefix + key, code);
continue;
}
applyDefineKey(prefix, key);
applyDefine(prefix + key, code);
}
};
/**
* Processes the provided prefix.
* @param {string} prefix Prefix
* @param {string} key Key
* @returns {void}
*/
const applyDefineKey = (prefix, key) => {
const splittedKey = key.split(".");
const firstKey = splittedKey[0];
for (const [i, _] of splittedKey.slice(1).entries()) {
const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
addValueDependency(key);
if (
parser.scope.definitions.get(firstKey) instanceof VariableInfo
) {
return false;
}
return true;
});
}
if (prefix === "") {
const final = splittedKey[splittedKey.length - 1];
const nestedSet = nestedByFinalKey.get(final);
if (!nestedSet || nestedSet.size <= 0) return;
for (const nested of /** @type {Set<string>} */ (nestedSet)) {
if (nested && !hooked.has(nested)) {
// only detect the same nested key once
hooked.add(nested);
parser.hooks.collectDestructuringAssignmentProperties.tap(
PLUGIN_NAME,
(expr) => {
const nameInfo = parser.getNameForExpression(expr);
if (nameInfo && nameInfo.name === nested) return true;
}
);
parser.hooks.expression.for(nested).tap(
{
name: PLUGIN_NAME,
// why 100? Ensures it runs after object define
stage: 100
},
(expr) => {
const destructed =
parser.destructuringAssignmentPropertiesFor(expr);
if (destructed === undefined) {
return;
}
/** @type {Definitions} */
const obj = Object.create(null);
const finalSet = finalByNestedKey.get(nested);
for (const { id } of destructed) {
const fullKey = `${nested}.${id}`;
if (
!finalSet ||
!finalSet.has(id) ||
!definitions[fullKey]
) {
return;
}
obj[id] = definitions[fullKey];
}
let strCode = stringifyObj(
obj,
parser,
compilation.valueCacheVersions,
key,
runtimeTemplate,
logger,
!parser.isAsiPosition(
/** @type {Range} */ (expr.range)[0]
),
getObjKeys(destructed)
);
if (parser.scope.inShorthand) {
strCode = `${parser.scope.inShorthand}:${strCode}`;
}
return toConstantDependency(parser, strCode)(expr);
}
);
}
}
}
};
/**
* Processes the provided key.
* @param {string} key Key
* @param {CodeValue} code Code
* @returns {void}
*/
const applyDefine = (key, code) => {
const originalKey = key;
const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
let recurse = false;
let recurseTypeof = false;
if (!isTypeof) {
parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
addValueDependency(originalKey);
return true;
});
parser.hooks.evaluateIdentifier
.for(key)
.tap(PLUGIN_NAME, (expr) => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "a": "b",
* "b": "a"
* });
*/
if (recurse) return;
addValueDependency(originalKey);
recurse = true;
const res = parser.evaluate(
toCode(
code,
parser,
compilation.valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)
);
recurse = false;
res.setRange(/** @type {Range} */ (expr.range));
return res;
});
parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
addValueDependency(originalKey);
let strCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
logger,
!parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
null
);
if (parser.scope.inShorthand) {
strCode = `${parser.scope.inShorthand}:${strCode}`;
}
if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
} else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
}
return toConstantDependency(parser, strCode)(expr);
});
}
parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, (expr) => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "typeof a": "typeof b",
* "typeof b": "typeof a"
* });
*/
if (recurseTypeof) return;
recurseTypeof = true;
addValueDependency(originalKey);
const codeCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
logger,
null
);
const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
const res = parser.evaluate(typeofCode);
recurseTypeof = false;
res.setRange(/** @type {Range} */ (expr.range));
return res;
});
parser.hooks.typeof.for(key).tap(PLUGIN_NAME, (expr) => {
addValueDependency(originalKey);
const codeCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
logger,
null
);
const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
const res = parser.evaluate(typeofCode);
if (!res.isString()) return;
return toConstantDependency(
parser,
JSON.stringify(res.string)
).bind(parser)(expr);
});
};
/**
* Processes the provided key.
* @param {string} key Key
* @param {object} obj Object
* @returns {void}
*/
const applyObjectDefine = (key, obj) => {
parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
addValueDependency(key);
return true;
});
parser.hooks.evaluateIdentifier
.for(key)
.tap(PLUGIN_NAME, (expr) => {
addValueDependency(key);
return new BasicEvaluatedExpression()
.setTruthy()
.setSideEffects(false)
.setRange(/** @type {Range} */ (expr.range));
});
parser.hooks.evaluateTypeof
.for(key)
.tap(
PLUGIN_NAME,
withValueDependency(key, evaluateToString("object"))
);
parser.hooks.collectDestructuringAssignmentProperties.tap(
PLUGIN_NAME,
(expr) => {
const nameInfo = parser.getNameForExpression(expr);
if (nameInfo && nameInfo.name === key) return true;
}
);
parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
addValueDependency(key);
let strCode = stringifyObj(
obj,
parser,
compilation.valueCacheVersions,
key,
runtimeTemplate,
logger,
!parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
getObjKeys(parser.destructuringAssignmentPropertiesFor(expr))
);
if (parser.scope.inShorthand) {
strCode = `${parser.scope.inShorthand}:${strCode}`;
}
if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
} else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
}
return toConstantDependency(parser, strCode)(expr);
});
parser.hooks.typeof
.for(key)
.tap(
PLUGIN_NAME,
withValueDependency(
key,
toConstantDependency(parser, JSON.stringify("object"))
)
);
};
walkDefinitions(definitions, "");
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
/**
* Processes the provided definition.
* @param {Definitions} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
const walkDefinitionsForValues = (definitions, prefix) => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
const version = /** @type {string} */ (toCacheVersion(code));
const name = VALUE_DEP_PREFIX + prefix + key;
mainHash.update(`|${prefix}${key}`);
const oldVersion = compilation.valueCacheVersions.get(name);
if (oldVersion === undefined) {
compilation.valueCacheVersions.set(name, version);
} else if (oldVersion !== version) {
const warning = new WebpackError(
`${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
);
warning.details = `'${oldVersion}' !== '${version}'`;
warning.hideStack = true;
compilation.warnings.push(warning);
}
if (
code &&
typeof code === "object" &&
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
walkDefinitionsForValues(
/** @type {Definitions} */ (code),
`${prefix + key}.`
);
}
}
};
/**
* Walk definitions for keys.
* @param {Definitions} definitions Definitions map
* @returns {void}
*/
const walkDefinitionsForKeys = (definitions) => {
/**
* Adds the provided map to the define plugin.
* @param {Map<string, Set<string>>} map Map
* @param {string} key key
* @param {string} value v
* @returns {void}
*/
const addToMap = (map, key, value) => {
if (map.has(key)) {
/** @type {Set<string>} */
(map.get(key)).add(value);
} else {
map.set(key, new Set([value]));
}
};
for (const key of Object.keys(definitions)) {
const code = definitions[key];
if (
!code ||
typeof code === "object" ||
TYPEOF_OPERATOR_REGEXP.test(key)
) {
continue;
}
const idx = key.lastIndexOf(".");
if (idx <= 0 || idx >= key.length - 1) {
continue;
}
const nested = key.slice(0, idx);
const final = key.slice(idx + 1);
addToMap(finalByNestedKey, nested, final);
addToMap(nestedByFinalKey, final, nested);
}
};
walkDefinitionsForKeys(definitions);
walkDefinitionsForValues(definitions, "");
compilation.valueCacheVersions.set(
VALUE_DEP_MAIN,
mainHash.digest("hex").slice(0, 8)
);
}
);
}
}
module.exports = DefinePlugin;

125
node_modules/webpack/lib/DependenciesBlock.js generated vendored Normal file
View File

@@ -0,0 +1,125 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */
/**
* DependenciesBlock is the base class for all Module classes in webpack. It describes a
* "block" of dependencies which are pointers to other DependenciesBlock instances. For example
* when a Module has a CommonJs require statement, the DependencyBlock for the CommonJs module
* would be added as a dependency to the Module. DependenciesBlock is inherited by two types of classes:
* Module subclasses and AsyncDependenciesBlock subclasses. The only difference between the two is that
* AsyncDependenciesBlock subclasses are used for code-splitting (async boundary) and Module subclasses are not.
*/
class DependenciesBlock {
constructor() {
/** @type {Dependency[]} */
this.dependencies = [];
/** @type {AsyncDependenciesBlock[]} */
this.blocks = [];
/** @type {DependenciesBlock | undefined} */
this.parent = undefined;
}
getRootBlock() {
/** @type {DependenciesBlock} */
let current = this;
while (current.parent) current = current.parent;
return current;
}
/**
* Adds a DependencyBlock to DependencyBlock relationship.
* This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting)
* @param {AsyncDependenciesBlock} block block being added
* @returns {void}
*/
addBlock(block) {
this.blocks.push(block);
block.parent = this;
}
/**
* Adds the provided dependency to the dependencies block.
* @param {Dependency} dependency dependency being tied to block.
* This is an "edge" pointing to another "node" on module graph.
* @returns {void}
*/
addDependency(dependency) {
this.dependencies.push(dependency);
}
/**
* Removes dependency.
* @param {Dependency} dependency dependency being removed
* @returns {void}
*/
removeDependency(dependency) {
const idx = this.dependencies.indexOf(dependency);
if (idx >= 0) {
this.dependencies.splice(idx, 1);
}
}
/**
* Clear dependencies and blocks.
* @returns {void}
*/
clearDependenciesAndBlocks() {
this.dependencies.length = 0;
this.blocks.length = 0;
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
for (const dep of this.dependencies) {
dep.updateHash(hash, context);
}
for (const block of this.blocks) {
block.updateHash(hash, context);
}
}
/**
* Serializes this instance into the provided serializer context.
* @param {ObjectSerializerContext} context context
*/
serialize({ write }) {
write(this.dependencies);
write(this.blocks);
}
/**
* Restores this instance from the provided deserializer context.
* @param {ObjectDeserializerContext} context context
*/
deserialize({ read }) {
this.dependencies = read();
this.blocks = read();
for (const block of this.blocks) {
block.parent = this;
}
}
}
makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock");
module.exports = DependenciesBlock;

434
node_modules/webpack/lib/Dependency.js generated vendored Normal file
View File

@@ -0,0 +1,434 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const memoize = require("./util/memoize");
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./errors/WebpackError")} WebpackError */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */
/**
* Defines the update hash context type used by this module.
* @typedef {object} UpdateHashContext
* @property {ChunkGraph} chunkGraph
* @property {RuntimeSpec} runtime
* @property {RuntimeTemplate=} runtimeTemplate
*/
/**
* Defines the source position type used by this module.
* @typedef {object} SourcePosition
* @property {number} line
* @property {number=} column
*/
/**
* Defines the real dependency location type used by this module.
* @typedef {object} RealDependencyLocation
* @property {SourcePosition} start
* @property {SourcePosition=} end
* @property {number=} index
*/
/**
* Defines the synthetic dependency location type used by this module.
* @typedef {object} SyntheticDependencyLocation
* @property {string} name
* @property {number=} index
*/
/** @typedef {SyntheticDependencyLocation | RealDependencyLocation} DependencyLocation */
/** @typedef {string} ExportInfoName */
/**
* Defines the export spec type used by this module.
* @typedef {object} ExportSpec
* @property {ExportInfoName} name the name of the export
* @property {boolean=} canMangle can the export be renamed (defaults to true)
* @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts
* @property {(string | ExportSpec)[]=} exports nested exports
* @property {ModuleGraphConnection=} from when reexported: from which module
* @property {string[] | null=} export when reexported: from which export
* @property {number=} priority when reexported: with which priority
* @property {boolean=} hidden export is not visible, because another export blends over it
*/
/** @typedef {Set<string>} ExportsSpecExcludeExports */
/**
* Defines the exports spec type used by this module.
* @typedef {object} ExportsSpec
* @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports
* @property {ExportsSpecExcludeExports=} excludeExports when exports = true, list of unaffected exports
* @property {(Set<string> | null)=} hideExports list of maybe prior exposed, but now hidden exports
* @property {ModuleGraphConnection=} from when reexported: from which module
* @property {number=} priority when reexported: with which priority
* @property {boolean=} canMangle can the export be renamed (defaults to true)
* @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts
* @property {Module[]=} dependencies module on which the result depends on
*/
/**
* Defines the referenced export type used by this module.
* @typedef {object} ReferencedExport
* @property {string[]} name name of the referenced export
* @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true
*/
/** @typedef {string[][]} RawReferencedExports */
/** @typedef {(string[] | ReferencedExport)[]} ReferencedExports */
/** @typedef {(moduleGraphConnection: ModuleGraphConnection, runtime: RuntimeSpec) => ConnectionState} GetConditionFn */
const TRANSITIVE = /** @type {symbol} */ (Symbol("transitive"));
const getIgnoredModule = memoize(() => {
const RawModule = require("./RawModule");
const module = new RawModule("/* (ignored) */", "ignored", "(ignored)");
module.factoryMeta = { sideEffectFree: true };
return module;
});
class Dependency {
constructor() {
/** @type {Module | undefined} */
this._parentModule = undefined;
/** @type {DependenciesBlock | undefined} */
this._parentDependenciesBlock = undefined;
/** @type {number} */
this._parentDependenciesBlockIndex = -1;
// TODO check if this can be moved into ModuleDependency
/** @type {boolean} */
this.weak = false;
// TODO check if this can be moved into ModuleDependency
/** @type {boolean | undefined} */
this.optional = false;
this._locSL = 0;
this._locSC = 0;
this._locEL = 0;
this._locEC = 0;
/** @type {undefined | number} */
this._locI = undefined;
/** @type {undefined | string} */
this._locN = undefined;
/** @type {undefined | DependencyLocation} */
this._loc = undefined;
}
/**
* Returns a display name for the type of dependency.
* @returns {string} a display name for the type of dependency
*/
get type() {
return "unknown";
}
/**
* Returns a dependency category, typical categories are "commonjs", "amd", "esm".
* @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm"
*/
get category() {
return "unknown";
}
/**
* Returns location.
* @returns {DependencyLocation} location
*/
get loc() {
if (this._loc !== undefined) return this._loc;
/** @type {SyntheticDependencyLocation & RealDependencyLocation} */
const loc = {};
if (this._locSL > 0) {
loc.start = { line: this._locSL, column: this._locSC };
}
if (this._locEL > 0) {
loc.end = { line: this._locEL, column: this._locEC };
}
if (this._locN !== undefined) {
loc.name = this._locN;
}
if (this._locI !== undefined) {
loc.index = this._locI;
}
return (this._loc = loc);
}
set loc(loc) {
if ("start" in loc && typeof loc.start === "object") {
this._locSL = loc.start.line || 0;
this._locSC = loc.start.column || 0;
} else {
this._locSL = 0;
this._locSC = 0;
}
if ("end" in loc && typeof loc.end === "object") {
this._locEL = loc.end.line || 0;
this._locEC = loc.end.column || 0;
} else {
this._locEL = 0;
this._locEC = 0;
}
this._locI = "index" in loc ? loc.index : undefined;
this._locN = "name" in loc ? loc.name : undefined;
this._loc = loc;
}
/**
* Updates loc using the provided start line.
* @param {number} startLine start line
* @param {number} startColumn start column
* @param {number} endLine end line
* @param {number} endColumn end column
*/
setLoc(startLine, startColumn, endLine, endColumn) {
this._locSL = startLine;
this._locSC = startColumn;
this._locEL = endLine;
this._locEC = endColumn;
this._locI = undefined;
this._locN = undefined;
this._loc = undefined;
}
/**
* Returns a request context.
* @returns {string | undefined} a request context
*/
getContext() {
return undefined;
}
/**
* Returns an identifier to merge equal requests.
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier() {
return null;
}
/**
* Could affect referencing module.
* @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module
*/
couldAffectReferencingModule() {
return TRANSITIVE;
}
/**
* Returns the referenced module and export
* @deprecated
* @param {ModuleGraph} moduleGraph module graph
* @returns {never} throws error
*/
getReference(moduleGraph) {
throw new Error(
"Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule, ModuleGraph.getConnection(), and ModuleGraphConnection.getActiveState(runtime)"
);
}
/**
* Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {ReferencedExports} referenced exports
*/
getReferencedExports(moduleGraph, runtime) {
return Dependency.EXPORTS_OBJECT_REFERENCED;
}
/**
* Returns function to determine if the connection is active.
* @param {ModuleGraph} moduleGraph module graph
* @returns {null | false | GetConditionFn} function to determine if the connection is active
*/
getCondition(moduleGraph) {
return null;
}
/**
* Returns the exported names
* @param {ModuleGraph} moduleGraph module graph
* @returns {ExportsSpec | undefined} export names
*/
getExports(moduleGraph) {
return undefined;
}
/**
* Returns warnings.
* @param {ModuleGraph} moduleGraph module graph
* @returns {WebpackError[] | null | undefined} warnings
*/
getWarnings(moduleGraph) {
return null;
}
/**
* Returns errors.
* @param {ModuleGraph} moduleGraph module graph
* @returns {WebpackError[] | null | undefined} errors
*/
getErrors(moduleGraph) {
return null;
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash hash to be updated
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {}
/**
* implement this method to allow the occurrence order plugin to count correctly
* @returns {number} count how often the id is used in this dependency
*/
getNumberOfIdOccurrences() {
return 1;
}
/**
* Gets module evaluation side effects state.
* @param {ModuleGraph} moduleGraph the module graph
* @returns {ConnectionState} how this dependency connects the module to referencing modules
*/
getModuleEvaluationSideEffectsState(moduleGraph) {
return true;
}
/**
* Creates an ignored module.
* @param {string} context context directory
* @returns {Module} ignored module
*/
createIgnoredModule(context) {
return getIgnoredModule();
}
/**
* Returns true if this dependency can be concatenated
* @returns {boolean} true if this dependency can be concatenated
*/
canConcatenate() {
return false;
}
/**
* Serializes this instance into the provided serializer context.
* @param {ObjectSerializerContext} context context
*/
serialize({ write }) {
write(this.weak);
write(this.optional);
write(this._locSL);
write(this._locSC);
write(this._locEL);
write(this._locEC);
write(this._locI);
write(this._locN);
}
/**
* Restores this instance from the provided deserializer context.
* @param {ObjectDeserializerContext} context context
*/
deserialize({ read }) {
this.weak = read();
this.optional = read();
this._locSL = read();
this._locSC = read();
this._locEL = read();
this._locEC = read();
this._locI = read();
this._locN = read();
}
}
/** @type {RawReferencedExports} */
Dependency.NO_EXPORTS_REFERENCED = [];
/** @type {RawReferencedExports} */
Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
// TODO remove in webpack 6
Object.defineProperty(Dependency.prototype, "module", {
/**
* Returns throws.
* @deprecated
* @returns {EXPECTED_ANY} throws
*/
get() {
throw new Error(
"module property was removed from Dependency (use compilation.moduleGraph.getModule(dependency) instead)"
);
},
/**
* Updates module.
* @deprecated
* @returns {never} throws
*/
set() {
throw new Error(
"module property was removed from Dependency (use compilation.moduleGraph.updateModule(dependency, module) instead)"
);
}
});
/**
* Returns true if the dependency is a low priority dependency.
* @param {Dependency} dependency dep
* @returns {boolean} true if the dependency is a low priority dependency
*/
Dependency.isLowPriorityDependency = (dependency) =>
/** @type {ModuleDependency} */ (dependency).sourceOrder === Infinity;
// TODO in webpack 6, call canConcatenate() directly on the dependency instance instead of using this static method.
/**
* Returns true if the dependency can be concatenated (scope hoisting).
* @param {Dependency} dependency dep
* @returns {boolean} true if this dependency supports concatenation
*/
Dependency.canConcatenate = (dependency) => {
if (typeof dependency.canConcatenate === "function") {
return dependency.canConcatenate();
}
return false;
};
// TODO remove in webpack 6
Object.defineProperty(Dependency.prototype, "disconnect", {
/**
* Returns throws.
* @deprecated
* @returns {EXPECTED_ANY} throws
*/
get() {
throw new Error(
"disconnect was removed from Dependency (Dependency no longer carries graph specific information)"
);
}
});
Dependency.TRANSITIVE = TRANSITIVE;
module.exports = Dependency;

77
node_modules/webpack/lib/DependencyTemplate.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./ConcatenationScope")} ConcatenationScope */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/**
* Defines the init fragment type used by this module.
* @template T
* @typedef {import("./InitFragment")<T>} InitFragment
*/
/**
* Defines the dependency template context type used by this module.
* @typedef {object} DependencyTemplateContext
* @property {RuntimeTemplate} runtimeTemplate the runtime template
* @property {DependencyTemplates} dependencyTemplates the dependency templates
* @property {ModuleGraph} moduleGraph the module graph
* @property {ChunkGraph} chunkGraph the chunk graph
* @property {RuntimeRequirements} runtimeRequirements the requirements for runtime
* @property {Module} module current module
* @property {RuntimeSpec} runtime current runtimes, for which code is generated
* @property {InitFragment<GenerateContext>[]} initFragments mutable array of init fragments for the current module
* @property {ConcatenationScope=} concatenationScope when in a concatenated module, information about other concatenated modules
* @property {CodeGenerationResults} codeGenerationResults the code generation results
* @property {InitFragment<GenerateContext>[]} chunkInitFragments chunkInitFragments
*/
/**
* Defines the css dependency template context extras type used by this module.
* @typedef {object} CssDependencyTemplateContextExtras
* @property {CssData} cssData the css exports data
* @property {string} type the css exports data
*/
/**
* Defines the css data type used by this module.
* @typedef {object} CssData
* @property {boolean} esModule whether export __esModule
* @property {Map<string, string>} exports the css exports
* @property {Map<string, { line: number, column: number }>=} exportLocs source position (line is 1-based, column is 0-based) of each export's defining identifier in the original CSS, used to emit fine-grained JS-to-CSS source mappings
*/
/** @typedef {DependencyTemplateContext & CssDependencyTemplateContextExtras} CssDependencyTemplateContext */
class DependencyTemplate {
/* istanbul ignore next */
/**
* Applies the plugin by registering its hooks on the compiler.
* @abstract
* @param {Dependency} dependency the dependency for which the template should be applied
* @param {ReplaceSource} source the current replace source which can be modified
* @param {DependencyTemplateContext} templateContext the context object
* @returns {void}
*/
apply(dependency, source, templateContext) {
const AbstractMethodError = require("./errors/AbstractMethodError");
throw new AbstractMethodError();
}
}
module.exports = DependencyTemplate;

71
node_modules/webpack/lib/DependencyTemplates.js generated vendored Normal file
View File

@@ -0,0 +1,71 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { DEFAULTS } = require("./config/defaults");
const createHash = require("./util/createHash");
/** @typedef {import("./Compilation").DependencyConstructor} DependencyConstructor */
/** @typedef {import("./DependencyTemplate")} DependencyTemplate */
/** @typedef {import("./util/Hash").HashFunction} HashFunction */
class DependencyTemplates {
/**
* Creates an instance of DependencyTemplates.
* @param {HashFunction} hashFunction the hash function to use
*/
constructor(hashFunction = DEFAULTS.HASH_FUNCTION) {
/** @type {Map<DependencyConstructor, DependencyTemplate>} */
this._map = new Map();
/** @type {string} */
this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0";
/** @type {HashFunction} */
this._hashFunction = hashFunction;
}
/**
* Returns template for this dependency.
* @param {DependencyConstructor} dependency Constructor of Dependency
* @returns {DependencyTemplate | undefined} template for this dependency
*/
get(dependency) {
return this._map.get(dependency);
}
/**
* Updates value using the provided dependency.
* @param {DependencyConstructor} dependency Constructor of Dependency
* @param {DependencyTemplate} dependencyTemplate template for this dependency
* @returns {void}
*/
set(dependency, dependencyTemplate) {
this._map.set(dependency, dependencyTemplate);
}
/**
* Updates the hash with the data contributed by this instance.
* @param {string} part additional hash contributor
* @returns {void}
*/
updateHash(part) {
const hash = createHash(this._hashFunction);
hash.update(`${this._hash}${part}`);
this._hash = hash.digest("hex");
}
getHash() {
return this._hash;
}
clone() {
const newInstance = new DependencyTemplates(this._hashFunction);
newInstance._map = new Map(this._map);
newInstance._hash = this._hash;
return newInstance;
}
}
module.exports = DependencyTemplates;

473
node_modules/webpack/lib/DotenvPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,473 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Natsu @xiaoxiaojx
*/
"use strict";
const FileSystemInfo = require("./FileSystemInfo");
const { join } = require("./util/fs");
/** @typedef {import("../declarations/WebpackOptions").DotenvPluginOptions} DotenvPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */
/** @typedef {Exclude<DotenvPluginOptions["prefix"], string | undefined>} Prefix */
/** @typedef {Record<string, string>} Env */
const DEFAULT_TEMPLATE = [
".env",
".env.local",
".env.[mode]",
".env.[mode].local"
];
// Regex for parsing .env files
// ported from https://github.com/motdotla/dotenv/blob/master/lib/main.js#L49
const LINE =
/^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
const PLUGIN_NAME = "DotenvPlugin";
/**
* Parse .env file content
* ported from https://github.com/motdotla/dotenv/blob/master/lib/main.js#L49
* @param {string | Buffer} src the source content to parse
* @returns {Env} parsed environment variables object
*/
function parse(src) {
const obj = /** @type {Env} */ (Object.create(null));
// Convert buffer to string
let lines = src.toString();
// Convert line breaks to same format
lines = lines.replace(/\r\n?/g, "\n");
/** @type {null | RegExpExecArray} */
let match;
while ((match = LINE.exec(lines)) !== null) {
const key = match[1];
// Default undefined or null to empty string
let value = match[2] || "";
// Remove whitespace
value = value.trim();
// Check if double quoted
const maybeQuote = value[0];
// Remove surrounding quotes
value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
// Expand newlines if double quoted
if (maybeQuote === '"') {
value = value.replace(/\\n/g, "\n");
value = value.replace(/\\r/g, "\r");
}
// Add to object
obj[key] = value;
}
return obj;
}
/**
* Resolve escape sequences
* ported from https://github.com/motdotla/dotenv-expand
* @param {string} value value to resolve
* @returns {string} resolved value
*/
function _resolveEscapeSequences(value) {
return value.replace(/\\\$/g, "$");
}
/**
* Expand environment variable value
* ported from https://github.com/motdotla/dotenv-expand
* @param {string} value value to expand
* @param {Record<string, string | undefined>} processEnv process.env object
* @param {Env} runningParsed running parsed object
* @returns {string} expanded value
*/
function expandValue(value, processEnv, runningParsed) {
const env = { ...runningParsed, ...processEnv }; // process.env wins
const regex = /(?<!\\)\$\{([^{}]+)\}|(?<!\\)\$([a-z_]\w*)/gi;
let result = value;
/** @type {null | RegExpExecArray} */
let match;
/** @type {Set<string>} */
const seen = new Set(); // self-referential checker
while ((match = regex.exec(result)) !== null) {
seen.add(result);
const [template, bracedExpression, unbracedExpression] = match;
const expression = bracedExpression || unbracedExpression;
// match the operators `:+`, `+`, `:-`, and `-`
const opRegex = /(:\+|\+|:-|-)/;
// find first match
const opMatch = expression.match(opRegex);
const splitter = opMatch ? opMatch[0] : null;
const r = expression.split(/** @type {string} */ (splitter));
// const r = splitter ? expression.split(splitter) : [expression];
/** @type {string} */
let defaultValue;
/** @type {undefined | null | string} */
let value;
const key = r.shift();
if ([":+", "+"].includes(splitter || "")) {
defaultValue = env[key || ""] ? r.join(splitter || "") : "";
value = null;
} else {
defaultValue = r.join(splitter || "");
value = env[key || ""];
}
if (value) {
// self-referential check
result = seen.has(value)
? result.replace(template, defaultValue)
: result.replace(template, value);
} else {
result = result.replace(template, defaultValue);
}
// if the result equaled what was in process.env and runningParsed then stop expanding
if (result === runningParsed[key || ""]) {
break;
}
regex.lastIndex = 0; // reset regex search position to re-evaluate after each replacement
}
return result;
}
/**
* Expand environment variables in parsed object
* ported from https://github.com/motdotla/dotenv-expand
* @param {{ parsed: Env, processEnv: Record<string, string | undefined> }} options expand options
* @returns {{ parsed: Env }} expanded options
*/
function expand(options) {
// for use with progressive expansion
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
for (const key in options.parsed) {
let value = options.parsed[key];
// short-circuit scenario: process.env was already set prior to the file value
value =
Object.prototype.hasOwnProperty.call(processEnv, key) &&
processEnv[key] !== value
? /** @type {string} */ (processEnv[key])
: expandValue(value, processEnv, runningParsed);
const resolvedValue = _resolveEscapeSequences(value);
options.parsed[key] = resolvedValue;
// for use with progressive expansion
runningParsed[key] = resolvedValue;
}
// Part of `dotenv-expand` code, but we don't need it because of we don't modify `process.env`
// for (const processKey in options.parsed) {
// if (processEnv) {
// processEnv[processKey] = options.parsed[processKey];
// }
// }
return options;
}
/**
* Format environment variables as DefinePlugin definitions
* @param {Env} env environment variables
* @returns {Record<string, string>} formatted definitions
*/
const envToDefinitions = (env) => {
const definitions = /** @type {Record<string, string>} */ ({});
for (const [key, value] of Object.entries(env)) {
const defValue = JSON.stringify(value);
definitions[`process.env.${key}`] = defValue;
definitions[`import.meta.env.${key}`] = defValue;
}
return definitions;
};
class DotenvPlugin {
/**
* Creates an instance of DotenvPlugin.
* @param {DotenvPluginOptions=} options options object
*/
constructor(options = {}) {
/** @type {DotenvPluginOptions} */
this.options = options;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
() => {
const { definitions } = require("../schemas/WebpackOptions.json");
return {
definitions,
oneOf: [{ $ref: "#/definitions/DotenvPluginOptions" }]
};
},
this.options,
{
name: "Dotenv Plugin",
baseDataPath: "options"
}
);
});
const definePlugin = new compiler.webpack.DefinePlugin({});
const prefixes = Array.isArray(this.options.prefix)
? this.options.prefix
: [this.options.prefix || "WEBPACK_"];
/** @type {string | false} */
const dir =
typeof this.options.dir === "string"
? this.options.dir
: typeof this.options.dir === "undefined"
? compiler.context
: this.options.dir;
/** @type {undefined | Snapshot} */
let snapshot;
const cache = compiler.getCache(PLUGIN_NAME);
const identifier = JSON.stringify(
this.options.template || DEFAULT_TEMPLATE
);
const itemCache = cache.getItemCache(identifier, null);
compiler.hooks.beforeCompile.tapPromise(PLUGIN_NAME, async () => {
const { parsed, snapshot: newSnapshot } = dir
? await this._loadEnv(compiler, itemCache, dir)
: { parsed: {} };
const env = this._getEnv(prefixes, parsed);
definePlugin.definitions = envToDefinitions(env || {});
snapshot = newSnapshot;
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (snapshot) {
compilation.fileDependencies.addAll(snapshot.getFileIterable());
compilation.missingDependencies.addAll(snapshot.getMissingIterable());
}
});
definePlugin.apply(compiler);
}
/**
* Get list of env files to load based on mode and template
* Similar to Vite's getEnvFilesForMode
* @private
* @param {InputFileSystem} inputFileSystem the input file system
* @param {string | false} dir the directory containing .env files
* @param {string | undefined} mode the mode (e.g., 'production', 'development')
* @returns {string[]} array of file paths to load
*/
_getEnvFilesForMode(inputFileSystem, dir, mode) {
if (!dir) {
return [];
}
const templates = this.options.template || DEFAULT_TEMPLATE;
return templates
.map((pattern) => pattern.replace(/\[mode\]/g, mode || "development"))
.map((file) => join(inputFileSystem, dir, file));
}
/**
* Get parsed env variables from `.env` files
* @private
* @param {InputFileSystem} fs input file system
* @param {string} dir dir to load `.env` files
* @param {string} mode mode
* @returns {Promise<{ parsed: Env, fileDependencies: string[], missingDependencies: string[] }>} parsed env variables and dependencies
*/
async _getParsed(fs, dir, mode) {
/** @type {string[]} */
const fileDependencies = [];
/** @type {string[]} */
const missingDependencies = [];
// Get env files to load
const envFiles = this._getEnvFilesForMode(fs, dir, mode);
// Read all files
const contents = await Promise.all(
envFiles.map((filePath) =>
this._loadFile(fs, filePath).then(
(content) => {
fileDependencies.push(filePath);
return content;
},
() => {
// File doesn't exist, add to missingDependencies (this is normal)
missingDependencies.push(filePath);
return "";
}
)
)
);
// Parse all files and merge (later files override earlier ones)
// Similar to Vite's implementation
const parsed = /** @type {Env} */ (Object.create(null));
for (const content of contents) {
if (!content) continue;
const entries = parse(content);
for (const key in entries) {
parsed[key] = entries[key];
}
}
return { parsed, fileDependencies, missingDependencies };
}
/**
* Loads the provided compiler.
* @private
* @param {Compiler} compiler compiler
* @param {ItemCacheFacade} itemCache item cache facade
* @param {string} dir directory to read
* @returns {Promise<{ parsed: Env, snapshot: Snapshot }>} parsed result and snapshot
*/
async _loadEnv(compiler, itemCache, dir) {
const fs = /** @type {InputFileSystem} */ (compiler.inputFileSystem);
const fileSystemInfo = new FileSystemInfo(fs, {
unmanagedPaths: compiler.unmanagedPaths,
managedPaths: compiler.managedPaths,
immutablePaths: compiler.immutablePaths,
hashFunction: compiler.options.output.hashFunction
});
const result = await itemCache.getPromise();
if (result) {
const isSnapshotValid = await new Promise((resolve, reject) => {
fileSystemInfo.checkSnapshotValid(result.snapshot, (error, isValid) => {
if (error) {
reject(error);
return;
}
resolve(isValid);
});
});
if (isSnapshotValid) {
return { parsed: result.parsed, snapshot: result.snapshot };
}
}
const { parsed, fileDependencies, missingDependencies } =
await this._getParsed(
fs,
dir,
/** @type {string} */
(compiler.options.mode)
);
const startTime = Date.now();
const newSnapshot = await new Promise((resolve, reject) => {
fileSystemInfo.createSnapshot(
startTime,
fileDependencies,
null,
missingDependencies,
// `.env` files are build dependencies
compiler.options.snapshot.buildDependencies,
(err, snapshot) => {
if (err) return reject(err);
resolve(snapshot);
}
);
});
await itemCache.storePromise({ parsed, snapshot: newSnapshot });
return { parsed, snapshot: newSnapshot };
}
/**
* Generate env variables
* @private
* @param {Prefix} prefixes expose only environment variables that start with these prefixes
* @param {Env} parsed parsed env variables
* @returns {Env} env variables
*/
_getEnv(prefixes, parsed) {
// Always expand environment variables (like Vite does)
// 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} */ (Object.create(null));
// Get all keys from parser and process.env
const keys = [...Object.keys(parsed), ...Object.keys(process.env)];
// Prioritize actual env variables from `process.env`, fallback to parsed
for (const key of keys) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env[key] =
Object.prototype.hasOwnProperty.call(process.env, key) &&
process.env[key]
? process.env[key]
: parsed[key];
}
}
return env;
}
/**
* Load a file with proper path resolution
* @private
* @param {InputFileSystem} fs the input file system
* @param {string} file the file to load
* @returns {Promise<string>} the content of the file
*/
_loadFile(fs, file) {
return new Promise((resolve, reject) => {
fs.readFile(file, (err, content) => {
if (err) reject(err);
else resolve(/** @type {Buffer} */ (content).toString() || "");
});
});
}
}
module.exports = DotenvPlugin;

95
node_modules/webpack/lib/DynamicEntryPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,95 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Naoyuki Kanezawa @nkzawa
*/
"use strict";
const EntryOptionPlugin = require("./EntryOptionPlugin");
const EntryPlugin = require("./EntryPlugin");
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */
/** @typedef {import("../declarations/WebpackOptions").EntryStatic} EntryStatic */
/** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "DynamicEntryPlugin";
/** @typedef {() => EntryStatic | Promise<EntryStatic>} RawEntryDynamic */
/** @typedef {() => Promise<EntryStaticNormalized>} EntryDynamic */
class DynamicEntryPlugin {
/**
* Creates an instance of DynamicEntryPlugin.
* @param {string} context the context path
* @param {EntryDynamic} entry the entry value
*/
constructor(context, entry) {
/** @type {string} */
this.context = context;
/** @type {EntryDynamic} */
this.entry = entry;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
EntryDependency,
normalModuleFactory
);
}
);
compiler.hooks.make.tapPromise(PLUGIN_NAME, (compilation) =>
Promise.resolve(this.entry())
.then((entry) => {
/** @type {Promise<void>[]} */
const promises = [];
for (const name of Object.keys(entry)) {
const desc = entry[name];
const options = EntryOptionPlugin.entryDescriptionToOptions(
compiler,
name,
desc
);
for (const entry of /** @type {NonNullable<EntryDescriptionNormalized["import"]>} */ (
desc.import
)) {
promises.push(
new Promise(
/**
* Handles the callback logic for this hook.
* @param {(value?: undefined) => void} resolve resolve
* @param {(reason?: Error) => void} reject reject
*/
(resolve, reject) => {
compilation.addEntry(
this.context,
EntryPlugin.createDependency(entry, options),
options,
(err) => {
if (err) return reject(err);
resolve();
}
);
}
)
);
}
}
return Promise.all(promises);
})
.then(() => {})
);
}
}
module.exports = DynamicEntryPlugin;

101
node_modules/webpack/lib/EntryOptionPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,101 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */
/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
const PLUGIN_NAME = "EntryOptionPlugin";
class EntryOptionPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance one is tapping into
* @returns {void}
*/
apply(compiler) {
compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => {
EntryOptionPlugin.applyEntryOption(compiler, context, entry);
return true;
});
}
/**
* Apply entry option.
* @param {Compiler} compiler the compiler
* @param {string} context context directory
* @param {Entry} entry request
* @returns {void}
*/
static applyEntryOption(compiler, context, entry) {
if (typeof entry === "function") {
const DynamicEntryPlugin = require("./DynamicEntryPlugin");
new DynamicEntryPlugin(context, entry).apply(compiler);
} else {
const EntryPlugin = require("./EntryPlugin");
for (const name of Object.keys(entry)) {
const desc = entry[name];
const options = EntryOptionPlugin.entryDescriptionToOptions(
compiler,
name,
desc
);
const descImport =
/** @type {Exclude<EntryDescription["import"], undefined>} */
(desc.import);
for (const entry of descImport) {
new EntryPlugin(context, entry, options).apply(compiler);
}
}
}
}
/**
* Entry description to options.
* @param {Compiler} compiler the compiler
* @param {string} name entry name
* @param {EntryDescription} desc entry description
* @returns {EntryOptions} options for the entry
*/
static entryDescriptionToOptions(compiler, name, desc) {
/** @type {EntryOptions} */
const options = {
name,
filename: desc.filename,
runtime: desc.runtime,
layer: desc.layer,
dependOn: desc.dependOn,
baseUri: desc.baseUri,
publicPath: desc.publicPath,
chunkLoading: desc.chunkLoading,
asyncChunks: desc.asyncChunks,
wasmLoading: desc.wasmLoading,
library: desc.library
};
if (desc.chunkLoading) {
const EnableChunkLoadingPlugin = require("./javascript/EnableChunkLoadingPlugin");
EnableChunkLoadingPlugin.checkEnabled(compiler, desc.chunkLoading);
}
if (desc.wasmLoading) {
const EnableWasmLoadingPlugin = require("./wasm/EnableWasmLoadingPlugin");
EnableWasmLoadingPlugin.checkEnabled(compiler, desc.wasmLoading);
}
if (desc.library) {
const EnableLibraryPlugin = require("./library/EnableLibraryPlugin");
EnableLibraryPlugin.checkEnabled(compiler, desc.library.type);
}
return options;
}
}
module.exports = EntryOptionPlugin;

73
node_modules/webpack/lib/EntryPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,73 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
const PLUGIN_NAME = "EntryPlugin";
class EntryPlugin {
/**
* An entry plugin which will handle creation of the EntryDependency
* @param {string} context context path
* @param {string} entry entry path
* @param {EntryOptions | string=} options entry options (passing a string is deprecated)
*/
constructor(context, entry, options) {
this.context = context;
this.entry = entry;
this.options = options || "";
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
EntryDependency,
normalModuleFactory
);
}
);
const { entry, options, context } = this;
const dep = EntryPlugin.createDependency(entry, options);
compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
compilation.addEntry(context, dep, options, (err) => {
callback(err);
});
});
}
/**
* Creates a dependency.
* @param {string} entry entry request
* @param {EntryOptions | string} options entry options (passing string is deprecated)
* @returns {EntryDependency} the dependency
*/
static createDependency(entry, options) {
const dep = new EntryDependency(entry);
// TODO webpack 6 remove string option
dep.loc = {
name:
typeof options === "object"
? /** @type {string} */ (options.name)
: options
};
return dep;
}
}
module.exports = EntryPlugin;

124
node_modules/webpack/lib/Entrypoint.js generated vendored Normal file
View File

@@ -0,0 +1,124 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ChunkGroup = require("./ChunkGroup");
const SortableSet = require("./util/SortableSet");
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {{ name?: string } & Omit<EntryDescription, "import">} EntryOptions */
/**
* Entrypoint serves as an encapsulation primitive for chunks that are
* a part of a single ChunkGroup. They represent all bundles that need to be loaded for a
* single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects
* inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks.
*/
class Entrypoint extends ChunkGroup {
/**
* Creates an instance of Entrypoint.
* @param {EntryOptions | string} entryOptions the options for the entrypoint (or name)
* @param {boolean=} initial false, when the entrypoint is not initial loaded
*/
constructor(entryOptions, initial = true) {
if (typeof entryOptions === "string") {
entryOptions = { name: entryOptions };
}
super({
name: entryOptions.name
});
this.options = entryOptions;
/** @type {Chunk=} */
this._runtimeChunk = undefined;
/** @type {Chunk=} */
this._entrypointChunk = undefined;
/** @type {boolean} */
this._initial = initial;
/** @type {SortableSet<Entrypoint>} */
this._dependOn = new SortableSet();
}
/**
* Indicates whether this chunk group is loaded as part of the initial page
* load instead of being created lazily.
* @returns {boolean} true, when this chunk group will be loaded on initial page load
*/
isInitial() {
return this._initial;
}
/**
* Sets the runtimeChunk for an entrypoint.
* @param {Chunk} chunk the chunk being set as the runtime chunk.
* @returns {void}
*/
setRuntimeChunk(chunk) {
this._runtimeChunk = chunk;
}
/**
* Fetches the chunk reference containing the webpack bootstrap code
* @returns {Chunk | null} returns the runtime chunk or null if there is none
*/
getRuntimeChunk() {
if (this._runtimeChunk) return this._runtimeChunk;
for (const parent of this.parentsIterable) {
if (parent instanceof Entrypoint) return parent.getRuntimeChunk();
}
return null;
}
/**
* Sets the chunk with the entrypoint modules for an entrypoint.
* @param {Chunk} chunk the chunk being set as the entrypoint chunk.
* @returns {void}
*/
setEntrypointChunk(chunk) {
this._entrypointChunk = chunk;
}
/**
* Returns the chunk which contains the entrypoint modules
* (or at least the execution of them)
* @returns {Chunk} chunk
*/
getEntrypointChunk() {
return /** @type {Chunk} */ (this._entrypointChunk);
}
/**
* Replaces one member chunk with another while preserving the group's
* ordering and avoiding duplicates.
* @param {Chunk} oldChunk chunk to be replaced
* @param {Chunk} newChunk New chunk that will be replaced with
* @returns {boolean | undefined} returns true if the replacement was successful
*/
replaceChunk(oldChunk, newChunk) {
if (this._runtimeChunk === oldChunk) this._runtimeChunk = newChunk;
if (this._entrypointChunk === oldChunk) this._entrypointChunk = newChunk;
return super.replaceChunk(oldChunk, newChunk);
}
/**
* @param {Entrypoint} entrypoint the entrypoint
* @returns {void}
*/
addDependOn(entrypoint) {
this._dependOn.add(entrypoint);
}
/**
* @param {Entrypoint} entrypoint the entrypoint
* @returns {boolean} true if the entrypoint is in the dependOn set
*/
dependOn(entrypoint) {
return this._dependOn.has(entrypoint);
}
}
module.exports = Entrypoint;

75
node_modules/webpack/lib/EnvironmentPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
"use strict";
const DefinePlugin = require("./DefinePlugin");
const WebpackError = require("./errors/WebpackError");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */
const PLUGIN_NAME = "EnvironmentPlugin";
class EnvironmentPlugin {
/**
* Creates an instance of EnvironmentPlugin.
* @param {(string | string[] | Record<string, EXPECTED_ANY>)[]} keys keys
*/
constructor(...keys) {
if (keys.length === 1 && Array.isArray(keys[0])) {
/** @type {string[]} */
this.keys = keys[0];
this.defaultValues = {};
} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
this.keys = Object.keys(keys[0]);
this.defaultValues =
/** @type {Record<string, EXPECTED_ANY>} */
(keys[0]);
} else {
this.keys = /** @type {string[]} */ (keys);
this.defaultValues = {};
}
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const definePlugin = new DefinePlugin({});
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
/** @type {Record<string, CodeValue>} */
const definitions = {};
for (const key of this.keys) {
const value =
process.env[key] !== undefined
? process.env[key]
: this.defaultValues[key];
if (value === undefined) {
const error = new WebpackError(
`${PLUGIN_NAME} - ${key} environment variable is undefined.\n\n` +
"You can pass an object with default values to suppress this warning.\n" +
"See https://webpack.js.org/plugins/environment-plugin for example."
);
error.name = "EnvVariableNotDefinedError";
compilation.errors.push(error);
}
const defValue =
value === undefined ? "undefined" : JSON.stringify(value);
definitions[`process.env.${key}`] = defValue;
definitions[`import.meta.env.${key}`] = defValue;
}
definePlugin.definitions = definitions;
});
definePlugin.apply(compiler);
}
}
module.exports = EnvironmentPlugin;

107
node_modules/webpack/lib/ErrorHelpers.js generated vendored Normal file
View File

@@ -0,0 +1,107 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const loaderFlag = "LOADER_EXECUTION";
const webpackOptionsFlag = "WEBPACK_OPTIONS";
/**
* Returns stack trace without the specified flag included.
* @param {string} stack stack trace
* @param {string} flag flag to cut off
* @returns {string} stack trace without the specified flag included
*/
const cutOffByFlag = (stack, flag) => {
const errorStack = stack.split("\n");
for (let i = 0; i < errorStack.length; i++) {
if (errorStack[i].includes(flag)) {
errorStack.length = i;
}
}
return errorStack.join("\n");
};
/**
* Cut off loader execution.
* @param {string} stack stack trace
* @returns {string} stack trace without the loader execution flag included
*/
const cutOffLoaderExecution = (stack) => cutOffByFlag(stack, loaderFlag);
/**
* Cut off webpack options.
* @param {string} stack stack trace
* @returns {string} stack trace without the webpack options flag included
*/
const cutOffWebpackOptions = (stack) => cutOffByFlag(stack, webpackOptionsFlag);
/**
* Cut off multiline message.
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the message included
*/
const cutOffMultilineMessage = (stack, message) => {
const stackSplitByLines = stack.split("\n");
const messageSplitByLines = message.split("\n");
/** @type {string[]} */
const result = [];
for (const [idx, line] of stackSplitByLines.entries()) {
if (!line.includes(messageSplitByLines[idx])) result.push(line);
}
return result.join("\n");
};
/**
* Returns stack trace without the message included.
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the message included
*/
const cutOffMessage = (stack, message) => {
const nextLine = stack.indexOf("\n");
if (nextLine === -1) {
return stack === message ? "" : stack;
}
const firstLine = stack.slice(0, nextLine);
return firstLine === message ? stack.slice(nextLine + 1) : stack;
};
/**
* Returns stack trace without the loader execution flag and message included.
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the loader execution flag and message included
*/
const cleanUp = (stack, message) => {
stack = cutOffLoaderExecution(stack);
stack = cutOffMessage(stack, message);
return stack;
};
/**
* Clean up webpack options.
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the webpack options flag and message included
*/
const cleanUpWebpackOptions = (stack, message) => {
stack = cutOffWebpackOptions(stack);
stack = cutOffMultilineMessage(stack, message);
return stack;
};
module.exports.cleanUp = cleanUp;
module.exports.cleanUpWebpackOptions = cleanUpWebpackOptions;
module.exports.cutOffByFlag = cutOffByFlag;
module.exports.cutOffLoaderExecution = cutOffLoaderExecution;
module.exports.cutOffMessage = cutOffMessage;
module.exports.cutOffMultilineMessage = cutOffMultilineMessage;
module.exports.cutOffWebpackOptions = cutOffWebpackOptions;

137
node_modules/webpack/lib/EvalDevToolModulePlugin.js generated vendored Normal file
View File

@@ -0,0 +1,137 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, RawSource } = require("webpack-sources");
const ExternalModule = require("./ExternalModule");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const RuntimeGlobals = require("./RuntimeGlobals");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").DevtoolNamespace} DevtoolNamespace */
/** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */
/** @typedef {import("./Compiler")} Compiler */
/** @type {WeakMap<Source, Source>} */
const cache = new WeakMap();
const devtoolWarning = new RawSource(`/*
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
* This devtool is neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
`);
/**
* Defines the eval dev tool module plugin options type used by this module.
* @typedef {object} EvalDevToolModulePluginOptions
* @property {DevtoolNamespace=} namespace namespace
* @property {string=} sourceUrlComment source url comment
* @property {DevtoolModuleFilenameTemplate=} moduleFilenameTemplate module filename template
*/
const PLUGIN_NAME = "EvalDevToolModulePlugin";
class EvalDevToolModulePlugin {
/**
* Creates an instance of EvalDevToolModulePlugin.
* @param {EvalDevToolModulePluginOptions=} options options
*/
constructor(options = {}) {
/** @type {DevtoolNamespace} */
this.namespace = options.namespace || "";
/** @type {string} */
this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]";
/** @type {DevtoolModuleFilenameTemplate} */
this.moduleFilenameTemplate =
options.moduleFilenameTemplate ||
"webpack://[namespace]/[resourcePath]?[loaders]";
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModuleContent.tap(
PLUGIN_NAME,
(source, module, { chunk, runtimeTemplate, chunkGraph }) => {
const cacheEntry = cache.get(source);
if (cacheEntry !== undefined) return cacheEntry;
if (module instanceof ExternalModule) {
cache.set(source, source);
return source;
}
const content = source.source();
const namespace = compilation.getPath(this.namespace, {
chunk
});
const str = ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: this.moduleFilenameTemplate,
namespace
},
{
requestShortener: runtimeTemplate.requestShortener,
chunkGraph,
hashFunction: compilation.outputOptions.hashFunction
}
);
const footer = `\n${this.sourceUrlComment.replace(
/\[url\]/g,
encodeURI(str)
.replace(/%2F/g, "/")
.replace(/%20/g, "_")
.replace(/%5E/g, "^")
.replace(/%5C/g, "\\")
.replace(/^\//, "")
)}`;
const result = new RawSource(
`eval(${
compilation.outputOptions.trustedTypes
? `${RuntimeGlobals.createScript}(${JSON.stringify(
`{${content + footer}\n}`
)})`
: JSON.stringify(`{${content + footer}\n}`)
});`
);
cache.set(source, result);
return result;
}
);
hooks.inlineInRuntimeBailout.tap(
PLUGIN_NAME,
() => "the eval devtool is used."
);
hooks.render.tap(
PLUGIN_NAME,
(source) => new ConcatSource(devtoolWarning, source)
);
hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => {
hash.update(PLUGIN_NAME);
hash.update("2");
});
if (compilation.outputOptions.trustedTypes) {
compilation.hooks.additionalModuleRuntimeRequirements.tap(
PLUGIN_NAME,
(module, set, _context) => {
set.add(RuntimeGlobals.createScript);
}
);
}
});
}
}
module.exports = EvalDevToolModulePlugin;

252
node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,252 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, RawSource } = require("webpack-sources");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const NormalModule = require("./NormalModule");
const RuntimeGlobals = require("./RuntimeGlobals");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const ConcatenatedModule = require("./optimize/ConcatenatedModule");
const generateDebugId = require("./util/generateDebugId");
const { makePathsAbsolute } = require("./util/identifier");
/** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").DevtoolNamespace} DevtoolNamespace */
/** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").Rules} Rules */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @type {WeakMap<Source, Source>} */
const cache = new WeakMap();
const devtoolWarning = new RawSource(`/*
* ATTENTION: An "eval-source-map" devtool has been used.
* This devtool is neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
`);
const PLUGIN_NAME = "EvalSourceMapDevToolPlugin";
class EvalSourceMapDevToolPlugin {
/**
* Creates an instance of EvalSourceMapDevToolPlugin.
* @param {SourceMapDevToolPluginOptions | string=} inputOptions Options object
*/
constructor(inputOptions = {}) {
/** @type {SourceMapDevToolPluginOptions} */
let options;
if (typeof inputOptions === "string") {
options = {
append: inputOptions
};
} else {
options = inputOptions;
}
/** @type {string} */
this.sourceMapComment =
options.append && typeof options.append !== "function"
? options.append
: "//# sourceURL=[module]\n//# sourceMappingURL=[url]";
/** @type {DevtoolModuleFilenameTemplate} */
this.moduleFilenameTemplate =
options.moduleFilenameTemplate ||
"webpack://[namespace]/[resource-path]?[hash]";
/** @type {DevtoolNamespace} */
this.namespace = options.namespace || "";
/** @type {SourceMapDevToolPluginOptions} */
this.options = options;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
const matchModule = ModuleFilenameHelpers.matchObject.bind(
ModuleFilenameHelpers,
options
);
hooks.renderModuleContent.tap(
PLUGIN_NAME,
(source, m, { chunk, runtimeTemplate, chunkGraph }) => {
const cachedSource = cache.get(source);
if (cachedSource !== undefined) {
return cachedSource;
}
/**
* Returns result.
* @param {Source} r result
* @returns {Source} result
*/
const result = (r) => {
cache.set(source, r);
return r;
};
if (m instanceof NormalModule) {
if (!matchModule(m.resource)) {
return result(source);
}
} else if (m instanceof ConcatenatedModule) {
if (m.rootModule instanceof NormalModule) {
if (!matchModule(m.rootModule.resource)) {
return result(source);
}
} else {
return result(source);
}
} else {
return result(source);
}
const namespace = compilation.getPath(this.namespace, {
chunk
});
/** @type {RawSourceMap} */
let sourceMap;
/** @type {string | Buffer} */
let content;
if (source.sourceAndMap) {
const sourceAndMap = source.sourceAndMap(options);
sourceMap = /** @type {RawSourceMap} */ (sourceAndMap.map);
content = sourceAndMap.source;
} else {
sourceMap = /** @type {RawSourceMap} */ (source.map(options));
content = source.source();
}
if (!sourceMap) {
return result(source);
}
// Clone (flat) the sourcemap to ensure that the mutations below do not persist.
sourceMap = { ...sourceMap };
const context = compiler.context;
const root = compiler.root;
const cachedAbsolutify = makePathsAbsolute.bindContextCache(
context,
root
);
const modules = sourceMap.sources.map((source) => {
if (!source.startsWith("webpack://")) return source;
source = cachedAbsolutify(source.slice(10));
const module = compilation.findModule(source);
return module || source;
});
let moduleFilenames = modules.map((module) =>
ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: this.moduleFilenameTemplate,
namespace
},
{
requestShortener: runtimeTemplate.requestShortener,
chunkGraph,
hashFunction: compilation.outputOptions.hashFunction
}
)
);
moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(
moduleFilenames,
(filename, i, n) => {
for (let j = 0; j < n; j++) filename += "*";
return filename;
}
);
sourceMap.sources = moduleFilenames;
if (options.ignoreList) {
const ignoreList = sourceMap.sources.reduce(
/** @type {(acc: number[], sourceName: string, idx: number) => number[]} */ (
(acc, sourceName, idx) => {
const rule = /** @type {Rules} */ (options.ignoreList);
if (ModuleFilenameHelpers.matchPart(sourceName, rule)) {
acc.push(idx);
}
return acc;
}
),
[]
);
if (ignoreList.length > 0) {
sourceMap.ignoreList = ignoreList;
}
}
if (options.noSources) {
sourceMap.sourcesContent = undefined;
}
sourceMap.sourceRoot = options.sourceRoot || "";
const moduleId =
/** @type {ModuleId} */
(chunkGraph.getModuleId(m));
sourceMap.file =
typeof moduleId === "number" ? `${moduleId}.js` : moduleId;
if (options.debugIds) {
sourceMap.debugId = generateDebugId(content, sourceMap.file);
}
const footer = `${this.sourceMapComment.replace(
/\[url\]/g,
`data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(sourceMap),
"utf8"
).toString("base64")}`
)}\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug
return result(
new RawSource(
`eval(${
compilation.outputOptions.trustedTypes
? `${RuntimeGlobals.createScript}(${JSON.stringify(
`{${content + footer}\n}`
)})`
: JSON.stringify(`{${content + footer}\n}`)
});`
)
);
}
);
hooks.inlineInRuntimeBailout.tap(
PLUGIN_NAME,
() => "the eval-source-map devtool is used."
);
hooks.render.tap(
PLUGIN_NAME,
(source) => new ConcatSource(devtoolWarning, source)
);
hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => {
hash.update(PLUGIN_NAME);
hash.update("2");
});
if (compilation.outputOptions.trustedTypes) {
compilation.hooks.additionalModuleRuntimeRequirements.tap(
PLUGIN_NAME,
(module, set, context) => {
set.add(RuntimeGlobals.createScript);
}
);
}
});
}
}
module.exports = EvalSourceMapDevToolPlugin;

1713
node_modules/webpack/lib/ExportsInfo.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

88
node_modules/webpack/lib/ExportsInfoApiPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,88 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const ConstDependency = require("./dependencies/ConstDependency");
const ExportsInfoDependency = require("./dependencies/ExportsInfoDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
const PLUGIN_NAME = "ExportsInfoApiPlugin";
class ExportsInfoApiPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ExportsInfoDependency,
new ExportsInfoDependency.Template()
);
/**
* Handles the hook callback for this code path.
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const handler = (parser) => {
parser.hooks.expressionMemberChain
.for("__webpack_exports_info__")
.tap(PLUGIN_NAME, (expr, members) => {
const dep =
members.length >= 2
? new ExportsInfoDependency(
/** @type {Range} */ (expr.range),
members.slice(0, -1),
members[members.length - 1]
)
: new ExportsInfoDependency(
/** @type {Range} */ (expr.range),
null,
members[0]
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
return true;
});
parser.hooks.expression
.for("__webpack_exports_info__")
.tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
"true",
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = ExportsInfoApiPlugin;

1305
node_modules/webpack/lib/ExternalModule.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

386
node_modules/webpack/lib/ExternalModuleFactoryPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,386 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const ExternalModule = require("./ExternalModule");
const { ASSET_URL_TYPE } = require("./ModuleSourceTypeConstants");
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const CssImportDependency = require("./dependencies/CssImportDependency");
const CssUrlDependency = require("./dependencies/CssUrlDependency");
const HarmonyImportDependency = require("./dependencies/HarmonyImportDependency");
const ImportDependency = require("./dependencies/ImportDependency");
const { cachedSetProperty, resolveByProperty } = require("./util/cleverMerge");
/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").ExternalsType} ExternalsType */
/** @typedef {import("../declarations/WebpackOptions").ExternalItem} ExternalItem */
/** @typedef {import("../declarations/WebpackOptions").ExternalItemValue} ExternalItemValue */
/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectKnown} ExternalItemObjectKnown */
/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectUnknown} ExternalItemObjectUnknown */
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./ExternalModule").DependencyMeta} DependencyMeta */
/** @typedef {import("./ModuleFactory").IssuerLayer} IssuerLayer */
/** @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) => Promise<string>)} ExternalItemFunctionDataGetResolveResult */
/** @typedef {(options?: ResolveOptions) => ExternalItemFunctionDataGetResolveCallbackResult | ExternalItemFunctionDataGetResolveResult} ExternalItemFunctionDataGetResolve */
/**
* Defines the external item function data type used by this module.
* @typedef {object} ExternalItemFunctionData
* @property {string} context the directory in which the request is placed
* @property {ModuleFactoryCreateDataContextInfo} contextInfo contextual information
* @property {string} dependencyType the category of the referencing dependency
* @property {ExternalItemFunctionDataGetResolve} getResolve get a resolve function with the current resolver options
* @property {string} request the request as written by the user in the require/import expression/statement
*/
/** @typedef {((data: ExternalItemFunctionData, callback: (err?: (Error | null), result?: ExternalItemValue) => void) => void)} ExternalItemFunctionCallback */
/** @typedef {((data: import("../lib/ExternalModuleFactoryPlugin").ExternalItemFunctionData) => Promise<ExternalItemValue>)} ExternalItemFunctionPromise */
const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9-]+ /;
const EMPTY_RESOLVE_OPTIONS = {};
// TODO webpack 6 remove this
const callDeprecatedExternals = util.deprecate(
/**
* Handles the callback logic for this hook.
* @param {EXPECTED_FUNCTION} externalsFunction externals function
* @param {string} context context
* @param {string} request request
* @param {(err: Error | null | undefined, value: ExternalValue | undefined, ty: ExternalsType | undefined) => void} cb cb
*/
(externalsFunction, context, request, cb) => {
// eslint-disable-next-line no-useless-call
externalsFunction.call(null, context, request, cb);
},
"The externals-function should be defined like ({context, request}, cb) => { ... }",
"DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS"
);
/** @typedef {(layer: string | null) => ExternalItem} ExternalItemByLayerFn */
/** @typedef {ExternalItemObjectKnown & ExternalItemObjectUnknown} ExternalItemObject */
/**
* Defines the external weak cache type used by this module.
* @template {ExternalItemObject} T
* @typedef {WeakMap<T, Map<IssuerLayer, Omit<T, "byLayer">>>} ExternalWeakCache
*/
/** @type {ExternalWeakCache<ExternalItemObject>} */
const cache = new WeakMap();
/**
* Returns result.
* @param {ExternalItemObject} obj obj
* @param {IssuerLayer} layer layer
* @returns {Omit<ExternalItemObject, "byLayer">} result
*/
const resolveLayer = (obj, layer) => {
let map = cache.get(obj);
if (map === undefined) {
map = new Map();
cache.set(obj, map);
} else {
const cacheEntry = map.get(layer);
if (cacheEntry !== undefined) return cacheEntry;
}
const result = resolveByProperty(obj, "byLayer", layer);
map.set(layer, result);
return result;
};
/** @typedef {string | string[] | boolean | Record<string, string | string[]>} ExternalValue */
const PLUGIN_NAME = "ExternalModuleFactoryPlugin";
class ExternalModuleFactoryPlugin {
/**
* Creates an instance of ExternalModuleFactoryPlugin.
* @param {ExternalsType | ((dependency: Dependency) => ExternalsType)} type default external type
* @param {Externals} externals externals config
*/
constructor(type, externals) {
this.type = type;
this.externals = externals;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {NormalModuleFactory} normalModuleFactory the normal module factory
* @returns {void}
*/
apply(normalModuleFactory) {
const globalType = this.type;
normalModuleFactory.hooks.factorize.tapAsync(
PLUGIN_NAME,
(data, callback) => {
const context = data.context;
const contextInfo = data.contextInfo;
const dependency = data.dependencies[0];
const dependencyType = data.dependencyType;
/** @typedef {(err?: Error | null, externalModule?: ExternalModule) => void} HandleExternalCallback */
/**
* Processes the provided value.
* @param {ExternalValue} value the external config
* @param {ExternalsType | undefined} type type of external
* @param {HandleExternalCallback} callback callback
* @returns {void}
*/
const handleExternal = (value, type, callback) => {
if (value === false) {
// Not externals, fallback to original factory
return callback();
}
/** @type {ExternalValue} */
let externalConfig = value === true ? dependency.request : value;
// When no explicit type is specified, extract it from the externalConfig
if (type === undefined) {
if (
typeof externalConfig === "string" &&
UNSPECIFIED_EXTERNAL_TYPE_REGEXP.test(externalConfig)
) {
const idx = externalConfig.indexOf(" ");
type =
/** @type {ExternalsType} */
(externalConfig.slice(0, idx));
externalConfig = externalConfig.slice(idx + 1);
} else if (
Array.isArray(externalConfig) &&
externalConfig.length > 0 &&
UNSPECIFIED_EXTERNAL_TYPE_REGEXP.test(externalConfig[0])
) {
const firstItem = externalConfig[0];
const idx = firstItem.indexOf(" ");
type = /** @type {ExternalsType} */ (firstItem.slice(0, idx));
externalConfig = [
firstItem.slice(idx + 1),
...externalConfig.slice(1)
];
}
}
const defaultType =
typeof globalType === "function"
? globalType(dependency)
: globalType;
const resolvedType = type || defaultType;
// TODO make it pluggable/add hooks to `ExternalModule` to allow output modules own externals?
/** @type {DependencyMeta | undefined} */
let dependencyMeta;
if (
dependency instanceof HarmonyImportDependency ||
dependency instanceof ImportDependency ||
dependency instanceof ContextElementDependency
) {
const externalType =
dependency instanceof HarmonyImportDependency
? "module"
: dependency instanceof ImportDependency
? "import"
: undefined;
dependencyMeta = {
attributes: dependency.attributes,
phase:
dependency instanceof HarmonyImportDependency ||
dependency instanceof ImportDependency
? dependency.phase
: undefined,
externalType
};
} else if (dependency instanceof CssImportDependency) {
dependencyMeta = {
layer: dependency.layer,
supports: dependency.supports,
media: dependency.media
};
}
if (
resolvedType === "asset" &&
dependency instanceof CssUrlDependency
) {
dependencyMeta = { sourceType: ASSET_URL_TYPE };
}
callback(
null,
new ExternalModule(
externalConfig,
resolvedType,
dependency.request,
dependencyMeta
)
);
};
/**
* Processes the provided external.
* @param {Externals} externals externals config
* @param {HandleExternalCallback} callback callback
* @returns {void}
*/
const handleExternals = (externals, callback) => {
if (typeof externals === "string") {
if (externals === dependency.request) {
return handleExternal(dependency.request, undefined, callback);
}
} else if (Array.isArray(externals)) {
let i = 0;
const next = () => {
/** @type {boolean | undefined} */
let asyncFlag;
/**
* Handle externals and callback.
* @param {(Error | null)=} err err
* @param {ExternalModule=} module module
* @returns {void}
*/
const handleExternalsAndCallback = (err, module) => {
if (err) return callback(err);
if (!module) {
if (asyncFlag) {
asyncFlag = false;
return;
}
return next();
}
callback(null, module);
};
do {
asyncFlag = true;
if (i >= externals.length) return callback();
handleExternals(externals[i++], handleExternalsAndCallback);
} while (!asyncFlag);
asyncFlag = false;
};
next();
return;
} else if (externals instanceof RegExp) {
if (externals.test(dependency.request)) {
return handleExternal(dependency.request, undefined, callback);
}
} else if (typeof externals === "function") {
/**
* Processes the provided err.
* @param {Error | null | undefined} err err
* @param {ExternalValue=} value value
* @param {ExternalsType=} type type
* @returns {void}
*/
const cb = (err, value, type) => {
if (err) return callback(err);
if (value !== undefined) {
handleExternal(value, type, callback);
} else {
callback();
}
};
if (externals.length === 3) {
// TODO webpack 6 remove this
callDeprecatedExternals(
externals,
context,
dependency.request,
cb
);
} else {
const promise = externals(
{
context,
request: dependency.request,
dependencyType,
contextInfo,
getResolve: (options) => (context, request, callback) => {
/** @type {ResolveContext} */
const resolveContext = {
fileDependencies: data.fileDependencies,
missingDependencies: data.missingDependencies,
contextDependencies: data.contextDependencies
};
let resolver = normalModuleFactory.getResolver(
"normal",
dependencyType
? cachedSetProperty(
data.resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType",
dependencyType
)
: data.resolveOptions
);
if (options) resolver = resolver.withOptions(options);
if (callback) {
resolver.resolve(
{},
context,
request,
resolveContext,
callback
);
} else {
return new Promise((resolve, reject) => {
resolver.resolve(
{},
context,
request,
resolveContext,
(err, result) => {
if (err) reject(err);
else resolve(result);
}
);
});
}
}
},
cb
);
if (promise && promise.then) {
promise.then((r) => cb(null, r), cb);
}
}
return;
} else if (typeof externals === "object") {
const resolvedExternals = resolveLayer(
externals,
/** @type {IssuerLayer} */
(contextInfo.issuerLayer)
);
if (
Object.prototype.hasOwnProperty.call(
resolvedExternals,
dependency.request
)
) {
return handleExternal(
resolvedExternals[dependency.request],
undefined,
callback
);
}
}
callback();
};
handleExternals(this.externals, callback);
}
);
}
}
module.exports = ExternalModuleFactoryPlugin;

94
node_modules/webpack/lib/ExternalsPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,94 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ModuleExternalInitFragment } = require("./ExternalModule");
const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
const ConcatenatedModule = require("./optimize/ConcatenatedModule");
/** @typedef {import("../declarations/WebpackOptions").ExternalsType} ExternalsType */
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ExternalModule").Imported} Imported */
/** @typedef {import("./Dependency")} Dependency */
const PLUGIN_NAME = "ExternalsPlugin";
class ExternalsPlugin {
/**
* Creates an instance of ExternalsPlugin.
* @param {ExternalsType | ((dependency: Dependency) => ExternalsType)} type default external type
* @param {Externals} externals externals config
*/
constructor(type, externals) {
this.type = type;
this.externals = externals;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compile.tap(PLUGIN_NAME, ({ normalModuleFactory }) => {
new ExternalModuleFactoryPlugin(this.type, this.externals).apply(
normalModuleFactory
);
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const { concatenatedModuleInfo } =
ConcatenatedModule.getCompilationHooks(compilation);
concatenatedModuleInfo.tap(PLUGIN_NAME, (updatedInfo, moduleInfo) => {
const rawExportMap = updatedInfo.rawExportMap;
if (!rawExportMap) {
return;
}
const chunkInitFragments = moduleInfo.chunkInitFragments;
const moduleExternalInitFragments =
/** @type {ModuleExternalInitFragment[]} */
(
chunkInitFragments
? /** @type {unknown[]} */
(chunkInitFragments).filter(
(fragment) => fragment instanceof ModuleExternalInitFragment
)
: []
);
let initFragmentChanged = false;
for (const fragment of moduleExternalInitFragments) {
const imported = fragment.getImported();
if (Array.isArray(imported)) {
const newImported =
/** @type {Imported} */
(
imported.map(([specifier, finalName]) => [
specifier,
rawExportMap.has(specifier)
? rawExportMap.get(specifier)
: finalName
])
);
fragment.setImported(newImported);
initFragmentChanged = true;
}
}
if (initFragmentChanged) {
return true;
}
});
});
}
}
module.exports = ExternalsPlugin;

4353
node_modules/webpack/lib/FileSystemInfo.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

56
node_modules/webpack/lib/FlagAllModulesAsUsedPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,56 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").FactoryMeta} FactoryMeta */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
const PLUGIN_NAME = "FlagAllModulesAsUsedPlugin";
class FlagAllModulesAsUsedPlugin {
/**
* Creates an instance of FlagAllModulesAsUsedPlugin.
* @param {string} explanation explanation
*/
constructor(explanation) {
this.explanation = explanation;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, (modules) => {
/** @type {RuntimeSpec} */
let runtime;
for (const [name, { options }] of compilation.entries) {
runtime = mergeRuntimeOwned(
runtime,
getEntryRuntime(compilation, name, options)
);
}
for (const module of modules) {
const exportsInfo = moduleGraph.getExportsInfo(module);
exportsInfo.setUsedInUnknownWay(runtime);
moduleGraph.addExtraReason(module, this.explanation);
if (module.factoryMeta === undefined) {
module.factoryMeta = {};
}
/** @type {FactoryMeta} */
(module.factoryMeta).sideEffectFree = false;
}
});
});
}
}
module.exports = FlagAllModulesAsUsedPlugin;

440
node_modules/webpack/lib/FlagDependencyExportsPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,440 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const Queue = require("./util/Queue");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").ExportSpec} ExportSpec */
/** @typedef {import("./Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("./ExportsInfo").RestoreProvidedData} RestoreProvidedData */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
const PLUGIN_NAME = "FlagDependencyExportsPlugin";
const PLUGIN_LOGGER_NAME = `webpack.${PLUGIN_NAME}`;
class FlagDependencyExportsPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
const cache = compilation.getCache(PLUGIN_NAME);
compilation.hooks.finishModules.tapAsync(
PLUGIN_NAME,
(modules, callback) => {
const logger = compilation.getLogger(PLUGIN_LOGGER_NAME);
let statRestoredFromMemCache = 0;
let statRestoredFromCache = 0;
let statNoExports = 0;
let statFlaggedUncached = 0;
let statNotCached = 0;
let statQueueItemsProcessed = 0;
const { moduleMemCaches } = compilation;
/** @type {Queue<Module>} */
const queue = new Queue();
// Step 1: Try to restore cached provided export info from cache
logger.time("restore cached provided exports");
asyncLib.each(
/** @type {import("neo-async").IterableCollection<Module>} */ (
/** @type {unknown} */ (modules)
),
(module, callback) => {
const exportsInfo = moduleGraph.getExportsInfo(module);
// If the module doesn't have an exportsType, it's a module
// without declared exports.
if (
(!module.buildMeta || !module.buildMeta.exportsType) &&
exportsInfo.otherExportsInfo.provided !== null
) {
// It's a module without declared exports
statNoExports++;
exportsInfo.setHasProvideInfo();
exportsInfo.setUnknownExportsProvided();
return callback();
}
// If the module has no hash, it's uncacheable
if (
typeof (/** @type {BuildInfo} */ (module.buildInfo).hash) !==
"string"
) {
statFlaggedUncached++;
// Enqueue uncacheable module for determining the exports
queue.enqueue(module);
exportsInfo.setHasProvideInfo();
return callback();
}
const memCache = moduleMemCaches && moduleMemCaches.get(module);
const memCacheValue = memCache && memCache.get(this);
if (memCacheValue !== undefined) {
statRestoredFromMemCache++;
exportsInfo.restoreProvided(memCacheValue);
return callback();
}
cache.get(
module.identifier(),
/** @type {BuildInfo} */
(module.buildInfo).hash,
(err, result) => {
if (err) return callback(err);
if (result !== undefined) {
statRestoredFromCache++;
exportsInfo.restoreProvided(result);
} else {
statNotCached++;
// Without cached info enqueue module for determining the exports
queue.enqueue(module);
exportsInfo.setHasProvideInfo();
}
callback();
}
);
},
(err) => {
logger.timeEnd("restore cached provided exports");
if (err) return callback(err);
/** @type {Set<Module>} */
const modulesToStore = new Set();
/** @type {Map<Module, Set<Module>>} */
const dependencies = new Map();
/** @type {Module} */
let module;
/** @type {ExportsInfo} */
let exportsInfo;
/** @type {Map<Dependency, ExportsSpec>} */
const exportsSpecsFromDependencies = new Map();
let cacheable = true;
let changed = false;
/**
* Process dependencies block.
* @param {DependenciesBlock} depBlock the dependencies block
* @returns {void}
*/
const processDependenciesBlock = (depBlock) => {
for (const dep of depBlock.dependencies) {
processDependency(dep);
}
for (const block of depBlock.blocks) {
processDependenciesBlock(block);
}
};
/**
* Process dependency.
* @param {Dependency} dep the dependency
* @returns {void}
*/
const processDependency = (dep) => {
const exportDesc = dep.getExports(moduleGraph);
if (!exportDesc) return;
exportsSpecsFromDependencies.set(dep, exportDesc);
};
/**
* Process exports spec.
* @param {Dependency} dep dependency
* @param {ExportsSpec} exportDesc info
* @returns {void}
*/
const processExportsSpec = (dep, exportDesc) => {
const exports = exportDesc.exports;
const globalCanMangle = exportDesc.canMangle;
const globalFrom = exportDesc.from;
const globalPriority = exportDesc.priority;
const globalTerminalBinding =
exportDesc.terminalBinding || false;
const exportDeps = exportDesc.dependencies;
if (exportDesc.hideExports) {
for (const name of exportDesc.hideExports) {
const exportInfo = exportsInfo.getExportInfo(name);
exportInfo.unsetTarget(dep);
}
}
if (exports === true) {
// unknown exports
if (
exportsInfo.setUnknownExportsProvided(
globalCanMangle,
exportDesc.excludeExports,
globalFrom && dep,
globalFrom,
globalPriority
)
) {
changed = true;
}
} else if (Array.isArray(exports)) {
/**
* merge in new exports
* @param {ExportsInfo} exportsInfo own exports info
* @param {(ExportSpec | string)[]} exports list of exports
*/
const mergeExports = (exportsInfo, exports) => {
for (const exportNameOrSpec of exports) {
/** @type {ExportInfoName} */
let name;
let canMangle = globalCanMangle;
let terminalBinding = globalTerminalBinding;
/** @type {ExportSpec["exports"]} */
let exports;
let from = globalFrom;
/** @type {ExportSpec["export"]} */
let fromExport;
let priority = globalPriority;
let hidden = false;
if (typeof exportNameOrSpec === "string") {
name = exportNameOrSpec;
} else {
name = exportNameOrSpec.name;
if (exportNameOrSpec.canMangle !== undefined) {
canMangle = exportNameOrSpec.canMangle;
}
if (exportNameOrSpec.export !== undefined) {
fromExport = exportNameOrSpec.export;
}
if (exportNameOrSpec.exports !== undefined) {
exports = exportNameOrSpec.exports;
}
if (exportNameOrSpec.from !== undefined) {
from = exportNameOrSpec.from;
}
if (exportNameOrSpec.priority !== undefined) {
priority = exportNameOrSpec.priority;
}
if (exportNameOrSpec.terminalBinding !== undefined) {
terminalBinding = exportNameOrSpec.terminalBinding;
}
if (exportNameOrSpec.hidden !== undefined) {
hidden = exportNameOrSpec.hidden;
}
}
const exportInfo = exportsInfo.getExportInfo(name);
if (
exportInfo.provided === false ||
exportInfo.provided === null
) {
exportInfo.provided = true;
changed = true;
}
if (
exportInfo.canMangleProvide !== false &&
canMangle === false
) {
exportInfo.canMangleProvide = false;
changed = true;
}
if (terminalBinding && !exportInfo.terminalBinding) {
exportInfo.terminalBinding = true;
changed = true;
}
if (exports) {
const nestedExportsInfo =
exportInfo.createNestedExportsInfo();
mergeExports(
/** @type {ExportsInfo} */ (nestedExportsInfo),
exports
);
}
if (
from &&
(hidden
? exportInfo.unsetTarget(dep)
: exportInfo.setTarget(
dep,
from,
fromExport === undefined ? [name] : fromExport,
priority
))
) {
changed = true;
}
// Recalculate target exportsInfo
const target = exportInfo.getTarget(moduleGraph);
/** @type {undefined | ExportsInfo} */
let targetExportsInfo;
if (target) {
const targetModuleExportsInfo =
moduleGraph.getExportsInfo(target.module);
targetExportsInfo =
targetModuleExportsInfo.getNestedExportsInfo(
target.export
);
// add dependency for this module
const set = dependencies.get(target.module);
if (set === undefined) {
dependencies.set(target.module, new Set([module]));
} else {
set.add(module);
}
}
if (exportInfo.exportsInfoOwned) {
if (
/** @type {ExportsInfo} */
(exportInfo.exportsInfo).setRedirectNamedTo(
targetExportsInfo
)
) {
changed = true;
}
} else if (exportInfo.exportsInfo !== targetExportsInfo) {
exportInfo.exportsInfo = targetExportsInfo;
changed = true;
}
}
};
mergeExports(exportsInfo, exports);
}
// store dependencies
if (exportDeps) {
cacheable = false;
for (const exportDependency of exportDeps) {
// add dependency for this module
const set = dependencies.get(exportDependency);
if (set === undefined) {
dependencies.set(exportDependency, new Set([module]));
} else {
set.add(module);
}
}
}
};
const notifyDependencies = () => {
const deps = dependencies.get(module);
if (deps !== undefined) {
for (const dep of deps) {
queue.enqueue(dep);
}
}
};
logger.time("figure out provided exports");
while (queue.length > 0) {
module = /** @type {Module} */ (queue.dequeue());
statQueueItemsProcessed++;
exportsInfo = moduleGraph.getExportsInfo(module);
cacheable = true;
changed = false;
exportsSpecsFromDependencies.clear();
moduleGraph.freeze();
processDependenciesBlock(module);
moduleGraph.unfreeze();
for (const [dep, exportsSpec] of exportsSpecsFromDependencies) {
processExportsSpec(dep, exportsSpec);
}
if (cacheable) {
modulesToStore.add(module);
}
if (changed) {
notifyDependencies();
}
}
logger.timeEnd("figure out provided exports");
logger.log(
`${Math.round(
(100 * (statFlaggedUncached + statNotCached)) /
(statRestoredFromMemCache +
statRestoredFromCache +
statNotCached +
statFlaggedUncached +
statNoExports)
)}% of exports of modules have been determined (${statNoExports} no declared exports, ${statNotCached} not cached, ${statFlaggedUncached} flagged uncacheable, ${statRestoredFromCache} from cache, ${statRestoredFromMemCache} from mem cache, ${
statQueueItemsProcessed - statNotCached - statFlaggedUncached
} additional calculations due to dependencies)`
);
logger.time("store provided exports into cache");
asyncLib.each(
modulesToStore,
(module, callback) => {
if (
typeof (
/** @type {BuildInfo} */
(module.buildInfo).hash
) !== "string"
) {
// not cacheable
return callback();
}
const cachedData = moduleGraph
.getExportsInfo(module)
.getRestoreProvidedData();
const memCache =
moduleMemCaches && moduleMemCaches.get(module);
if (memCache) {
memCache.set(this, cachedData);
}
cache.store(
module.identifier(),
/** @type {BuildInfo} */
(module.buildInfo).hash,
cachedData,
callback
);
},
(err) => {
logger.timeEnd("store provided exports into cache");
callback(err);
}
);
}
);
}
);
/** @type {WeakMap<Module, RestoreProvidedData>} */
const providedExportsCache = new WeakMap();
compilation.hooks.rebuildModule.tap(PLUGIN_NAME, (module) => {
providedExportsCache.set(
module,
moduleGraph.getExportsInfo(module).getRestoreProvidedData()
);
});
compilation.hooks.finishRebuildingModule.tap(PLUGIN_NAME, (module) => {
moduleGraph.getExportsInfo(module).restoreProvided(
/** @type {RestoreProvidedData} */
(providedExportsCache.get(module))
);
});
});
}
}
module.exports = FlagDependencyExportsPlugin;

352
node_modules/webpack/lib/FlagDependencyUsagePlugin.js generated vendored Normal file
View File

@@ -0,0 +1,352 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Dependency = require("./Dependency");
const { UsageState } = require("./ExportsInfo");
const ModuleGraphConnection = require("./ModuleGraphConnection");
const { STAGE_DEFAULT } = require("./OptimizationStages");
const ArrayQueue = require("./util/ArrayQueue");
const TupleQueue = require("./util/TupleQueue");
const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */
/** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
const { NO_EXPORTS_REFERENCED, EXPORTS_OBJECT_REFERENCED } = Dependency;
const PLUGIN_NAME = "FlagDependencyUsagePlugin";
const PLUGIN_LOGGER_NAME = `webpack.${PLUGIN_NAME}`;
class FlagDependencyUsagePlugin {
/**
* Creates an instance of FlagDependencyUsagePlugin.
* @param {boolean} global do a global analysis instead of per runtime
*/
constructor(global) {
/** @type {boolean} */
this.global = global;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.optimizeDependencies.tap(
{ name: PLUGIN_NAME, stage: STAGE_DEFAULT },
(modules) => {
if (compilation.moduleMemCaches) {
throw new Error(
"optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect"
);
}
const logger = compilation.getLogger(PLUGIN_LOGGER_NAME);
/** @type {Map<ExportsInfo, Module>} */
const exportInfoToModuleMap = new Map();
/** @type {TupleQueue<Module, RuntimeSpec>} */
const queue = new TupleQueue();
/**
* Process referenced module.
* @param {Module} module module to process
* @param {ReferencedExports} usedExports list of used exports
* @param {RuntimeSpec} runtime part of which runtime
* @param {boolean} forceSideEffects always apply side effects
* @returns {void}
*/
const processReferencedModule = (
module,
usedExports,
runtime,
forceSideEffects
) => {
const exportsInfo = moduleGraph.getExportsInfo(module);
if (usedExports.length > 0) {
if (!module.buildMeta || !module.buildMeta.exportsType) {
if (exportsInfo.setUsedWithoutInfo(runtime)) {
queue.enqueue(module, runtime);
}
return;
}
for (const usedExportInfo of usedExports) {
/** @type {string[]} */
let usedExport;
let canMangle = true;
if (Array.isArray(usedExportInfo)) {
usedExport = usedExportInfo;
} else {
usedExport = usedExportInfo.name;
canMangle = usedExportInfo.canMangle !== false;
}
if (usedExport.length === 0) {
if (exportsInfo.setUsedInUnknownWay(runtime)) {
queue.enqueue(module, runtime);
}
} else {
let currentExportsInfo = exportsInfo;
for (let i = 0; i < usedExport.length; i++) {
const exportInfo = currentExportsInfo.getExportInfo(
usedExport[i]
);
if (canMangle === false) {
exportInfo.canMangleUse = false;
}
const lastOne = i === usedExport.length - 1;
if (!lastOne) {
const nestedInfo = exportInfo.getNestedExportsInfo();
if (nestedInfo) {
if (
exportInfo.setUsedConditionally(
(used) => used === UsageState.Unused,
UsageState.OnlyPropertiesUsed,
runtime
)
) {
const currentModule =
currentExportsInfo === exportsInfo
? module
: exportInfoToModuleMap.get(currentExportsInfo);
if (currentModule) {
queue.enqueue(currentModule, runtime);
}
}
currentExportsInfo = nestedInfo;
continue;
}
}
if (
exportInfo.setUsedConditionally(
(v) => v !== UsageState.Used,
UsageState.Used,
runtime
)
) {
const currentModule =
currentExportsInfo === exportsInfo
? module
: exportInfoToModuleMap.get(currentExportsInfo);
if (currentModule) {
queue.enqueue(currentModule, runtime);
}
}
break;
}
}
}
} else {
// for a module without side effects we stop tracking usage here when no export is used
// This module won't be evaluated in this case
// TODO webpack 6 remove this check
if (
!forceSideEffects &&
module.factoryMeta !== undefined &&
module.factoryMeta.sideEffectFree
) {
return;
}
if (exportsInfo.setUsedForSideEffectsOnly(runtime)) {
queue.enqueue(module, runtime);
}
}
};
/**
* Processes the provided module.
* @param {DependenciesBlock} module the module
* @param {RuntimeSpec} runtime part of which runtime
* @param {boolean} forceSideEffects always apply side effects
* @returns {void}
*/
const processModule = (module, runtime, forceSideEffects) => {
/** @typedef {Map<string, string[] | ReferencedExport>} ExportMaps */
/** @type {Map<Module, ReferencedExports | ExportMaps>} */
const map = new Map();
/** @type {ArrayQueue<DependenciesBlock>} */
const queue = new ArrayQueue();
queue.enqueue(module);
for (;;) {
const block = queue.dequeue();
if (block === undefined) break;
for (const b of block.blocks) {
if (b.groupOptions && b.groupOptions.entryOptions) {
processModule(
b,
this.global
? undefined
: b.groupOptions.entryOptions.runtime || undefined,
true
);
} else {
queue.enqueue(b);
}
}
for (const dep of block.dependencies) {
const connection = moduleGraph.getConnection(dep);
if (!connection || !connection.module) {
continue;
}
const activeState = connection.getActiveState(runtime);
if (activeState === false) continue;
const { module } = connection;
if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) {
processModule(module, runtime, false);
continue;
}
const oldReferencedExports = map.get(module);
if (oldReferencedExports === EXPORTS_OBJECT_REFERENCED) {
continue;
}
const referencedExports =
compilation.getDependencyReferencedExports(dep, runtime);
if (
oldReferencedExports === undefined ||
oldReferencedExports === NO_EXPORTS_REFERENCED ||
referencedExports === EXPORTS_OBJECT_REFERENCED
) {
map.set(module, referencedExports);
} else if (
oldReferencedExports !== undefined &&
referencedExports === NO_EXPORTS_REFERENCED
) {
continue;
} else {
/** @type {undefined | ExportMaps} */
let exportsMap;
if (Array.isArray(oldReferencedExports)) {
exportsMap = new Map();
for (const item of oldReferencedExports) {
if (Array.isArray(item)) {
exportsMap.set(item.join("\n"), item);
} else {
exportsMap.set(item.name.join("\n"), item);
}
}
map.set(module, exportsMap);
} else {
exportsMap = oldReferencedExports;
}
for (const item of referencedExports) {
if (Array.isArray(item)) {
const key = item.join("\n");
const oldItem = exportsMap.get(key);
if (oldItem === undefined) {
exportsMap.set(key, item);
}
// if oldItem is already an array we have to do nothing
// if oldItem is an ReferencedExport object, we don't have to do anything
// as canMangle defaults to true for arrays
} else {
const key = item.name.join("\n");
const oldItem = exportsMap.get(key);
if (oldItem === undefined || Array.isArray(oldItem)) {
exportsMap.set(key, item);
} else {
exportsMap.set(key, {
name: item.name,
canMangle: item.canMangle && oldItem.canMangle
});
}
}
}
}
}
}
for (const [module, referencedExports] of map) {
if (Array.isArray(referencedExports)) {
processReferencedModule(
module,
referencedExports,
runtime,
forceSideEffects
);
} else {
processReferencedModule(
module,
[...referencedExports.values()],
runtime,
forceSideEffects
);
}
}
};
logger.time("initialize exports usage");
for (const module of modules) {
const exportsInfo = moduleGraph.getExportsInfo(module);
exportInfoToModuleMap.set(exportsInfo, module);
exportsInfo.setHasUseInfo();
}
logger.timeEnd("initialize exports usage");
logger.time("trace exports usage in graph");
/**
* Process entry dependency.
* @param {Dependency} dep dependency
* @param {RuntimeSpec} runtime runtime
*/
const processEntryDependency = (dep, runtime) => {
const module = moduleGraph.getModule(dep);
if (module) {
processReferencedModule(
module,
NO_EXPORTS_REFERENCED,
runtime,
true
);
}
};
/** @type {RuntimeSpec} */
let globalRuntime;
for (const [
entryName,
{ dependencies: deps, includeDependencies: includeDeps, options }
] of compilation.entries) {
const runtime = this.global
? undefined
: getEntryRuntime(compilation, entryName, options);
for (const dep of deps) {
processEntryDependency(dep, runtime);
}
for (const dep of includeDeps) {
processEntryDependency(dep, runtime);
}
globalRuntime = mergeRuntimeOwned(globalRuntime, runtime);
}
for (const dep of compilation.globalEntry.dependencies) {
processEntryDependency(dep, globalRuntime);
}
for (const dep of compilation.globalEntry.includeDependencies) {
processEntryDependency(dep, globalRuntime);
}
while (queue.length) {
const [module, runtime] = /** @type {[Module, RuntimeSpec]} */ (
queue.dequeue()
);
processModule(module, runtime, false);
}
logger.timeEnd("trace exports usage in graph");
}
);
});
}
}
module.exports = FlagDependencyUsagePlugin;

View File

@@ -0,0 +1,57 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { getEntryRuntime } = require("./util/runtime");
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "FlagEntryExportAsUsedPlugin";
class FlagEntryExportAsUsedPlugin {
/**
* Creates an instance of FlagEntryExportAsUsedPlugin.
* @param {boolean} nsObjectUsed true, if the ns object is used
* @param {string} explanation explanation for the reason
*/
constructor(nsObjectUsed, explanation) {
this.nsObjectUsed = nsObjectUsed;
this.explanation = explanation;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.seal.tap(PLUGIN_NAME, () => {
for (const [
entryName,
{ dependencies: deps, options }
] of compilation.entries) {
const runtime = getEntryRuntime(compilation, entryName, options);
for (const dep of deps) {
const module = moduleGraph.getModule(dep);
if (module) {
const exportsInfo = moduleGraph.getExportsInfo(module);
if (this.nsObjectUsed) {
exportsInfo.setUsedInUnknownWay(runtime);
} else {
exportsInfo.setAllKnownExportsUsed(runtime);
}
moduleGraph.addExtraReason(module, this.explanation);
}
}
}
});
});
}
}
module.exports = FlagEntryExportAsUsedPlugin;

201
node_modules/webpack/lib/Generator.js generated vendored Normal file
View File

@@ -0,0 +1,201 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { JAVASCRIPT_TYPE } = require("./ModuleSourceTypeConstants");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./ConcatenationScope")} ConcatenationScope */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @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 */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* Defines the generate context type used by this module.
* @typedef {object} GenerateContext
* @property {DependencyTemplates} dependencyTemplates mapping from dependencies to templates
* @property {RuntimeTemplate} runtimeTemplate the runtime template
* @property {ModuleGraph} moduleGraph the module graph
* @property {ChunkGraph} chunkGraph the chunk graph
* @property {RuntimeRequirements} runtimeRequirements the requirements for runtime
* @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 {SourceType} type which kind of code should be generated
* @property {() => CodeGenerationResultData=} getData get access to the code generation data
*/
/**
* Defines the generate error fn callback.
* @callback GenerateErrorFn
* @param {Error} error the error
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
/**
* Represents the generator runtime component.
* @typedef {object} UpdateHashContext
* @property {NormalModule} module the module
* @property {ChunkGraph} chunkGraph
* @property {RuntimeSpec} runtime
* @property {RuntimeTemplate=} runtimeTemplate
*/
class Generator {
/**
* Returns generator by type.
* @param {{ [key in SourceType]?: Generator }} map map of types
* @returns {ByTypeGenerator} generator by type
*/
static byType(map) {
return new ByTypeGenerator(map);
}
/* istanbul ignore next */
/**
* Returns the source types available for this module.
* @abstract
* @param {NormalModule} module fresh module
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
const AbstractMethodError = require("./errors/AbstractMethodError");
throw new AbstractMethodError();
}
/* istanbul ignore next */
/**
* Returns the estimated size for the requested source type.
* @abstract
* @param {NormalModule} module the module
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
const AbstractMethodError = require("./errors/AbstractMethodError");
throw new AbstractMethodError();
}
/* istanbul ignore next */
/**
* Generates generated code for this runtime module.
* @abstract
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generate(
module,
{ dependencyTemplates, runtimeTemplate, moduleGraph, type }
) {
const AbstractMethodError = require("./errors/AbstractMethodError");
throw new AbstractMethodError();
}
/**
* Returns the reason this module cannot be concatenated, when one exists.
* @param {NormalModule} module module for which the bailout reason should be determined
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason(module, context) {
return `Module Concatenation is not implemented for ${this.constructor.name}`;
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash hash that will be modified
* @param {UpdateHashContext} updateHashContext context for updating hash
*/
updateHash(hash, { module, runtime }) {
// no nothing
}
}
/**
* @this {ByTypeGenerator}
* @type {GenerateErrorFn}
*/
function generateError(error, module, generateContext) {
const type = generateContext.type;
const generator =
/** @type {Generator & { generateError?: GenerateErrorFn }} */
(this.map[type]);
if (!generator) {
throw new Error(`Generator.byType: no generator specified for ${type}`);
}
if (typeof generator.generateError === "undefined") {
return null;
}
return generator.generateError(error, module, generateContext);
}
class ByTypeGenerator extends Generator {
/**
* Creates an instance of ByTypeGenerator.
* @param {{ [key in SourceType]?: Generator }} map map of types
*/
constructor(map) {
super();
this.map = map;
this._types = /** @type {SourceTypes} */ (new Set(Object.keys(map)));
/** @type {GenerateErrorFn | undefined} */
this.generateError = generateError.bind(this);
}
/**
* Returns the source types available for this module.
* @param {NormalModule} module fresh module
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
return this._types;
}
/**
* Returns the estimated size for the requested source type.
* @param {NormalModule} module the module
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type = JAVASCRIPT_TYPE) {
const t = type;
const generator = this.map[t];
return generator ? generator.getSize(module, t) : 0;
}
/**
* Generates generated code for this runtime module.
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generate(module, generateContext) {
const type = generateContext.type;
const generator = this.map[type];
if (!generator) {
throw new Error(`Generator.byType: no generator specified for ${type}`);
}
return generator.generate(module, generateContext);
}
}
module.exports = Generator;

956
node_modules/webpack/lib/HotModuleReplacementPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,956 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncBailHook } = require("tapable");
const { RawSource } = require("webpack-sources");
const ChunkGraph = require("./ChunkGraph");
const Compilation = require("./Compilation");
const HotUpdateChunk = require("./HotUpdateChunk");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM,
WEBPACK_MODULE_TYPE_RUNTIME
} = require("./ModuleTypeConstants");
const NormalModule = require("./NormalModule");
const RuntimeGlobals = require("./RuntimeGlobals");
const { chunkHasCss } = require("./css/CssModulesPlugin");
const ConstDependency = require("./dependencies/ConstDependency");
const ImportMetaHotAcceptDependency = require("./dependencies/ImportMetaHotAcceptDependency");
const ImportMetaHotDeclineDependency = require("./dependencies/ImportMetaHotDeclineDependency");
const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
const WebpackError = require("./errors/WebpackError");
const HotModuleReplacementRuntimeModule = require("./hmr/HotModuleReplacementRuntimeModule");
const JavascriptParser = require("./javascript/JavascriptParser");
const {
evaluateToIdentifier
} = require("./javascript/JavascriptParserHelpers");
const ConcatenatedModule = require("./optimize/ConcatenatedModule");
const { find, isSubset } = require("./util/SetHelpers");
const TupleSet = require("./util/TupleSet");
const { compareModulesById } = require("./util/comparators");
const {
forEachRuntime,
getRuntimeKey,
intersectRuntime,
keyToRuntime,
mergeRuntimeOwned,
subtractRuntime
} = require("./util/runtime");
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").SpreadElement} SpreadElement */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").Records} Records */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./RuntimeModule")} RuntimeModule */
/** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {string[]} Requests */
/**
* Defines the hmr javascript parser hooks type used by this module.
* @typedef {object} HMRJavascriptParserHooks
* @property {SyncBailHook<[Expression | SpreadElement, Requests], void>} hotAcceptCallback
* @property {SyncBailHook<[CallExpression, Requests], void>} hotAcceptWithoutCallback
*/
/** @typedef {number} HotIndex */
/** @typedef {Record<string, string>} FullHashChunkModuleHashes */
/** @typedef {Record<string, string>} ChunkModuleHashes */
/** @typedef {Record<ChunkId, string>} ChunkHashes */
/** @typedef {Record<ChunkId, string>} ChunkRuntime */
/** @typedef {Record<ChunkId, ModuleId[]>} ChunkModuleIds */
/** @typedef {Set<ChunkId>} ChunkIds */
/** @typedef {Set<Module>} ModuleSet */
/** @typedef {{ updatedChunkIds: ChunkIds, removedChunkIds: ChunkIds, removedModules: ModuleSet, filename: string, assetInfo: AssetInfo }} HotUpdateMainContentByRuntimeItem */
/** @typedef {Map<string, HotUpdateMainContentByRuntimeItem>} HotUpdateMainContentByRuntime */
/** @type {WeakMap<JavascriptParser, HMRJavascriptParserHooks>} */
const parserHooksMap = new WeakMap();
const PLUGIN_NAME = "HotModuleReplacementPlugin";
class HotModuleReplacementPlugin {
/**
* Returns the attached hooks.
* @param {JavascriptParser} parser the parser
* @returns {HMRJavascriptParserHooks} the attached hooks
*/
static getParserHooks(parser) {
if (!(parser instanceof JavascriptParser)) {
throw new TypeError(
"The 'parser' argument must be an instance of JavascriptParser"
);
}
let hooks = parserHooksMap.get(parser);
if (hooks === undefined) {
hooks = {
hotAcceptCallback: new SyncBailHook(["expression", "requests"]),
hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"])
};
parserHooksMap.set(parser, hooks);
}
return hooks;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { _backCompat: backCompat } = compiler;
if (compiler.options.output.strictModuleErrorHandling === undefined) {
compiler.options.output.strictModuleErrorHandling = true;
}
const runtimeRequirements = [RuntimeGlobals.module];
/**
* Creates an accept handler.
* @param {JavascriptParser} parser the parser
* @param {typeof ModuleHotAcceptDependency} ParamDependency dependency
* @returns {(expr: CallExpression) => boolean | undefined} callback
*/
const createAcceptHandler = (parser, ParamDependency) => {
const { hotAcceptCallback, hotAcceptWithoutCallback } =
HotModuleReplacementPlugin.getParserHooks(parser);
return (expr) => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot.accept`,
/** @type {Range} */ (expr.callee.range),
runtimeRequirements
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
module.addPresentationalDependency(dep);
/** @type {BuildInfo} */
(module.buildInfo).moduleConcatenationBailout =
"Hot Module Replacement";
if (expr.arguments.length >= 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
/** @type {BasicEvaluatedExpression[]} */
let params = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params =
/** @type {BasicEvaluatedExpression[]} */
(arg.items).filter((param) => param.isString());
}
/** @type {Requests} */
const requests = [];
if (params.length > 0) {
for (const [idx, param] of params.entries()) {
const request = /** @type {string} */ (param.string);
const dep = new ParamDependency(
request,
/** @type {Range} */ (param.range)
);
dep.optional = true;
dep.loc = Object.create(
/** @type {DependencyLocation} */ (expr.loc)
);
dep.loc.index = idx;
module.addDependency(dep);
requests.push(request);
}
if (expr.arguments.length > 1) {
hotAcceptCallback.call(expr.arguments[1], requests);
for (let i = 1; i < expr.arguments.length; i++) {
parser.walkExpression(expr.arguments[i]);
}
return true;
}
hotAcceptWithoutCallback.call(expr, requests);
return true;
}
}
parser.walkExpressions(expr.arguments);
return true;
};
};
/**
* Creates a decline handler.
* @param {JavascriptParser} parser the parser
* @param {typeof ModuleHotDeclineDependency} ParamDependency dependency
* @returns {(expr: CallExpression) => boolean | undefined} callback
*/
const createDeclineHandler = (parser, ParamDependency) => (expr) => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot.decline`,
/** @type {Range} */ (expr.callee.range),
runtimeRequirements
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
module.addPresentationalDependency(dep);
/** @type {BuildInfo} */
(module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement";
if (expr.arguments.length === 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
/** @type {BasicEvaluatedExpression[]} */
let params = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params =
/** @type {BasicEvaluatedExpression[]} */
(arg.items).filter((param) => param.isString());
}
for (const [idx, param] of params.entries()) {
const dep = new ParamDependency(
/** @type {string} */ (param.string),
/** @type {Range} */ (param.range)
);
dep.optional = true;
dep.loc = Object.create(/** @type {DependencyLocation} */ (expr.loc));
dep.loc.index = idx;
module.addDependency(dep);
}
}
return true;
};
/**
* Creates a hmr expression handler.
* @param {JavascriptParser} parser the parser
* @returns {(expr: Expression) => boolean | undefined} callback
*/
const createHMRExpressionHandler = (parser) => (expr) => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot`,
/** @type {Range} */ (expr.range),
runtimeRequirements
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
module.addPresentationalDependency(dep);
/** @type {BuildInfo} */
(module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement";
return true;
};
/**
* Processes the provided parser.
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const applyModuleHot = (parser) => {
parser.hooks.evaluateIdentifier.for("module.hot").tap(
{
name: PLUGIN_NAME,
before: "NodeStuffPlugin"
},
(expr) =>
evaluateToIdentifier(
"module.hot",
"module",
() => ["hot"],
true
)(expr)
);
parser.hooks.call
.for("module.hot.accept")
.tap(
PLUGIN_NAME,
createAcceptHandler(parser, ModuleHotAcceptDependency)
);
parser.hooks.call
.for("module.hot.decline")
.tap(
PLUGIN_NAME,
createDeclineHandler(parser, ModuleHotDeclineDependency)
);
parser.hooks.expression
.for("module.hot")
.tap(PLUGIN_NAME, createHMRExpressionHandler(parser));
};
/**
* Apply import meta hot.
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const applyImportMetaHot = (parser) => {
parser.hooks.evaluateIdentifier
.for("import.meta.webpackHot")
.tap(PLUGIN_NAME, (expr) =>
evaluateToIdentifier(
"import.meta.webpackHot",
"import.meta",
() => ["webpackHot"],
true
)(expr)
);
parser.hooks.call
.for("import.meta.webpackHot.accept")
.tap(
PLUGIN_NAME,
createAcceptHandler(parser, ImportMetaHotAcceptDependency)
);
parser.hooks.call
.for("import.meta.webpackHot.decline")
.tap(
PLUGIN_NAME,
createDeclineHandler(parser, ImportMetaHotDeclineDependency)
);
parser.hooks.expression
.for("import.meta.webpackHot")
.tap(PLUGIN_NAME, createHMRExpressionHandler(parser));
};
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
// This applies the HMR plugin only to the targeted compiler
// It should not affect child compilations
if (compilation.compiler !== compiler) return;
// #region module.hot.* API
compilation.dependencyFactories.set(
ModuleHotAcceptDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotAcceptDependency,
new ModuleHotAcceptDependency.Template()
);
compilation.dependencyFactories.set(
ModuleHotDeclineDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotDeclineDependency,
new ModuleHotDeclineDependency.Template()
);
// #endregion
// #region import.meta.webpackHot.* API
compilation.dependencyFactories.set(
ImportMetaHotAcceptDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ImportMetaHotAcceptDependency,
new ImportMetaHotAcceptDependency.Template()
);
compilation.dependencyFactories.set(
ImportMetaHotDeclineDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ImportMetaHotDeclineDependency,
new ImportMetaHotDeclineDependency.Template()
);
// #endregion
/** @type {HotIndex} */
let hotIndex = 0;
/** @type {FullHashChunkModuleHashes} */
const fullHashChunkModuleHashes = {};
/** @type {ChunkModuleHashes} */
const chunkModuleHashes = {};
compilation.hooks.record.tap(PLUGIN_NAME, (compilation, records) => {
if (records.hash === compilation.hash) return;
const chunkGraph = compilation.chunkGraph;
records.hash = compilation.hash;
records.hotIndex = hotIndex;
records.fullHashChunkModuleHashes = fullHashChunkModuleHashes;
records.chunkModuleHashes = chunkModuleHashes;
records.chunkHashes = {};
records.chunkRuntime = {};
for (const chunk of compilation.chunks) {
const chunkId = /** @type {ChunkId} */ (chunk.id);
records.chunkHashes[chunkId] = /** @type {string} */ (chunk.hash);
records.chunkRuntime[chunkId] = getRuntimeKey(chunk.runtime);
}
records.chunkModuleIds = {};
for (const chunk of compilation.chunks) {
const chunkId = /** @type {ChunkId} */ (chunk.id);
/** @type {ModuleId[]} */
const moduleIds = [];
for (const m of chunkGraph.getOrderedChunkModulesIterable(
chunk,
compareModulesById(chunkGraph)
)) {
moduleIds.push(
/** @type {ModuleId} */ (chunkGraph.getModuleId(m))
);
if (m instanceof ConcatenatedModule && m.modules) {
for (const innerModule of m.modules) {
if (
innerModule.buildMeta &&
innerModule.buildMeta.needIdInConcatenation
) {
const innerId = chunkGraph.getModuleId(innerModule);
if (innerId !== null) {
moduleIds.push(innerId);
}
}
}
}
}
records.chunkModuleIds[chunkId] = moduleIds;
}
});
/** @type {TupleSet<Module, Chunk>} */
const updatedModules = new TupleSet();
/** @type {TupleSet<Module, Chunk>} */
const fullHashModules = new TupleSet();
/** @type {TupleSet<Module, RuntimeSpec>} */
const nonCodeGeneratedModules = new TupleSet();
compilation.hooks.fullHash.tap(PLUGIN_NAME, (hash) => {
const chunkGraph = compilation.chunkGraph;
const records = /** @type {Records} */ (compilation.records);
for (const chunk of compilation.chunks) {
/**
* Returns module hash.
* @param {Module} module module
* @returns {string} module hash
*/
const getModuleHash = (module) => {
const codeGenerationResults =
/** @type {CodeGenerationResults} */
(compilation.codeGenerationResults);
if (codeGenerationResults.has(module, chunk.runtime)) {
return codeGenerationResults.getHash(module, chunk.runtime);
}
nonCodeGeneratedModules.add(module, chunk.runtime);
return chunkGraph.getModuleHash(module, chunk.runtime);
};
const fullHashModulesInThisChunk =
chunkGraph.getChunkFullHashModulesSet(chunk);
if (fullHashModulesInThisChunk !== undefined) {
for (const module of fullHashModulesInThisChunk) {
fullHashModules.add(module, chunk);
}
}
const modules = chunkGraph.getChunkModulesIterable(chunk);
if (modules !== undefined) {
if (records.chunkModuleHashes) {
if (fullHashModulesInThisChunk !== undefined) {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (
fullHashModulesInThisChunk.has(
/** @type {RuntimeModule} */
(module)
)
) {
if (
/** @type {FullHashChunkModuleHashes} */
(records.fullHashChunkModuleHashes)[key] !== hash
) {
updatedModules.add(module, chunk);
}
fullHashChunkModuleHashes[key] = hash;
} else {
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
chunkModuleHashes[key] = hash;
}
}
} else {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
chunkModuleHashes[key] = hash;
}
}
} else if (fullHashModulesInThisChunk !== undefined) {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (
fullHashModulesInThisChunk.has(
/** @type {RuntimeModule} */ (module)
)
) {
fullHashChunkModuleHashes[key] = hash;
} else {
chunkModuleHashes[key] = hash;
}
}
} else {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
chunkModuleHashes[key] = hash;
}
}
}
}
hotIndex = records.hotIndex || 0;
if (updatedModules.size > 0) hotIndex++;
hash.update(`${hotIndex}`);
});
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
},
() => {
const chunkGraph = compilation.chunkGraph;
const records = /** @type {Records} */ (compilation.records);
if (records.hash === compilation.hash) return;
if (
!records.chunkModuleHashes ||
!records.chunkHashes ||
!records.chunkModuleIds
) {
return;
}
const codeGenerationResults =
/** @type {CodeGenerationResults} */
(compilation.codeGenerationResults);
for (const [module, chunk] of fullHashModules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = nonCodeGeneratedModules.has(module, chunk.runtime)
? chunkGraph.getModuleHash(module, chunk.runtime)
: codeGenerationResults.getHash(module, chunk.runtime);
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
chunkModuleHashes[key] = hash;
}
/** @type {HotUpdateMainContentByRuntime} */
const hotUpdateMainContentByRuntime = new Map();
/** @type {RuntimeSpec} */
let allOldRuntime;
const chunkRuntime =
/** @type {ChunkRuntime} */
(records.chunkRuntime);
for (const key of Object.keys(chunkRuntime)) {
const runtime = keyToRuntime(chunkRuntime[key]);
allOldRuntime = mergeRuntimeOwned(allOldRuntime, runtime);
}
forEachRuntime(allOldRuntime, (runtime) => {
const { path: filename, info: assetInfo } =
compilation.getPathWithInfo(
compilation.outputOptions.hotUpdateMainFilename,
{
hash: records.hash,
runtime
}
);
hotUpdateMainContentByRuntime.set(
/** @type {string} */ (runtime),
{
/** @type {ChunkIds} */
updatedChunkIds: new Set(),
/** @type {ChunkIds} */
removedChunkIds: new Set(),
/** @type {ModuleSet} */
removedModules: new Set(),
filename,
assetInfo
}
);
});
if (hotUpdateMainContentByRuntime.size === 0) return;
// Create a list of all active modules to verify which modules are removed completely
/** @type {Map<ModuleId, Module>} */
const allModules = new Map();
for (const module of compilation.modules) {
const id =
/** @type {ModuleId} */
(chunkGraph.getModuleId(module));
allModules.set(id, module);
}
// List of completely removed modules
/** @type {Set<ModuleId>} */
const completelyRemovedModules = new Set();
for (const key of Object.keys(records.chunkHashes)) {
const oldRuntime = keyToRuntime(
/** @type {ChunkRuntime} */
(records.chunkRuntime)[key]
);
/** @type {Module[]} */
const remainingModules = [];
// Check which modules are removed
for (const id of records.chunkModuleIds[key]) {
const module = allModules.get(id);
if (module === undefined) {
completelyRemovedModules.add(id);
} else {
remainingModules.push(module);
}
}
/** @type {ChunkId | null} */
let chunkId;
/** @type {undefined | Module[]} */
let newModules;
/** @type {undefined | RuntimeModule[]} */
let newRuntimeModules;
/** @type {undefined | RuntimeModule[]} */
let newFullHashModules;
/** @type {undefined | RuntimeModule[]} */
let newDependentHashModules;
/** @type {RuntimeSpec} */
let newRuntime;
/** @type {RuntimeSpec} */
let removedFromRuntime;
const currentChunk = find(
compilation.chunks,
(chunk) => `${chunk.id}` === key
);
if (currentChunk) {
chunkId = currentChunk.id;
newRuntime = intersectRuntime(
currentChunk.runtime,
allOldRuntime
);
if (newRuntime === undefined) continue;
newModules = chunkGraph
.getChunkModules(currentChunk)
.filter((module) => updatedModules.has(module, currentChunk));
newRuntimeModules = [
...chunkGraph.getChunkRuntimeModulesIterable(currentChunk)
].filter((module) => updatedModules.has(module, currentChunk));
const fullHashModules =
chunkGraph.getChunkFullHashModulesIterable(currentChunk);
newFullHashModules =
fullHashModules &&
[...fullHashModules].filter((module) =>
updatedModules.has(module, currentChunk)
);
const dependentHashModules =
chunkGraph.getChunkDependentHashModulesIterable(currentChunk);
newDependentHashModules =
dependentHashModules &&
[...dependentHashModules].filter((module) =>
updatedModules.has(module, currentChunk)
);
removedFromRuntime = subtractRuntime(oldRuntime, newRuntime);
} else {
// chunk has completely removed
chunkId = `${Number(key)}` === key ? Number(key) : key;
removedFromRuntime = oldRuntime;
newRuntime = oldRuntime;
}
if (removedFromRuntime) {
// chunk was removed from some runtimes
forEachRuntime(removedFromRuntime, (runtime) => {
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */
(
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.removedChunkIds.add(/** @type {ChunkId} */ (chunkId));
});
// dispose modules from the chunk in these runtimes
// where they are no longer in this runtime
for (const module of remainingModules) {
const moduleKey = `${key}|${module.identifier()}`;
const oldHash = records.chunkModuleHashes[moduleKey];
const runtimes = chunkGraph.getModuleRuntimes(module);
if (oldRuntime === newRuntime && runtimes.has(newRuntime)) {
// Module is still in the same runtime combination
const hash = nonCodeGeneratedModules.has(module, newRuntime)
? chunkGraph.getModuleHash(module, newRuntime)
: codeGenerationResults.getHash(module, newRuntime);
if (hash !== oldHash) {
if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) {
newRuntimeModules = newRuntimeModules || [];
newRuntimeModules.push(
/** @type {RuntimeModule} */ (module)
);
} else {
newModules = newModules || [];
newModules.push(module);
}
}
} else {
// module is no longer in this runtime combination
// We (incorrectly) assume that it's not in an overlapping runtime combination
// and dispose it from the main runtimes the chunk was removed from
forEachRuntime(removedFromRuntime, (runtime) => {
// If the module is still used in this runtime, do not dispose it
// This could create a bad runtime state where the module is still loaded,
// but no chunk which contains it. This means we don't receive further HMR updates
// to this module and that's bad.
// TODO force load one of the chunks which contains the module
for (const moduleRuntime of runtimes) {
if (typeof moduleRuntime === "string") {
if (moduleRuntime === runtime) return;
} else if (
moduleRuntime !== undefined &&
moduleRuntime.has(/** @type {string} */ (runtime))
) {
return;
}
}
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */ (
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.removedModules.add(module);
});
}
}
}
if (
(newModules && newModules.length > 0) ||
(newRuntimeModules && newRuntimeModules.length > 0)
) {
const hotUpdateChunk = new HotUpdateChunk();
if (backCompat) {
ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph);
}
hotUpdateChunk.id = chunkId;
hotUpdateChunk.runtime = currentChunk
? currentChunk.runtime
: newRuntime;
if (currentChunk) {
for (const group of currentChunk.groupsIterable) {
hotUpdateChunk.addGroup(group);
}
}
chunkGraph.attachModules(hotUpdateChunk, newModules || []);
chunkGraph.attachRuntimeModules(
hotUpdateChunk,
newRuntimeModules || []
);
if (newFullHashModules) {
chunkGraph.attachFullHashModules(
hotUpdateChunk,
newFullHashModules
);
}
if (newDependentHashModules) {
chunkGraph.attachDependentHashModules(
hotUpdateChunk,
newDependentHashModules
);
}
const renderManifest = compilation.getRenderManifest({
chunk: hotUpdateChunk,
hash: /** @type {string} */ (records.hash),
fullHash: /** @type {string} */ (records.hash),
outputOptions: compilation.outputOptions,
moduleTemplates: compilation.moduleTemplates,
dependencyTemplates: compilation.dependencyTemplates,
codeGenerationResults: /** @type {CodeGenerationResults} */ (
compilation.codeGenerationResults
),
runtimeTemplate: compilation.runtimeTemplate,
moduleGraph: compilation.moduleGraph,
chunkGraph
});
for (const entry of renderManifest) {
/** @type {string} */
let filename;
/** @type {AssetInfo} */
let assetInfo;
if ("filename" in entry) {
filename = entry.filename;
assetInfo = entry.info;
} else {
({ path: filename, info: assetInfo } =
compilation.getPathWithInfo(
entry.filenameTemplate,
entry.pathOptions
));
}
const source = entry.render();
compilation.additionalChunkAssets.push(filename);
compilation.emitAsset(filename, source, {
hotModuleReplacement: true,
...assetInfo
});
if (currentChunk) {
currentChunk.files.add(filename);
compilation.hooks.chunkAsset.call(currentChunk, filename);
}
}
forEachRuntime(newRuntime, (runtime) => {
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */ (
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.updatedChunkIds.add(/** @type {ChunkId} */ (chunkId));
});
}
}
const completelyRemovedModulesArray = [...completelyRemovedModules];
/** @type {Map<string, Omit<HotUpdateMainContentByRuntimeItem, "filename">>} */
const hotUpdateMainContentByFilename = new Map();
for (const {
removedChunkIds,
removedModules,
updatedChunkIds,
filename,
assetInfo
} of hotUpdateMainContentByRuntime.values()) {
const old = hotUpdateMainContentByFilename.get(filename);
if (
old &&
(!isSubset(old.removedChunkIds, removedChunkIds) ||
!isSubset(old.removedModules, removedModules) ||
!isSubset(old.updatedChunkIds, updatedChunkIds))
) {
compilation.warnings.push(
new WebpackError(`HotModuleReplacementPlugin
The configured output.hotUpdateMainFilename doesn't lead to unique filenames per runtime and HMR update differs between runtimes.
This might lead to incorrect runtime behavior of the applied update.
To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename option, or use the default config.`)
);
for (const chunkId of removedChunkIds) {
old.removedChunkIds.add(chunkId);
}
for (const chunkId of removedModules) {
old.removedModules.add(chunkId);
}
for (const chunkId of updatedChunkIds) {
old.updatedChunkIds.add(chunkId);
}
continue;
}
hotUpdateMainContentByFilename.set(filename, {
removedChunkIds,
removedModules,
updatedChunkIds,
assetInfo
});
}
for (const [
filename,
{ removedChunkIds, removedModules, updatedChunkIds, assetInfo }
] of hotUpdateMainContentByFilename) {
/** @type {{ c: ChunkId[], r: ChunkId[], m: ModuleId[], css?: { r: ChunkId[] } }} */
const hotUpdateMainJson = {
c: [...updatedChunkIds],
r: [...removedChunkIds],
m:
removedModules.size === 0
? completelyRemovedModulesArray
: [
...completelyRemovedModulesArray,
...Array.from(
removedModules,
(m) =>
/** @type {ModuleId} */ (chunkGraph.getModuleId(m))
)
]
};
// 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)
);
compilation.emitAsset(filename, source, {
hotModuleReplacement: true,
...assetInfo
});
}
}
);
compilation.hooks.additionalTreeRuntimeRequirements.tap(
PLUGIN_NAME,
(chunk, runtimeRequirements) => {
runtimeRequirements.add(RuntimeGlobals.hmrDownloadManifest);
runtimeRequirements.add(RuntimeGlobals.hmrDownloadUpdateHandlers);
runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
runtimeRequirements.add(RuntimeGlobals.moduleCache);
compilation.addRuntimeModule(
chunk,
new HotModuleReplacementRuntimeModule()
);
}
);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, (parser) => {
applyModuleHot(parser);
applyImportMetaHot(parser);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, (parser) => {
applyModuleHot(parser);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, (parser) => {
applyImportMetaHot(parser);
});
normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module) => {
module.hot = true;
return module;
});
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
(context) => {
context.hot = true;
}
);
}
);
}
}
module.exports = HotModuleReplacementPlugin;

16
node_modules/webpack/lib/HotUpdateChunk.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Chunk = require("./Chunk");
class HotUpdateChunk extends Chunk {
constructor() {
super();
}
}
module.exports = HotUpdateChunk;

108
node_modules/webpack/lib/IgnorePlugin.js generated vendored Normal file
View File

@@ -0,0 +1,108 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RawModule = require("./RawModule");
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */
/** @typedef {import("./ContextModuleFactory").BeforeContextResolveData} BeforeContextResolveData */
/** @typedef {(resource: string, context: string) => boolean} CheckResourceFn */
const PLUGIN_NAME = "IgnorePlugin";
class IgnorePlugin {
/**
* Creates an instance of IgnorePlugin.
* @param {IgnorePluginOptions} options IgnorePlugin options
*/
constructor(options) {
this.options = options;
this.checkIgnore = this.checkIgnore.bind(this);
}
/**
* Note that if "contextRegExp" is given, both the "resourceRegExp" and "contextRegExp" have to match.
* @param {ResolveData | BeforeContextResolveData} resolveData resolve data
* @returns {false | undefined} returns false when the request should be ignored, otherwise undefined
*/
checkIgnore(resolveData) {
if (
"checkResource" in this.options &&
this.options.checkResource &&
this.options.checkResource(resolveData.request, resolveData.context)
) {
return false;
}
if (
"resourceRegExp" in this.options &&
this.options.resourceRegExp &&
this.options.resourceRegExp.test(resolveData.request)
) {
if ("contextRegExp" in this.options && this.options.contextRegExp) {
// if "contextRegExp" is given,
// both the "resourceRegExp" and "contextRegExp" have to match.
if (this.options.contextRegExp.test(resolveData.context)) {
return false;
}
} else {
return false;
}
}
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
/** @type {EXPECTED_ANY} */
(require("../schemas/plugins/IgnorePlugin.json")),
this.options,
{
name: "Ignore Plugin",
baseDataPath: "options"
},
(options) => require("../schemas/plugins/IgnorePlugin.check")(options)
);
});
compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => {
nmf.hooks.beforeResolve.tap(PLUGIN_NAME, (resolveData) => {
const result = this.checkIgnore(resolveData);
if (
result === false &&
resolveData.dependencies.length > 0 &&
resolveData.dependencies[0] instanceof EntryDependency
) {
const module = new RawModule(
"",
"ignored-entry-module",
"(ignored-entry-module)"
);
module.factoryMeta = { sideEffectFree: true };
resolveData.ignoredModule = module;
}
return result;
});
});
compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => {
cmf.hooks.beforeResolve.tap(PLUGIN_NAME, this.checkIgnore);
});
}
}
module.exports = IgnorePlugin;

42
node_modules/webpack/lib/IgnoreWarningsPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {(warning: Error, compilation: Compilation) => boolean} IgnoreFn */
const PLUGIN_NAME = "IgnoreWarningsPlugin";
class IgnoreWarningsPlugin {
/**
* Creates an instance of IgnoreWarningsPlugin.
* @param {IgnoreFn[]} ignoreWarnings conditions to ignore warnings
*/
constructor(ignoreWarnings) {
/** @type {IgnoreFn[]} */
this._ignoreWarnings = ignoreWarnings;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processWarnings.tap(PLUGIN_NAME, (warnings) =>
warnings.filter(
(warning) =>
!this._ignoreWarnings.some((ignore) => ignore(warning, compilation))
)
);
});
}
}
module.exports = IgnoreWarningsPlugin;

214
node_modules/webpack/lib/InitFragment.js generated vendored Normal file
View File

@@ -0,0 +1,214 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Florent Cailhol @ooflorent
*/
"use strict";
const { ConcatSource } = require("webpack-sources");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {string} InitFragmentKey */
/**
* Defines the maybe mergeable init fragment type used by this module.
* @template GenerateContext
* @typedef {object} MaybeMergeableInitFragment
* @property {InitFragmentKey=} key
* @property {number} stage
* @property {number} position
* @property {(context: GenerateContext) => string | Source | undefined} getContent
* @property {(context: GenerateContext) => string | Source | undefined} getEndContent
* @property {(fragments: MaybeMergeableInitFragment<GenerateContext>) => MaybeMergeableInitFragment<GenerateContext>=} merge
* @property {(fragments: MaybeMergeableInitFragment<GenerateContext>[]) => MaybeMergeableInitFragment<GenerateContext>[]=} mergeAll
*/
/**
* Extract fragment index.
* @template T
* @param {T} fragment the init fragment
* @param {number} index index
* @returns {[T, number]} tuple with both
*/
const extractFragmentIndex = (fragment, index) => [fragment, index];
/**
* Sorts fragment with index.
* @template T
* @param {[MaybeMergeableInitFragment<T>, number]} a first pair
* @param {[MaybeMergeableInitFragment<T>, number]} b second pair
* @returns {number} sort value
*/
const sortFragmentWithIndex = ([a, i], [b, j]) => {
const stageCmp = a.stage - b.stage;
if (stageCmp !== 0) return stageCmp;
const positionCmp = a.position - b.position;
if (positionCmp !== 0) return positionCmp;
return i - j;
};
/**
* Represents InitFragment.
* @template GenerateContext
* @implements {MaybeMergeableInitFragment<GenerateContext>}
*/
class InitFragment {
/**
* Creates an instance of InitFragment.
* @param {string | Source | undefined} content the source code that will be included as initialization code
* @param {number} stage category of initialization code (contribute to order)
* @param {number} position position in the category (contribute to order)
* @param {InitFragmentKey=} key unique key to avoid emitting the same initialization code twice
* @param {string | Source=} endContent the source code that will be included at the end of the module
*/
constructor(content, stage, position, key, endContent) {
this.content = content;
this.stage = stage;
this.position = position;
this.key = key;
this.endContent = endContent;
}
/**
* Returns the source code that will be included as initialization code.
* @param {GenerateContext} context context
* @returns {string | Source | undefined} the source code that will be included as initialization code
*/
getContent(context) {
return this.content;
}
/**
* Returns the source code that will be included at the end of the module.
* @param {GenerateContext} context context
* @returns {string | Source | undefined} the source code that will be included at the end of the module
*/
getEndContent(context) {
return this.endContent;
}
/**
* Adds the provided source to the init fragment.
* @template Context
* @param {Source} source sources
* @param {MaybeMergeableInitFragment<Context>[]} initFragments init fragments
* @param {Context} context context
* @returns {Source} source
*/
static addToSource(source, initFragments, context) {
if (initFragments.length > 0) {
// Sort fragments by position. If 2 fragments have the same position,
// use their index.
const sortedFragments = initFragments
.map(extractFragmentIndex)
.sort(sortFragmentWithIndex);
// Deduplicate fragments. If a fragment has no key, it is always included.
/** @type {Map<InitFragmentKey | symbol, MaybeMergeableInitFragment<Context> | MaybeMergeableInitFragment<Context>[]>} */
const keyedFragments = new Map();
for (const [fragment] of sortedFragments) {
if (typeof fragment.mergeAll === "function") {
if (!fragment.key) {
throw new Error(
`InitFragment with mergeAll function must have a valid key: ${fragment.constructor.name}`
);
}
const oldValue = keyedFragments.get(fragment.key);
if (oldValue === undefined) {
keyedFragments.set(fragment.key, fragment);
} else if (Array.isArray(oldValue)) {
oldValue.push(fragment);
} else {
keyedFragments.set(fragment.key, [oldValue, fragment]);
}
continue;
} else if (typeof fragment.merge === "function") {
const key = /** @type {InitFragmentKey} */ (fragment.key);
const oldValue =
/** @type {MaybeMergeableInitFragment<Context>} */
(keyedFragments.get(key));
if (oldValue !== undefined) {
keyedFragments.set(key, fragment.merge(oldValue));
continue;
}
}
keyedFragments.set(fragment.key || Symbol("fragment key"), fragment);
}
const concatSource = new ConcatSource();
/** @type {(string | Source)[]} */
const endContents = [];
for (let fragment of keyedFragments.values()) {
if (Array.isArray(fragment)) {
fragment =
/** @type {[MaybeMergeableInitFragment<Context> & { mergeAll: (fragments: MaybeMergeableInitFragment<Context>[]) => MaybeMergeableInitFragment<Context>[] }, ...MaybeMergeableInitFragment<Context>[]]} */
(fragment)[0].mergeAll(fragment);
}
const content =
/** @type {MaybeMergeableInitFragment<Context>} */
(fragment).getContent(context);
if (content) {
concatSource.add(content);
}
const endContent =
/** @type {MaybeMergeableInitFragment<Context>} */
(fragment).getEndContent(context);
if (endContent) {
endContents.push(endContent);
}
}
concatSource.add(source);
for (const content of endContents.reverse()) {
concatSource.add(content);
}
return concatSource;
}
return source;
}
/**
* Serializes this instance into the provided serializer context.
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.content);
write(this.stage);
write(this.position);
write(this.key);
write(this.endContent);
}
/**
* Restores this instance from the provided deserializer context.
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.content = read();
this.stage = read();
this.position = read();
this.key = read();
this.endContent = read();
}
}
makeSerializable(InitFragment, "webpack/lib/InitFragment");
InitFragment.STAGE_CONSTANTS = 10;
InitFragment.STAGE_ASYNC_BOUNDARY = 20;
InitFragment.STAGE_HARMONY_EXPORTS = 30;
InitFragment.STAGE_HARMONY_IMPORTS = 40;
InitFragment.STAGE_PROVIDES = 50;
InitFragment.STAGE_ASYNC_DEPENDENCIES = 60;
InitFragment.STAGE_ASYNC_HARMONY_IMPORTS = 70;
module.exports = InitFragment;

79
node_modules/webpack/lib/JavascriptMetaInfoPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const InnerGraph = require("./optimize/InnerGraph");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
const PLUGIN_NAME = "JavascriptMetaInfoPlugin";
class JavascriptMetaInfoPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
/**
* Handles the hook callback for this code path.
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const handler = (parser) => {
parser.hooks.call.for("eval").tap(PLUGIN_NAME, () => {
const buildInfo =
/** @type {BuildInfo} */
(parser.state.module.buildInfo);
buildInfo.moduleConcatenationBailout = "eval()";
const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state);
if (currentSymbol) {
InnerGraph.addUsage(parser.state, null, currentSymbol);
} else {
InnerGraph.bailout(parser.state);
}
});
parser.hooks.finish.tap(PLUGIN_NAME, () => {
const buildInfo =
/** @type {BuildInfo} */
(parser.state.module.buildInfo);
let topLevelDeclarations = buildInfo.topLevelDeclarations;
if (topLevelDeclarations === undefined) {
topLevelDeclarations = buildInfo.topLevelDeclarations = new Set();
}
for (const name of parser.scope.definitions.asSet()) {
if (parser.isVariableDefined(name)) {
topLevelDeclarations.add(name);
}
}
});
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = JavascriptMetaInfoPlugin;

49
node_modules/webpack/lib/LibraryTemplatePlugin.js generated vendored Normal file
View File

@@ -0,0 +1,49 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const EnableLibraryPlugin = require("./library/EnableLibraryPlugin");
/** @typedef {import("../declarations/WebpackOptions").AuxiliaryComment} AuxiliaryComment */
/** @typedef {import("../declarations/WebpackOptions").LibraryExport} LibraryExport */
/** @typedef {import("../declarations/WebpackOptions").LibraryName} LibraryName */
/** @typedef {import("../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../declarations/WebpackOptions").UmdNamedDefine} UmdNamedDefine */
/** @typedef {import("./Compiler")} Compiler */
// TODO webpack 6 remove
class LibraryTemplatePlugin {
/**
* Creates an instance of LibraryTemplatePlugin.
* @param {LibraryName} name name of library
* @param {LibraryType} target type of library
* @param {UmdNamedDefine} umdNamedDefine setting this to true will name the UMD module
* @param {AuxiliaryComment} auxiliaryComment comment in the UMD wrapper
* @param {LibraryExport} exportProperty which export should be exposed as library
*/
constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) {
this.library = {
type: target || "var",
name,
umdNamedDefine,
auxiliaryComment,
export: exportProperty
};
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { output } = compiler.options;
output.library = this.library;
new EnableLibraryPlugin(this.library.type).apply(compiler);
}
}
module.exports = LibraryTemplatePlugin;

85
node_modules/webpack/lib/LoaderOptionsPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,85 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const NormalModule = require("./NormalModule");
/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ModuleFilenameHelpers").MatchObject} MatchObject */
/**
* Defines the loader context type used by this module.
* @template T
* @typedef {import("../declarations/LoaderContext").LoaderContext<T>} LoaderContext
*/
const PLUGIN_NAME = "LoaderOptionsPlugin";
class LoaderOptionsPlugin {
/**
* Creates an instance of LoaderOptionsPlugin.
* @param {LoaderOptionsPluginOptions & MatchObject} options options object
*/
constructor(options = {}) {
// If no options are set then generate empty options object
if (typeof options !== "object") options = {};
if (!options.test) {
options.test = () => true;
}
/** @type {LoaderOptionsPluginOptions & MatchObject} */
this.options = options;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
() => require("../schemas/plugins/LoaderOptionsPlugin.json"),
this.options,
{
name: "Loader Options Plugin",
baseDataPath: "options"
},
(options) =>
require("../schemas/plugins/LoaderOptionsPlugin.check")(options)
);
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
(context, module) => {
const resource = module.resource;
if (!resource) return;
const i = resource.indexOf("?");
if (
ModuleFilenameHelpers.matchObject(
this.options,
i < 0 ? resource : resource.slice(0, i)
)
) {
for (const key of Object.keys(this.options)) {
if (key === "include" || key === "exclude" || key === "test") {
continue;
}
/** @type {LoaderContext<EXPECTED_ANY> & Record<string, EXPECTED_ANY>} */
(context)[key] = this.options[key];
}
}
}
);
});
}
}
module.exports = LoaderOptionsPlugin;

40
node_modules/webpack/lib/LoaderTargetPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,40 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const NormalModule = require("./NormalModule");
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "LoaderTargetPlugin";
class LoaderTargetPlugin {
/**
* Creates an instance of LoaderTargetPlugin.
* @param {string} target the target
*/
constructor(target) {
this.target = target;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
(loaderContext) => {
loaderContext.target = this.target;
}
);
});
}
}
module.exports = LoaderTargetPlugin;

386
node_modules/webpack/lib/MainTemplate.js generated vendored Normal file
View File

@@ -0,0 +1,386 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const { SyncWaterfallHook } = require("tapable");
const RuntimeGlobals = require("./RuntimeGlobals");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").InterpolatedPathAndAssetInfo} InterpolatedPathAndAssetInfo */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderBootstrapContext} RenderBootstrapContext */
/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */
/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./TemplatedPathPlugin").PathData} PathData */
/**
* Defines the if set type used by this module.
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
const getJsonpTemplatePlugin = memoize(() =>
require("./web/JsonpTemplatePlugin")
);
const getLoadScriptRuntimeModule = memoize(() =>
require("./runtime/LoadScriptRuntimeModule")
);
// TODO webpack 6 remove this class
class MainTemplate {
/**
* Creates an instance of MainTemplate.
* @param {OutputOptions} outputOptions output options for the MainTemplate
* @param {Compilation} compilation the compilation
*/
constructor(outputOptions, compilation) {
/** @type {OutputOptions} */
this._outputOptions = outputOptions || {};
this.hooks = Object.freeze({
renderManifest: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(renderManifestEntries: RenderManifestEntry[], renderManifestOptions: RenderManifestOptions) => RenderManifestEntry[]} fn fn
*/
(options, fn) => {
compilation.hooks.renderManifest.tap(
options,
(entries, options) => {
if (!options.chunk.hasRuntime()) return entries;
return fn(entries, options);
}
);
},
"MainTemplate.hooks.renderManifest is deprecated (use Compilation.hooks.renderManifest instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER_MANIFEST"
)
},
modules: {
tap: () => {
throw new Error(
"MainTemplate.hooks.modules has been removed (there is no replacement, please create an issue to request that)"
);
}
},
moduleObj: {
tap: () => {
throw new Error(
"MainTemplate.hooks.moduleObj has been removed (there is no replacement, please create an issue to request that)"
);
}
},
require: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(value: string, renderBootstrapContext: RenderBootstrapContext) => string} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderRequire.tap(options, fn);
},
"MainTemplate.hooks.require is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderRequire instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE"
)
},
beforeStartup: {
tap: () => {
throw new Error(
"MainTemplate.hooks.beforeStartup has been removed (use RuntimeGlobals.startupOnlyBefore instead)"
);
}
},
startup: {
tap: () => {
throw new Error(
"MainTemplate.hooks.startup has been removed (use RuntimeGlobals.startup instead)"
);
}
},
afterStartup: {
tap: () => {
throw new Error(
"MainTemplate.hooks.afterStartup has been removed (use RuntimeGlobals.startupOnlyAfter instead)"
);
}
},
render: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, chunk: Chunk, hash: string | undefined, moduleTemplate: ModuleTemplate, dependencyTemplates: DependencyTemplates) => Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.render.tap(options, (source, renderContext) => {
if (
renderContext.chunkGraph.getNumberOfEntryModules(
renderContext.chunk
) === 0 ||
!renderContext.chunk.hasRuntime()
) {
return source;
}
return fn(
source,
renderContext.chunk,
compilation.hash,
compilation.moduleTemplates.javascript,
compilation.dependencyTemplates
);
});
},
"MainTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER"
)
},
renderWithEntry: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, chunk: Chunk, hash: string | undefined) => Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.render.tap(options, (source, renderContext) => {
if (
renderContext.chunkGraph.getNumberOfEntryModules(
renderContext.chunk
) === 0 ||
!renderContext.chunk.hasRuntime()
) {
return source;
}
return fn(source, renderContext.chunk, compilation.hash);
});
},
"MainTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER_WITH_ENTRY"
)
},
assetPath: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(value: string, path: PathData, assetInfo: AssetInfo | undefined) => string} fn fn
*/
(options, fn) => {
compilation.hooks.assetPath.tap(options, fn);
},
"MainTemplate.hooks.assetPath is deprecated (use Compilation.hooks.assetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH"
),
call: util.deprecate(
/**
* Handles the call callback for this hook.
* @param {TemplatePath} filename used to get asset path with hash
* @param {PathData} options context data
* @returns {string} interpolated path
*/
(filename, options) => compilation.getAssetPath(filename, options),
"MainTemplate.hooks.assetPath is deprecated (use Compilation.hooks.assetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH"
)
},
hash: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(hash: Hash) => void} fn fn
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
"MainTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH"
)
},
hashForChunk: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(hash: Hash, chunk: Chunk) => void} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.chunkHash.tap(options, (chunk, hash) => {
if (!chunk.hasRuntime()) return;
return fn(hash, chunk);
});
},
"MainTemplate.hooks.hashForChunk is deprecated (use JavascriptModulesPlugin.getCompilationHooks().chunkHash instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK"
)
},
globalHashPaths: {
tap: util.deprecate(
() => {},
"MainTemplate.hooks.globalHashPaths has been removed (it's no longer needed)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK"
)
},
globalHash: {
tap: util.deprecate(
() => {},
"MainTemplate.hooks.globalHash has been removed (it's no longer needed)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK"
)
},
hotBootstrap: {
tap: () => {
throw new Error(
"MainTemplate.hooks.hotBootstrap has been removed (use your own RuntimeModule instead)"
);
}
},
// for compatibility:
/** @type {SyncWaterfallHook<[string, Chunk, string, ModuleTemplate, DependencyTemplates]>} */
bootstrap: new SyncWaterfallHook([
"source",
"chunk",
"hash",
"moduleTemplate",
"dependencyTemplates"
]),
/** @type {SyncWaterfallHook<[string, Chunk, string]>} */
localVars: new SyncWaterfallHook(["source", "chunk", "hash"]),
/** @type {SyncWaterfallHook<[string, Chunk, string]>} */
requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]),
/** @type {SyncWaterfallHook<[string, Chunk, string, string]>} */
requireEnsure: new SyncWaterfallHook([
"source",
"chunk",
"hash",
"chunkIdExpression"
]),
get jsonpScript() {
const hooks =
getLoadScriptRuntimeModule().getCompilationHooks(compilation);
return hooks.createScript;
},
get linkPrefetch() {
const hooks = getJsonpTemplatePlugin().getCompilationHooks(compilation);
return hooks.linkPrefetch;
},
get linkPreload() {
const hooks = getJsonpTemplatePlugin().getCompilationHooks(compilation);
return hooks.linkPreload;
}
});
this.renderCurrentHashCode = util.deprecate(
/**
* Handles the require ensure callback for this hook.
* @deprecated
* @param {string} hash the hash
* @param {number=} length length of the hash
* @returns {string} generated code
*/
(hash, length) => {
if (length) {
return `${RuntimeGlobals.getFullHash} ? ${
RuntimeGlobals.getFullHash
}().slice(0, ${length}) : ${hash.slice(0, length)}`;
}
return `${RuntimeGlobals.getFullHash} ? ${RuntimeGlobals.getFullHash}() : ${hash}`;
},
"MainTemplate.renderCurrentHashCode is deprecated (use RuntimeGlobals.getFullHash runtime function instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER_CURRENT_HASH_CODE"
);
this.getPublicPath = util.deprecate(
/**
* Handles the callback logic for this hook.
* @param {PathData} options context data
* @returns {string} interpolated path
*/ (options) =>
compilation.getAssetPath(compilation.outputOptions.publicPath, options),
"MainTemplate.getPublicPath is deprecated (use Compilation.getAssetPath(compilation.outputOptions.publicPath, options) instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_PUBLIC_PATH"
);
this.getAssetPath = util.deprecate(
/**
* Handles the callback logic for this hook.
* @param {TemplatePath} path used to get asset path with hash
* @param {PathData} options context data
* @returns {string} interpolated path
*/
(path, options) => compilation.getAssetPath(path, options),
"MainTemplate.getAssetPath is deprecated (use Compilation.getAssetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH"
);
this.getAssetPathWithInfo = util.deprecate(
/**
* Handles the callback logic for this hook.
* @param {TemplatePath} path used to get asset path with hash
* @param {PathData} options context data
* @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info
*/
(path, options) => compilation.getAssetPathWithInfo(path, options),
"MainTemplate.getAssetPathWithInfo is deprecated (use Compilation.getAssetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH_WITH_INFO"
);
}
}
Object.defineProperty(MainTemplate.prototype, "requireFn", {
get: util.deprecate(
() => RuntimeGlobals.require,
`MainTemplate.requireFn is deprecated (use "${RuntimeGlobals.require}")`,
"DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE_FN"
)
});
Object.defineProperty(MainTemplate.prototype, "outputOptions", {
get: util.deprecate(
/**
* Returns output options.
* @this {MainTemplate}
* @returns {OutputOptions} output options
*/
function outputOptions() {
return this._outputOptions;
},
"MainTemplate.outputOptions is deprecated (use Compilation.outputOptions instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_OUTPUT_OPTIONS"
)
});
module.exports = MainTemplate;

251
node_modules/webpack/lib/ManifestPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,251 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Haijie Xie @hai-x
*/
"use strict";
const { RawSource } = require("webpack-sources");
const Compilation = require("./Compilation");
const HotUpdateChunk = require("./HotUpdateChunk");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkName} ChunkName */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./Compilation").Asset} Asset */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("../declarations/plugins/ManifestPlugin").ManifestPluginOptions} ManifestPluginOptions */
/** @typedef {import("../declarations/plugins/ManifestPlugin").ManifestObject} ManifestObject */
/** @typedef {import("../declarations/plugins/ManifestPlugin").ManifestEntrypoint} ManifestEntrypoint */
/** @typedef {import("../declarations/plugins/ManifestPlugin").ManifestItem} ManifestItem */
/** @typedef {(item: ManifestItem) => boolean} Filter */
/** @typedef {(manifest: ManifestObject) => ManifestObject} Generate */
/** @typedef {(manifest: ManifestObject) => string} Serialize */
const PLUGIN_NAME = "ManifestPlugin";
/**
* Returns extname.
* @param {string} filename filename
* @returns {string} extname
*/
const extname = (filename) => {
const replaced = filename.replace(/\?.*/, "");
const split = replaced.split(".");
const last = split.pop();
if (!last) return "";
return last && /^(?:gz|br|map)$/i.test(last)
? `${split.pop()}.${last}`
: last;
};
const DEFAULT_PREFIX = "[publicpath]";
const DEFAULT_FILENAME = "manifest.json";
class ManifestPlugin {
/**
* Creates an instance of ManifestPlugin.
* @param {ManifestPluginOptions} options options
*/
constructor(options = {}) {
/** @type {ManifestPluginOptions} */
this.options = options;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
() => require("../schemas/plugins/ManifestPlugin.json"),
this.options,
{
name: "ManifestPlugin",
baseDataPath: "options"
},
(options) => require("../schemas/plugins/ManifestPlugin.check")(options)
);
});
const entrypoints =
this.options.entrypoints !== undefined ? this.options.entrypoints : true;
const serialize =
this.options.serialize ||
((manifest) => JSON.stringify(manifest, null, 2));
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE
},
() => {
const hashDigestLength = compilation.outputOptions.hashDigestLength;
const publicPath = compilation.getPath(
compilation.outputOptions.publicPath
);
/**
* Creates a hash reg exp.
* @param {string | string[]} value value
* @returns {RegExp} regexp to remove hash
*/
const createHashRegExp = (value) =>
new RegExp(
`(?:\\.${Array.isArray(value) ? `(${value.join("|")})` : value})(?=\\.)`,
"gi"
);
/**
* Removes the provided name from the manifest plugin.
* @param {string} name name
* @param {AssetInfo | null} info asset info
* @returns {string} hash removed name
*/
const removeHash = (name, info) => {
// Handles hashes that match configured `hashDigestLength`
// i.e. index.XXXX.html -> index.html (html-webpack-plugin)
if (hashDigestLength <= 0) return name;
const reg = createHashRegExp(`[a-f0-9]{${hashDigestLength},32}`);
return name.replace(reg, "");
};
/**
* Returns chunk name or chunk id.
* @param {Chunk} chunk chunk
* @returns {ChunkName | ChunkId} chunk name or chunk id
*/
const getName = (chunk) => {
if (chunk.name) return chunk.name;
return chunk.id;
};
/** @type {ManifestObject} */
let manifest = {};
if (entrypoints) {
/** @type {ManifestObject["entrypoints"]} */
const entrypoints = {};
for (const [name, entrypoint] of compilation.entrypoints) {
/** @type {string[]} */
const imports = [];
for (const chunk of entrypoint.chunks) {
for (const file of chunk.files) {
const name = getName(chunk);
imports.push(name ? `${name}.${extname(file)}` : file);
}
}
/** @type {ManifestEntrypoint} */
const item = { imports };
const parents = entrypoint
.getParents()
.map((item) => /** @type {string} */ (item.name));
if (parents.length > 0) {
item.parents = parents;
}
entrypoints[name] = item;
}
manifest.entrypoints = entrypoints;
}
/** @type {ManifestObject["assets"]} */
const assets = {};
/** @type {Set<string>} */
const added = new Set();
/**
* Processes the provided file.
* @param {string} file file
* @param {string=} usedName usedName
* @returns {void}
*/
const handleFile = (file, usedName) => {
if (added.has(file)) return;
added.add(file);
const asset = compilation.getAsset(file);
if (!asset) return;
const sourceFilename = asset.info.sourceFilename;
const name =
usedName ||
sourceFilename ||
// Fallback for unofficial plugins, just remove hash from filename
removeHash(file, asset.info);
const prefix = (this.options.prefix || DEFAULT_PREFIX).replace(
/\[publicpath\]/gi,
() => (publicPath === "auto" ? "/" : publicPath)
);
/** @type {ManifestItem} */
const item = { file: prefix + file };
if (sourceFilename) {
item.src = sourceFilename;
}
if (this.options.filter) {
const needKeep = this.options.filter(item);
if (!needKeep) {
return;
}
}
assets[name] = item;
};
for (const chunk of compilation.chunks) {
if (chunk instanceof HotUpdateChunk) continue;
for (const auxiliaryFile of chunk.auxiliaryFiles) {
handleFile(auxiliaryFile);
}
const name = getName(chunk);
for (const file of chunk.files) {
handleFile(file, name ? `${name}.${extname(file)}` : file);
}
}
for (const asset of compilation.getAssets()) {
if (asset.info.hotModuleReplacement) {
continue;
}
handleFile(asset.name);
}
manifest.assets = assets;
if (this.options.generate) {
manifest = this.options.generate(manifest);
}
compilation.emitAsset(
this.options.filename || DEFAULT_FILENAME,
new RawSource(serialize(manifest)),
{ manifest: true }
);
}
);
});
}
}
module.exports = ManifestPlugin;

1463
node_modules/webpack/lib/Module.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

62
node_modules/webpack/lib/ModuleFactory.js generated vendored Normal file
View File

@@ -0,0 +1,62 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Module")} Module */
/**
* Defines the module factory result type used by this module.
* @typedef {object} ModuleFactoryResult
* @property {Module=} module the created module or unset if no module was created
* @property {Set<string>=} fileDependencies
* @property {Set<string>=} contextDependencies
* @property {Set<string>=} missingDependencies
* @property {boolean=} cacheable allow to use the unsafe cache
*/
/** @typedef {string | null} IssuerLayer */
/**
* Defines the module factory create data context info type used by this module.
* @typedef {object} ModuleFactoryCreateDataContextInfo
* @property {string} issuer
* @property {IssuerLayer} issuerLayer
* @property {string=} compiler
*/
/**
* Defines the module factory create data type used by this module.
* @typedef {object} ModuleFactoryCreateData
* @property {ModuleFactoryCreateDataContextInfo} contextInfo
* @property {ResolveOptions=} resolveOptions
* @property {string} context
* @property {Dependency[]} dependencies
*/
/**
* Represents the module factory runtime component.
* @typedef {(err?: Error | null, result?: ModuleFactoryResult) => void} ModuleFactoryCallback
*/
class ModuleFactory {
/* istanbul ignore next */
/**
* Processes the provided data.
* @abstract
* @param {ModuleFactoryCreateData} data data object
* @param {ModuleFactoryCallback} callback callback
* @returns {void}
*/
create(data, callback) {
const AbstractMethodError = require("./errors/AbstractMethodError");
throw new AbstractMethodError();
}
}
module.exports = ModuleFactory;

391
node_modules/webpack/lib/ModuleFilenameHelpers.js generated vendored Normal file
View File

@@ -0,0 +1,391 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const NormalModule = require("./NormalModule");
const { DEFAULTS } = require("./config/defaults");
const createHash = require("./util/createHash");
const memoize = require("./util/memoize");
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {(str: string) => boolean} MatcherFn */
/** @typedef {string | RegExp | MatcherFn | (string | RegExp | MatcherFn)[]} Matcher */
/** @typedef {{ test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */
const ModuleFilenameHelpers = module.exports;
// TODO webpack 6: consider removing these
ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE =
/\[all-?loaders\]\[resource\]/gi;
ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
ModuleFilenameHelpers.RESOURCE = "[resource]";
ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
// cSpell:words olute
ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH =
/\[abs(olute)?-?resource-?path\]/gi;
ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi;
ModuleFilenameHelpers.LOADERS = "[loaders]";
ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi;
ModuleFilenameHelpers.QUERY = "[query]";
ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi;
ModuleFilenameHelpers.ID = "[id]";
ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
ModuleFilenameHelpers.HASH = "[hash]";
ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
ModuleFilenameHelpers.NAMESPACE = "[namespace]";
ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi;
/** @typedef {() => string} ReturnStringCallback */
/**
* Returns a function that returns the part of the string after the token
* @param {ReturnStringCallback} strFn the function to get the string
* @param {string} token the token to search for
* @returns {ReturnStringCallback} a function that returns the part of the string after the token
*/
const getAfter = (strFn, token) => () => {
const str = strFn();
const idx = str.indexOf(token);
return idx < 0 ? "" : str.slice(idx);
};
/**
* Returns a function that returns the part of the string before the token
* @param {ReturnStringCallback} strFn the function to get the string
* @param {string} token the token to search for
* @returns {ReturnStringCallback} a function that returns the part of the string before the token
*/
const getBefore = (strFn, token) => () => {
const str = strFn();
const idx = str.lastIndexOf(token);
return idx < 0 ? "" : str.slice(0, idx);
};
/**
* Returns a function that returns a hash of the string
* @param {ReturnStringCallback} strFn the function to get the string
* @param {HashFunction=} hashFunction the hash function to use
* @returns {ReturnStringCallback} a function that returns the hash of the string
*/
const getHash =
(strFn, hashFunction = DEFAULTS.HASH_FUNCTION) =>
() => {
const hash = createHash(hashFunction);
hash.update(strFn());
const digest = hash.digest("hex");
return digest.slice(0, 4);
};
/**
* Returns the lazy access object.
* @template T
* Returns a lazy object. The object is lazy in the sense that the properties are
* only evaluated when they are accessed. This is only obtained by setting a function as the value for each key.
* @param {Record<string, () => T>} obj the object to convert to a lazy access object
* @returns {Record<string, T>} the lazy access object
*/
const lazyObject = (obj) => {
const newObj = /** @type {Record<string, T>} */ ({});
for (const key of Object.keys(obj)) {
const fn = obj[key];
Object.defineProperty(newObj, key, {
get: () => fn(),
set: (v) => {
Object.defineProperty(newObj, key, {
value: v,
enumerable: true,
writable: true
});
},
enumerable: true,
configurable: true
});
}
return newObj;
};
const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/g;
/**
* Defines the module filename template context type used by this module.
* @typedef {object} ModuleFilenameTemplateContext
* @property {string} identifier the identifier of the module
* @property {string} shortIdentifier the shortened identifier of the module
* @property {string} resource the resource of the module request
* @property {string} resourcePath the resource path of the module request
* @property {string} absoluteResourcePath the absolute resource path of the module request
* @property {string} loaders the loaders of the module request
* @property {string} allLoaders the all loaders of the module request
* @property {string} query the query of the module identifier
* @property {string} moduleId the module id of the module
* @property {string} hash the hash of the module identifier
* @property {string} namespace the module namespace
*/
/** @typedef {((context: ModuleFilenameTemplateContext) => string)} ModuleFilenameTemplateFunction */
/** @typedef {string | ModuleFilenameTemplateFunction} ModuleFilenameTemplate */
/**
* Returns the filename.
* @param {Module | string} module the module
* @param {{ namespace?: string, moduleFilenameTemplate?: ModuleFilenameTemplate }} options options
* @param {{ requestShortener: RequestShortener, chunkGraph: ChunkGraph, hashFunction?: HashFunction }} contextInfo context info
* @returns {string} the filename
*/
ModuleFilenameHelpers.createFilename = (
// eslint-disable-next-line default-param-last
module = "",
options,
{ requestShortener, chunkGraph, hashFunction = DEFAULTS.HASH_FUNCTION }
) => {
const opts = {
namespace: "",
moduleFilenameTemplate: "",
...(typeof options === "object"
? options
: {
moduleFilenameTemplate: options
})
};
/** @type {ReturnStringCallback} */
let absoluteResourcePath;
/** @type {ReturnStringCallback} */
let hash;
/** @type {ReturnStringCallback} */
let identifier;
/** @type {ReturnStringCallback} */
let moduleId;
/** @type {ReturnStringCallback} */
let shortIdentifier;
if (typeof module === "string") {
shortIdentifier =
/** @type {ReturnStringCallback} */
(memoize(() => requestShortener.shorten(module)));
identifier = shortIdentifier;
moduleId = () => "";
absoluteResourcePath = () =>
/** @type {string} */ (module.split("!").pop());
hash = getHash(identifier, hashFunction);
} else {
shortIdentifier = memoize(() =>
module.readableIdentifier(requestShortener)
);
identifier =
/** @type {ReturnStringCallback} */
(memoize(() => requestShortener.shorten(module.identifier())));
moduleId =
/** @type {ReturnStringCallback} */
(() => chunkGraph.getModuleId(module));
absoluteResourcePath = () =>
module instanceof NormalModule
? module.resource
: /** @type {string} */ (module.identifier().split("!").pop());
hash = getHash(identifier, hashFunction);
}
const resource =
/** @type {ReturnStringCallback} */
(memoize(() => shortIdentifier().split("!").pop()));
const loaders = getBefore(shortIdentifier, "!");
const allLoaders = getBefore(identifier, "!");
const query = getAfter(resource, "?");
const resourcePath = () => {
const q = query().length;
return q === 0 ? resource() : resource().slice(0, -q);
};
if (typeof opts.moduleFilenameTemplate === "function") {
return opts.moduleFilenameTemplate(
/** @type {ModuleFilenameTemplateContext} */
(
lazyObject({
identifier,
shortIdentifier,
resource,
resourcePath: memoize(resourcePath),
absoluteResourcePath: memoize(absoluteResourcePath),
loaders: memoize(loaders),
allLoaders: memoize(allLoaders),
query: memoize(query),
moduleId: memoize(moduleId),
hash: memoize(hash),
namespace: () => opts.namespace
})
)
);
}
// TODO webpack 6: consider removing alternatives without dashes
/** @type {Map<string, () => string>} */
const replacements = new Map([
["identifier", identifier],
["short-identifier", shortIdentifier],
["resource", resource],
["resource-path", resourcePath],
// cSpell:words resourcepath
["resourcepath", resourcePath],
["absolute-resource-path", absoluteResourcePath],
["abs-resource-path", absoluteResourcePath],
// cSpell:words absoluteresource
["absoluteresource-path", absoluteResourcePath],
// cSpell:words absresource
["absresource-path", absoluteResourcePath],
// cSpell:words resourcepath
["absolute-resourcepath", absoluteResourcePath],
// cSpell:words resourcepath
["abs-resourcepath", absoluteResourcePath],
// cSpell:words absoluteresourcepath
["absoluteresourcepath", absoluteResourcePath],
// cSpell:words absresourcepath
["absresourcepath", absoluteResourcePath],
["all-loaders", allLoaders],
// cSpell:words allloaders
["allloaders", allLoaders],
["loaders", loaders],
["query", query],
["id", moduleId],
["hash", hash],
["namespace", () => opts.namespace]
]);
// TODO webpack 6: consider removing weird double placeholders
return /** @type {string} */ (opts.moduleFilenameTemplate)
.replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, "[identifier]")
.replace(
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE,
"[short-identifier]"
)
.replace(SQUARE_BRACKET_TAG_REGEXP, (match, content) => {
if (content.length + 2 === match.length) {
const replacement = replacements.get(content.toLowerCase());
if (replacement !== undefined) {
return replacement();
}
} else if (match.startsWith("[\\") && match.endsWith("\\]")) {
return `[${match.slice(2, -2)}]`;
}
return match;
});
};
/**
* Replaces duplicate items in an array with new values generated by a callback function.
* The callback function is called with the duplicate item, the index of the duplicate item, and the number of times the item has been replaced.
* The callback function should return the new value for the duplicate item.
* @template T
* @param {T[]} array the array with duplicates to be replaced
* @param {(duplicateItem: T, duplicateItemIndex: number, numberOfTimesReplaced: number) => T} fn callback function to generate new values for the duplicate items
* @param {(firstElement: T, nextElement: T) => -1 | 0 | 1=} comparator optional comparator function to sort the duplicate items
* @returns {T[]} the array with duplicates replaced
* @example
* ```js
* const array = ["a", "b", "c", "a", "b", "a"];
* const result = ModuleFilenameHelpers.replaceDuplicates(array, (item, index, count) => `${item}-${count}`);
* // result: ["a-1", "b-1", "c", "a-2", "b-2", "a-3"]
* ```
*/
ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
const countMap = Object.create(null);
const posMap = Object.create(null);
for (const [idx, item] of array.entries()) {
countMap[item] = countMap[item] || [];
countMap[item].push(idx);
posMap[item] = 0;
}
if (comparator) {
for (const item of Object.keys(countMap)) {
countMap[item].sort(comparator);
}
}
return array.map((item, i) => {
if (countMap[item].length > 1) {
if (comparator && countMap[item][0] === i) return item;
return fn(item, i, posMap[item]++);
}
return item;
});
};
/**
* Tests if a string matches a RegExp or an array of RegExp.
* @param {string} str string to test
* @param {Matcher} test value which will be used to match against the string
* @returns {boolean} true, when the RegExp matches
* @example
* ```js
* ModuleFilenameHelpers.matchPart("foo.js", "foo"); // true
* ModuleFilenameHelpers.matchPart("foo.js", "foo.js"); // true
* ModuleFilenameHelpers.matchPart("foo.js", "foo."); // false
* ModuleFilenameHelpers.matchPart("foo.js", "foo*"); // false
* ModuleFilenameHelpers.matchPart("foo.js", "foo.*"); // true
* ModuleFilenameHelpers.matchPart("foo.js", /^foo/); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, /^bar/]); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^baz/, /^bar/]); // false
* ```
*/
const matchPart = (str, test) => {
if (!test) return true;
if (test instanceof RegExp) {
return test.test(str);
} else if (typeof test === "string") {
return str.startsWith(test);
} else if (typeof test === "function") {
return test(str);
}
return test.some((test) => matchPart(str, test));
};
ModuleFilenameHelpers.matchPart = matchPart;
/**
* Tests if a string matches a match object. The match object can have the following properties:
* - `test`: a RegExp or an array of RegExp
* - `include`: a RegExp or an array of RegExp
* - `exclude`: a RegExp or an array of RegExp
*
* The `test` property is tested first, then `include` and then `exclude`.
* @param {MatchObject} obj a match object to test against the string
* @param {string} str string to test against the matching object
* @returns {boolean} true, when the object matches
* @example
* ```js
* ModuleFilenameHelpers.matchObject({ test: "foo.js" }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ test: /^foo/ }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "baz.js"); // false
* ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "bar.js"); // false
* ModuleFilenameHelpers.matchObject({ include: /^foo/ }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "baz.js"); // false
* ModuleFilenameHelpers.matchObject({ exclude: "foo.js" }, "foo.js"); // false
* ModuleFilenameHelpers.matchObject({ exclude: [/^foo/, "bar"] }, "foo.js"); // false
* ```
*/
ModuleFilenameHelpers.matchObject = (obj, str) => {
if (obj.test && !ModuleFilenameHelpers.matchPart(str, obj.test)) {
return false;
}
if (obj.include && !ModuleFilenameHelpers.matchPart(str, obj.include)) {
return false;
}
if (obj.exclude && ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
return false;
}
return true;
};

1093
node_modules/webpack/lib/ModuleGraph.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

208
node_modules/webpack/lib/ModuleGraphConnection.js generated vendored Normal file
View File

@@ -0,0 +1,208 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").GetConditionFn} GetConditionFn */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* Module itself is not connected, but transitive modules are connected transitively.
*/
const TRANSITIVE_ONLY = Symbol("transitive only");
/**
* While determining the active state, this flag is used to signal a circular connection.
*/
const CIRCULAR_CONNECTION = Symbol("circular connection");
/** @typedef {boolean | typeof TRANSITIVE_ONLY | typeof CIRCULAR_CONNECTION} ConnectionState */
/**
* Adds connection states.
* @param {ConnectionState} a first
* @param {ConnectionState} b second
* @returns {ConnectionState} merged
*/
const addConnectionStates = (a, b) => {
if (a === true || b === true) return true;
if (a === false) return b;
if (b === false) return a;
if (a === TRANSITIVE_ONLY) return b;
if (b === TRANSITIVE_ONLY) return a;
return a;
};
/**
* Intersect connection states.
* @param {ConnectionState} a first
* @param {ConnectionState} b second
* @returns {ConnectionState} intersected
*/
const intersectConnectionStates = (a, b) => {
if (a === false || b === false) return false;
if (a === true) return b;
if (b === true) return a;
if (a === CIRCULAR_CONNECTION) return b;
if (b === CIRCULAR_CONNECTION) return a;
return a;
};
class ModuleGraphConnection {
/**
* Creates an instance of ModuleGraphConnection.
* @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
* @param {false | null | GetConditionFn=} condition condition for the connection
*/
constructor(
originModule,
dependency,
module,
explanation,
weak = false,
condition = undefined
) {
/** @type {Module | null} */
this.originModule = originModule;
/** @type {Module | null} */
this.resolvedOriginModule = originModule;
/** @type {Dependency | null} */
this.dependency = dependency;
/** @type {Module} */
this.resolvedModule = module;
/** @type {Module} */
this.module = module;
/** @type {boolean | undefined} */
this.weak = weak;
/** @type {boolean} */
this.conditional = Boolean(condition);
/** @type {boolean} */
this._active = condition !== false;
/** @type {false | null | GetConditionFn | undefined} */
this.condition = condition || undefined;
/** @type {Set<string> | undefined} */
this.explanations = undefined;
if (explanation) {
this.explanations = new Set();
this.explanations.add(explanation);
}
}
clone() {
const clone = new ModuleGraphConnection(
this.resolvedOriginModule,
this.dependency,
this.resolvedModule,
undefined,
this.weak,
this.condition
);
clone.originModule = this.originModule;
clone.module = this.module;
clone.conditional = this.conditional;
clone._active = this._active;
if (this.explanations) clone.explanations = new Set(this.explanations);
return clone;
}
/**
* Adds the provided condition to the module graph connection.
* @param {GetConditionFn} condition condition for the connection
* @returns {void}
*/
addCondition(condition) {
if (this.conditional) {
const old =
/** @type {GetConditionFn} */
(this.condition);
/** @type {GetConditionFn} */
(this.condition) = (c, r) =>
intersectConnectionStates(old(c, r), condition(c, r));
} else if (this._active) {
this.conditional = true;
this.condition = condition;
}
}
/**
* Adds the provided explanation to the module graph connection.
* @param {string} explanation the explanation to add
* @returns {void}
*/
addExplanation(explanation) {
if (this.explanations === undefined) {
this.explanations = new Set();
}
this.explanations.add(explanation);
}
get explanation() {
if (this.explanations === undefined) return "";
return [...this.explanations].join(" ");
}
/**
* Checks whether this module graph connection is active.
* @param {RuntimeSpec} runtime the runtime
* @returns {boolean} true, if the connection is active
*/
isActive(runtime) {
if (!this.conditional) return this._active;
return (
/** @type {GetConditionFn} */ (this.condition)(this, runtime) !== false
);
}
/**
* Checks whether this module graph connection is target active.
* @param {RuntimeSpec} runtime the runtime
* @returns {boolean} true, if the connection is active
*/
isTargetActive(runtime) {
if (!this.conditional) return this._active;
return (
/** @type {GetConditionFn} */ (this.condition)(this, runtime) === true
);
}
/**
* Returns true: fully active, false: inactive, TRANSITIVE: direct module inactive, but transitive connection maybe active.
* @param {RuntimeSpec} runtime the runtime
* @returns {ConnectionState} true: fully active, false: inactive, TRANSITIVE: direct module inactive, but transitive connection maybe active
*/
getActiveState(runtime) {
if (!this.conditional) return this._active;
return /** @type {GetConditionFn} */ (this.condition)(this, runtime);
}
/**
* Updates active using the provided value.
* @param {boolean} value active or not
* @returns {void}
*/
setActive(value) {
this.conditional = false;
this._active = value;
}
}
/** @typedef {typeof TRANSITIVE_ONLY} TRANSITIVE_ONLY */
/** @typedef {typeof CIRCULAR_CONNECTION} CIRCULAR_CONNECTION */
module.exports = ModuleGraphConnection;
module.exports.CIRCULAR_CONNECTION = /** @type {typeof CIRCULAR_CONNECTION} */ (
CIRCULAR_CONNECTION
);
module.exports.TRANSITIVE_ONLY = /** @type {typeof TRANSITIVE_ONLY} */ (
TRANSITIVE_ONLY
);
module.exports.addConnectionStates = addConnectionStates;

323
node_modules/webpack/lib/ModuleInfoHeaderPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,323 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { CachedSource, ConcatSource, RawSource } = require("webpack-sources");
const { UsageState } = require("./ExportsInfo");
const Template = require("./Template");
const CssModulesPlugin = require("./css/CssModulesPlugin");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RequestShortener")} RequestShortener */
/**
* Join iterable with comma.
* @template T
* @param {Iterable<T>} iterable iterable
* @returns {string} joined with comma
*/
const joinIterableWithComma = (iterable) => {
// This is more performant than Array.from().join(", ")
// as it doesn't create an array
let str = "";
let first = true;
for (const item of iterable) {
if (first) {
first = false;
} else {
str += ", ";
}
str += item;
}
return str;
};
/**
* Print exports info to source.
* @param {ConcatSource} source output
* @param {string} indent spacing
* @param {ExportsInfo} exportsInfo data
* @param {ModuleGraph} moduleGraph moduleGraph
* @param {RequestShortener} requestShortener requestShortener
* @param {Set<ExportInfo>} alreadyPrinted deduplication set
* @returns {void}
*/
const printExportsInfoToSource = (
source,
indent,
exportsInfo,
moduleGraph,
requestShortener,
alreadyPrinted = new Set()
) => {
const otherExportsInfo = exportsInfo.otherExportsInfo;
let alreadyPrintedExports = 0;
// determine exports to print
/** @type {ExportInfo[]} */
const printedExports = [];
for (const exportInfo of exportsInfo.orderedExports) {
if (!alreadyPrinted.has(exportInfo)) {
alreadyPrinted.add(exportInfo);
printedExports.push(exportInfo);
} else {
alreadyPrintedExports++;
}
}
let showOtherExports = false;
if (!alreadyPrinted.has(otherExportsInfo)) {
alreadyPrinted.add(otherExportsInfo);
showOtherExports = true;
} else {
alreadyPrintedExports++;
}
// print the exports
for (const exportInfo of printedExports) {
const target = exportInfo.getTarget(moduleGraph);
source.add(
`${Template.toComment(
`${indent}export ${JSON.stringify(exportInfo.name).slice(
1,
-1
)} [${exportInfo.getProvidedInfo()}] [${exportInfo.getUsedInfo()}] [${exportInfo.getRenameInfo()}]${
target
? ` -> ${target.module.readableIdentifier(requestShortener)}${
target.export
? ` .${target.export
.map((e) => JSON.stringify(e).slice(1, -1))
.join(".")}`
: ""
}`
: ""
}`
)}\n`
);
if (exportInfo.exportsInfo) {
printExportsInfoToSource(
source,
`${indent} `,
exportInfo.exportsInfo,
moduleGraph,
requestShortener,
alreadyPrinted
);
}
}
if (alreadyPrintedExports) {
source.add(
`${Template.toComment(
`${indent}... (${alreadyPrintedExports} already listed exports)`
)}\n`
);
}
if (showOtherExports) {
const target = otherExportsInfo.getTarget(moduleGraph);
if (
target ||
otherExportsInfo.provided !== false ||
otherExportsInfo.getUsed(undefined) !== UsageState.Unused
) {
const title =
printedExports.length > 0 || alreadyPrintedExports > 0
? "other exports"
: "exports";
source.add(
`${Template.toComment(
`${indent}${title} [${otherExportsInfo.getProvidedInfo()}] [${otherExportsInfo.getUsedInfo()}]${
target
? ` -> ${target.module.readableIdentifier(requestShortener)}`
: ""
}`
)}\n`
);
}
}
};
/** @typedef {{ header: RawSource | undefined, full: WeakMap<Source, CachedSource> }} CacheEntry */
/** @type {WeakMap<RequestShortener, WeakMap<Module, CacheEntry>>} */
const caches = new WeakMap();
const PLUGIN_NAME = "ModuleInfoHeaderPlugin";
class ModuleInfoHeaderPlugin {
/**
* Creates an instance of ModuleInfoHeaderPlugin.
* @param {boolean=} verbose add more information like exports, runtime requirements and bailouts
*/
constructor(verbose = true) {
/** @type {boolean} */
this._verbose = verbose;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler
* @returns {void}
*/
apply(compiler) {
const { _verbose: verbose } = this;
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const javascriptHooks =
JavascriptModulesPlugin.getCompilationHooks(compilation);
javascriptHooks.renderModulePackage.tap(
PLUGIN_NAME,
(
moduleSource,
module,
{ chunk, chunkGraph, moduleGraph, runtimeTemplate }
) => {
const { requestShortener } = runtimeTemplate;
/** @type {undefined | CacheEntry} */
let cacheEntry;
let cache = caches.get(requestShortener);
if (cache === undefined) {
caches.set(requestShortener, (cache = new WeakMap()));
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else {
cacheEntry = cache.get(module);
if (cacheEntry === undefined) {
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else if (!verbose) {
const cachedSource = cacheEntry.full.get(moduleSource);
if (cachedSource !== undefined) return cachedSource;
}
}
const source = new ConcatSource();
let header = cacheEntry.header;
if (header === undefined) {
header = this.generateHeader(module, requestShortener);
cacheEntry.header = header;
}
source.add(header);
if (verbose) {
const exportsType = /** @type {BuildMeta} */ (module.buildMeta)
.exportsType;
source.add(
`${Template.toComment(
exportsType
? `${exportsType} exports`
: "unknown exports (runtime-defined)"
)}\n`
);
if (exportsType) {
const exportsInfo = moduleGraph.getExportsInfo(module);
printExportsInfoToSource(
source,
"",
exportsInfo,
moduleGraph,
requestShortener
);
}
source.add(
`${Template.toComment(
`runtime requirements: ${joinIterableWithComma(
chunkGraph.getModuleRuntimeRequirements(module, chunk.runtime)
)}`
)}\n`
);
const optimizationBailout =
moduleGraph.getOptimizationBailout(module);
if (optimizationBailout) {
for (const text of optimizationBailout) {
const code =
typeof text === "function" ? text(requestShortener) : text;
source.add(`${Template.toComment(`${code}`)}\n`);
}
}
source.add(moduleSource);
return source;
}
source.add(moduleSource);
const cachedSource = new CachedSource(source);
cacheEntry.full.set(moduleSource, cachedSource);
return cachedSource;
}
);
javascriptHooks.chunkHash.tap(PLUGIN_NAME, (_chunk, hash) => {
hash.update(PLUGIN_NAME);
hash.update("1");
});
const cssHooks = CssModulesPlugin.getCompilationHooks(compilation);
cssHooks.renderModulePackage.tap(
PLUGIN_NAME,
(moduleSource, module, { runtimeTemplate }) => {
const { requestShortener } = runtimeTemplate;
/** @type {undefined | CacheEntry} */
let cacheEntry;
let cache = caches.get(requestShortener);
if (cache === undefined) {
caches.set(requestShortener, (cache = new WeakMap()));
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else {
cacheEntry = cache.get(module);
if (cacheEntry === undefined) {
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else if (!verbose) {
const cachedSource = cacheEntry.full.get(moduleSource);
if (cachedSource !== undefined) return cachedSource;
}
}
const source = new ConcatSource();
let header = cacheEntry.header;
if (header === undefined) {
header = this.generateHeader(module, requestShortener);
cacheEntry.header = header;
}
source.add(header);
source.add(moduleSource);
const cachedSource = new CachedSource(source);
cacheEntry.full.set(moduleSource, cachedSource);
return cachedSource;
}
);
cssHooks.chunkHash.tap(PLUGIN_NAME, (_chunk, hash) => {
hash.update(PLUGIN_NAME);
hash.update("1");
});
});
}
/**
* Returns the header.
* @param {Module} module the module
* @param {RequestShortener} requestShortener request shortener
* @returns {RawSource} the header
*/
generateHeader(module, requestShortener) {
const req = module.readableIdentifier(requestShortener);
const reqStr = req.replace(/\*\//g, "*_/");
const reqStrStar = "*".repeat(reqStr.length);
const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`;
return new RawSource(headerStr);
}
}
module.exports = ModuleInfoHeaderPlugin;

10
node_modules/webpack/lib/ModuleNotFoundError.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
// TODO remove in webpack 6
// Some old plugins use `require("webpack/lib/ModuleNotFoundError")`, in webpack@6 developer should migrate to `compiler.webpack.ModuleNotFoundError`
module.exports = require("./errors/ModuleNotFoundError");

108
node_modules/webpack/lib/ModuleProfile.js generated vendored Normal file
View File

@@ -0,0 +1,108 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ModuleProfile {
constructor() {
this.startTime = Date.now();
this.factoryStartTime = 0;
this.factoryEndTime = 0;
this.factory = 0;
this.factoryParallelismFactor = 0;
this.restoringStartTime = 0;
this.restoringEndTime = 0;
this.restoring = 0;
this.restoringParallelismFactor = 0;
this.integrationStartTime = 0;
this.integrationEndTime = 0;
this.integration = 0;
this.integrationParallelismFactor = 0;
this.buildingStartTime = 0;
this.buildingEndTime = 0;
this.building = 0;
this.buildingParallelismFactor = 0;
this.storingStartTime = 0;
this.storingEndTime = 0;
this.storing = 0;
this.storingParallelismFactor = 0;
/** @type {{ start: number, end: number }[] | undefined} */
this.additionalFactoryTimes = undefined;
this.additionalFactories = 0;
this.additionalFactoriesParallelismFactor = 0;
/** @deprecated */
this.additionalIntegration = 0;
}
markFactoryStart() {
this.factoryStartTime = Date.now();
}
markFactoryEnd() {
this.factoryEndTime = Date.now();
this.factory = this.factoryEndTime - this.factoryStartTime;
}
markRestoringStart() {
this.restoringStartTime = Date.now();
}
markRestoringEnd() {
this.restoringEndTime = Date.now();
this.restoring = this.restoringEndTime - this.restoringStartTime;
}
markIntegrationStart() {
this.integrationStartTime = Date.now();
}
markIntegrationEnd() {
this.integrationEndTime = Date.now();
this.integration = this.integrationEndTime - this.integrationStartTime;
}
markBuildingStart() {
this.buildingStartTime = Date.now();
}
markBuildingEnd() {
this.buildingEndTime = Date.now();
this.building = this.buildingEndTime - this.buildingStartTime;
}
markStoringStart() {
this.storingStartTime = Date.now();
}
markStoringEnd() {
this.storingEndTime = Date.now();
this.storing = this.storingEndTime - this.storingStartTime;
}
// This depends on timing so we ignore it for coverage
/* istanbul ignore next */
/**
* Merge this profile into another one
* @param {ModuleProfile} realProfile the profile to merge into
* @returns {void}
*/
mergeInto(realProfile) {
realProfile.additionalFactories = this.factory;
(realProfile.additionalFactoryTimes =
realProfile.additionalFactoryTimes || []).push({
start: this.factoryStartTime,
end: this.factoryEndTime
});
}
}
module.exports = ModuleProfile;

212
node_modules/webpack/lib/ModuleSourceTypeConstants.js generated vendored Normal file
View File

@@ -0,0 +1,212 @@
/*
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<"asset-url">}
*/
const ASSET_URL_TYPE = "asset-url";
/**
* @type {Readonly<"css">}
*/
const CSS_TYPE = "css";
/**
* @type {Readonly<"css-import">}
*/
const CSS_IMPORT_TYPE = "css-import";
/**
* @type {Readonly<"css-text">}
*/
const CSS_TEXT_TYPE = "css-text";
/**
* @type {Readonly<"html">}
*/
const HTML_TYPE = "html";
/**
* @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";
/**
* Defines the all types type used by this module.
* @typedef {JAVASCRIPT_TYPE | RUNTIME_TYPE | WEBASSEMBLY_TYPE | ASSET_TYPE | ASSET_URL_TYPE | CSS_TYPE | CSS_IMPORT_TYPE | CSS_TEXT_TYPE | HTML_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<"asset-url" | "asset">}
*/
const ASSET_AND_ASSET_URL_TYPES = new Set([ASSET_TYPE, ASSET_URL_TYPE]);
/**
* @type {ReadonlySet<"javascript" | "asset-url" | "asset">}
*/
const ASSET_AND_JAVASCRIPT_AND_ASSET_URL_TYPES = new Set([
ASSET_TYPE,
JAVASCRIPT_TYPE,
ASSET_URL_TYPE
]);
/**
* @type {ReadonlySet<"javascript">}
*/
const JAVASCRIPT_TYPES = new Set([JAVASCRIPT_TYPE]);
/**
* @type {ReadonlySet<"javascript" | "asset-url">}
*/
const JAVASCRIPT_AND_ASSET_URL_TYPES = new Set([
JAVASCRIPT_TYPE,
ASSET_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<"asset-url">}
*/
const ASSET_URL_TYPES = new Set([ASSET_URL_TYPE]);
/**
* @type {ReadonlySet<"css-text">}
*/
const CSS_TEXT_TYPES = new Set([CSS_TEXT_TYPE]);
/**
* @type {ReadonlySet<"javascript" | "css-text">}
*/
const JAVASCRIPT_AND_CSS_TEXT_TYPES = new Set([JAVASCRIPT_TYPE, CSS_TEXT_TYPE]);
/**
* @type {ReadonlySet<"css-import">}
*/
const CSS_IMPORT_TYPES = new Set([CSS_IMPORT_TYPE]);
/**
* @type {ReadonlySet<"html">}
*/
const HTML_TYPES = new Set([HTML_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_ASSET_URL_TYPES = ASSET_AND_ASSET_URL_TYPES;
module.exports.ASSET_AND_JAVASCRIPT_AND_ASSET_URL_TYPES =
ASSET_AND_JAVASCRIPT_AND_ASSET_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.ASSET_URL_TYPE = ASSET_URL_TYPE;
module.exports.ASSET_URL_TYPES = ASSET_URL_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_TEXT_TYPE = CSS_TEXT_TYPE;
module.exports.CSS_TEXT_TYPES = CSS_TEXT_TYPES;
module.exports.CSS_TYPE = CSS_TYPE;
module.exports.CSS_TYPES = CSS_TYPES;
module.exports.HTML_TYPE = HTML_TYPE;
module.exports.HTML_TYPES = HTML_TYPES;
module.exports.JAVASCRIPT_AND_ASSET_URL_TYPES = JAVASCRIPT_AND_ASSET_URL_TYPES;
module.exports.JAVASCRIPT_AND_CSS_TEXT_TYPES = JAVASCRIPT_AND_CSS_TEXT_TYPES;
module.exports.JAVASCRIPT_AND_CSS_TYPES = JAVASCRIPT_AND_CSS_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;

181
node_modules/webpack/lib/ModuleTemplate.js generated vendored Normal file
View File

@@ -0,0 +1,181 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ModuleRenderContext} ModuleRenderContext */
/** @typedef {import("./util/Hash")} Hash */
/**
* Defines the if set type used by this module.
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
// TODO webpack 6: remove this class
class ModuleTemplate {
/**
* Creates an instance of ModuleTemplate.
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Compilation} compilation the compilation
*/
constructor(runtimeTemplate, compilation) {
this._runtimeTemplate = runtimeTemplate;
this.type = "javascript";
this.hooks = Object.freeze({
content: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, module: Module, moduleRenderContext: ModuleRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContent.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.content is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
"DEP_MODULE_TEMPLATE_CONTENT"
)
},
module: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, module: Module, moduleRenderContext: ModuleRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContent.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.module is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
"DEP_MODULE_TEMPLATE_MODULE"
)
},
render: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, module: Module, chunkRenderContext: ChunkRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContainer.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer instead)",
"DEP_MODULE_TEMPLATE_RENDER"
)
},
package: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(source: Source, module: Module, chunkRenderContext: ChunkRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModulePackage.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.package is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModulePackage instead)",
"DEP_MODULE_TEMPLATE_PACKAGE"
)
},
hash: {
tap: util.deprecate(
/**
* Handles the callback logic for this hook.
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {(hash: Hash) => void} fn fn
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
"ModuleTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
"DEP_MODULE_TEMPLATE_HASH"
)
}
});
}
}
Object.defineProperty(ModuleTemplate.prototype, "runtimeTemplate", {
get: util.deprecate(
/**
* Returns output options.
* @this {ModuleTemplate}
* @returns {RuntimeTemplate} output options
*/
function runtimeTemplate() {
return this._runtimeTemplate;
},
"ModuleTemplate.runtimeTemplate is deprecated (use Compilation.runtimeTemplate instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS"
)
});
module.exports = ModuleTemplate;

199
node_modules/webpack/lib/ModuleTypeConstants.js generated vendored Normal file
View File

@@ -0,0 +1,199 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sean Larkin @TheLarkInn
*/
"use strict";
/**
* @type {Readonly<"javascript/auto">}
*/
const JAVASCRIPT_MODULE_TYPE_AUTO = "javascript/auto";
/**
* @type {Readonly<"javascript/dynamic">}
*/
const JAVASCRIPT_MODULE_TYPE_DYNAMIC = "javascript/dynamic";
/**
* @type {Readonly<"javascript/esm">}
* This is the module type used for _strict_ ES Module syntax. This means that all legacy formats
* that webpack supports (CommonJS, AMD, SystemJS) are not supported.
*/
const JAVASCRIPT_MODULE_TYPE_ESM = "javascript/esm";
/**
* @type {Readonly<"json">}
* This is the module type used for JSON files. JSON files are always parsed as ES Module.
*/
const JSON_MODULE_TYPE = "json";
/**
* @type {Readonly<"webassembly/async">}
* This is the module type used for WebAssembly modules. In webpack 5 they are always treated as async modules.
*/
const WEBASSEMBLY_MODULE_TYPE_ASYNC = "webassembly/async";
/**
* @type {Readonly<"webassembly/sync">}
* This is the module type used for WebAssembly modules. In webpack 4 they are always treated as sync modules.
* There is a legacy option to support this usage in webpack 5 and up.
*/
const WEBASSEMBLY_MODULE_TYPE_SYNC = "webassembly/sync";
/**
* @type {Readonly<"css">}
* This is the module type used for CSS files.
*/
const CSS_MODULE_TYPE = "css";
/**
* @type {Readonly<"css/global">}
* This is the module type used for CSS modules files where you need to use `:local` in selector list to hash classes.
*/
const CSS_MODULE_TYPE_GLOBAL = "css/global";
/**
* @type {Readonly<"css/module">}
* This is the module type used for CSS modules files, by default all classes are hashed.
*/
const CSS_MODULE_TYPE_MODULE = "css/module";
/**
* @type {Readonly<"css/auto">}
* This is the module type used for CSS files, the module will be parsed as CSS modules if it's filename contains `.module.` or `.modules.`.
*/
const CSS_MODULE_TYPE_AUTO = "css/auto";
/**
* @type {Readonly<"html">}
* This is the module type used for HTML files when `experiments.html` is enabled.
* HTML modules are emitted as HTML assets and can be used as entry points.
*/
const HTML_MODULE_TYPE = "html";
/**
* @type {Readonly<"asset">}
* This is the module type used for automatically choosing between `asset/inline`, `asset/resource` based on asset size limit (8096).
*/
const ASSET_MODULE_TYPE = "asset";
/**
* @type {Readonly<"asset/inline">}
* This is the module type used for assets that are inlined as a data URI. This is the equivalent of `url-loader`.
*/
const ASSET_MODULE_TYPE_INLINE = "asset/inline";
/**
* @type {Readonly<"asset/resource">}
* This is the module type used for assets that are copied to the output directory. This is the equivalent of `file-loader`.
*/
const ASSET_MODULE_TYPE_RESOURCE = "asset/resource";
/**
* @type {Readonly<"asset/source">}
* This is the module type used for assets that are imported as source code. This is the equivalent of `raw-loader`.
*/
const ASSET_MODULE_TYPE_SOURCE = "asset/source";
/**
* @type {Readonly<"asset/bytes">}
* This is the module type used for assets that are imported as Uint8Array.
*/
const ASSET_MODULE_TYPE_BYTES = "asset/bytes";
/**
* @type {Readonly<"asset/raw-data-url">}
* This is the module type used for the ignored asset module.
*/
const ASSET_MODULE_TYPE_RAW_DATA_URL = "asset/raw-data-url";
/**
* @type {Readonly<"runtime">}
* This is the module type used for the webpack runtime abstractions.
*/
const WEBPACK_MODULE_TYPE_RUNTIME = "runtime";
/**
* @type {Readonly<"fallback-module">}
* This is the module type used for the ModuleFederation feature's FallbackModule class.
*/
const WEBPACK_MODULE_TYPE_FALLBACK = "fallback-module";
/**
* @type {Readonly<"remote-module">}
* This is the module type used for the ModuleFederation feature's RemoteModule class.
*/
const WEBPACK_MODULE_TYPE_REMOTE = "remote-module";
/**
* @type {Readonly<"provide-module">}
* This is the module type used for the ModuleFederation feature's ProvideModule class.
*/
const WEBPACK_MODULE_TYPE_PROVIDE = "provide-module";
/**
* @type {Readonly<"consume-shared-module">}
* This is the module type used for the ModuleFederation feature's ConsumeSharedModule class.
*/
const WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE = "consume-shared-module";
/**
* @type {Readonly<"lazy-compilation-proxy">}
* Module type used for `experiments.lazyCompilation` feature. See `LazyCompilationPlugin` for more information.
*/
const WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = "lazy-compilation-proxy";
/** @typedef {"javascript/auto" | "javascript/dynamic" | "javascript/esm"} JavaScriptModuleTypes */
/** @typedef {"json"} JSONModuleType */
/** @typedef {"webassembly/async" | "webassembly/sync"} WebAssemblyModuleTypes */
/** @typedef {"css" | "css/global" | "css/module" | "css/auto"} CssModuleTypes */
/** @typedef {"html"} HTMLModuleType */
/** @typedef {"asset" | "asset/inline" | "asset/resource" | "asset/source" | "asset/raw-data-url"} AssetModuleTypes */
/** @typedef {"runtime" | "fallback-module" | "remote-module" | "provide-module" | "consume-shared-module" | "lazy-compilation-proxy"} WebpackModuleTypes */
/** @typedef {string} UnknownModuleTypes */
/** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CssModuleTypes | HTMLModuleType | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */
module.exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE;
module.exports.ASSET_MODULE_TYPE_BYTES = ASSET_MODULE_TYPE_BYTES;
module.exports.ASSET_MODULE_TYPE_INLINE = ASSET_MODULE_TYPE_INLINE;
module.exports.ASSET_MODULE_TYPE_RAW_DATA_URL = ASSET_MODULE_TYPE_RAW_DATA_URL;
module.exports.ASSET_MODULE_TYPE_RESOURCE = ASSET_MODULE_TYPE_RESOURCE;
module.exports.ASSET_MODULE_TYPE_SOURCE = ASSET_MODULE_TYPE_SOURCE;
/** @type {CssModuleTypes[]} */
module.exports.CSS_MODULES = [
CSS_MODULE_TYPE,
CSS_MODULE_TYPE_GLOBAL,
CSS_MODULE_TYPE_MODULE,
CSS_MODULE_TYPE_AUTO
];
module.exports.CSS_MODULE_TYPE = CSS_MODULE_TYPE;
module.exports.CSS_MODULE_TYPE_AUTO = CSS_MODULE_TYPE_AUTO;
module.exports.CSS_MODULE_TYPE_GLOBAL = CSS_MODULE_TYPE_GLOBAL;
module.exports.CSS_MODULE_TYPE_MODULE = CSS_MODULE_TYPE_MODULE;
module.exports.HTML_MODULE_TYPE = HTML_MODULE_TYPE;
/** @type {JavaScriptModuleTypes[]} */
module.exports.JAVASCRIPT_MODULES = [
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
];
module.exports.JAVASCRIPT_MODULE_TYPE_AUTO = JAVASCRIPT_MODULE_TYPE_AUTO;
module.exports.JAVASCRIPT_MODULE_TYPE_DYNAMIC = JAVASCRIPT_MODULE_TYPE_DYNAMIC;
module.exports.JAVASCRIPT_MODULE_TYPE_ESM = JAVASCRIPT_MODULE_TYPE_ESM;
module.exports.JSON_MODULE_TYPE = JSON_MODULE_TYPE;
/** @type {WebAssemblyModuleTypes[]} */
module.exports.WEBASSEMBLY_MODULES = [
WEBASSEMBLY_MODULE_TYPE_ASYNC,
WEBASSEMBLY_MODULE_TYPE_SYNC
];
module.exports.WEBASSEMBLY_MODULE_TYPE_ASYNC = WEBASSEMBLY_MODULE_TYPE_ASYNC;
module.exports.WEBASSEMBLY_MODULE_TYPE_SYNC = WEBASSEMBLY_MODULE_TYPE_SYNC;
module.exports.WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE =
WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE;
module.exports.WEBPACK_MODULE_TYPE_FALLBACK = WEBPACK_MODULE_TYPE_FALLBACK;
module.exports.WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY =
WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY;
module.exports.WEBPACK_MODULE_TYPE_PROVIDE = WEBPACK_MODULE_TYPE_PROVIDE;
module.exports.WEBPACK_MODULE_TYPE_REMOTE = WEBPACK_MODULE_TYPE_REMOTE;
module.exports.WEBPACK_MODULE_TYPE_RUNTIME = WEBPACK_MODULE_TYPE_RUNTIME;

720
node_modules/webpack/lib/MultiCompiler.js generated vendored Normal file
View File

@@ -0,0 +1,720 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const { MultiHook, SyncHook } = require("tapable");
const MultiStats = require("./MultiStats");
const MultiWatching = require("./MultiWatching");
const ConcurrentCompilationError = require("./errors/ConcurrentCompilationError");
const WebpackError = require("./errors/WebpackError");
const ArrayQueue = require("./util/ArrayQueue");
/**
* Defines the shared type used by this module.
* @template T
* @typedef {import("tapable").AsyncSeriesHook<T>} AsyncSeriesHook<T>
*/
/**
* Defines the shared type used by this module.
* @template T
* @template R
* @typedef {import("tapable").SyncBailHook<T, R>} SyncBailHook<T, R>
*/
/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
/** @typedef {import("./Compiler")} Compiler */
/**
* Defines the callback type used by this module.
* @template T
* @template [R=void]
* @typedef {import("./webpack").Callback<T, R>} Callback
*/
/** @typedef {import("./webpack").ErrorCallback} ErrorCallback */
/** @typedef {import("./Stats")} Stats */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
/**
* Defines the run with dependencies handler callback.
* @callback RunWithDependenciesHandler
* @param {Compiler} compiler
* @param {Callback<MultiStats>} callback
* @returns {void}
*/
/**
* Defines the multi compiler options type used by this module.
* @typedef {object} MultiCompilerOptions
* @property {number=} parallelism how many Compilers are allows to run at the same time in parallel
*/
/** @typedef {ReadonlyArray<WebpackOptions> & MultiCompilerOptions} MultiWebpackOptions */
const CLASS_NAME = "MultiCompiler";
module.exports = class MultiCompiler {
/**
* Creates an instance of MultiCompiler.
* @param {Compiler[] | Record<string, Compiler>} compilers child compilers
* @param {MultiCompilerOptions} options options
*/
constructor(compilers, options) {
if (!Array.isArray(compilers)) {
/** @type {Compiler[]} */
compilers = Object.keys(compilers).map((name) => {
/** @type {Record<string, Compiler>} */
(compilers)[name].name = name;
return /** @type {Record<string, Compiler>} */ (compilers)[name];
});
}
this.hooks = Object.freeze({
/** @type {SyncHook<[MultiStats]>} */
done: new SyncHook(["stats"]),
/** @type {MultiHook<SyncHook<[string | null, number]>>} */
invalid: new MultiHook(compilers.map((c) => c.hooks.invalid)),
/** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
run: new MultiHook(compilers.map((c) => c.hooks.run)),
/** @type {SyncHook<[]>} */
watchClose: new SyncHook([]),
/** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
watchRun: new MultiHook(compilers.map((c) => c.hooks.watchRun)),
/** @type {MultiHook<SyncBailHook<[string, string, EXPECTED_ANY[] | undefined], true | void>>} */
infrastructureLog: new MultiHook(
compilers.map((c) => c.hooks.infrastructureLog)
)
});
this.compilers = compilers;
/** @type {MultiCompilerOptions} */
this._options = {
parallelism: options.parallelism || Infinity
};
/** @type {WeakMap<Compiler, string[]>} */
this.dependencies = new WeakMap();
this.running = false;
/** @type {(Stats | null)[]} */
const compilerStats = this.compilers.map(() => null);
let doneCompilers = 0;
for (let index = 0; index < this.compilers.length; index++) {
const compiler = this.compilers[index];
const compilerIndex = index;
let compilerDone = false;
// eslint-disable-next-line no-loop-func
compiler.hooks.done.tap(CLASS_NAME, (stats) => {
if (!compilerDone) {
compilerDone = true;
doneCompilers++;
}
compilerStats[compilerIndex] = stats;
if (doneCompilers === this.compilers.length) {
this.hooks.done.call(
new MultiStats(/** @type {Stats[]} */ (compilerStats))
);
}
});
// eslint-disable-next-line no-loop-func
compiler.hooks.invalid.tap(CLASS_NAME, () => {
if (compilerDone) {
compilerDone = false;
doneCompilers--;
}
});
// Release fields on this child's Compilation once it's done. The
// stage: Infinity tap runs after every afterDone tap at a lower
// stage, so plugins observing compilation state in afterDone still
// see it intact. Stats remains usable; only fields Stats never reads
// (and that the persistent cache never serializes) are dropped.
compiler.hooks.afterDone.tap(
{ name: CLASS_NAME, stage: Infinity },
(stats) => {
if (stats !== undefined) {
compiler._releaseUnusedCompilationData(stats.compilation);
}
}
);
}
this._validateCompilersOptions();
}
_validateCompilersOptions() {
if (this.compilers.length < 2) return;
/**
* Adds the provided compiler to the multi compiler.
* @param {Compiler} compiler compiler
* @param {WebpackError} warning warning
*/
const addWarning = (compiler, warning) => {
compiler.hooks.thisCompilation.tap(CLASS_NAME, (compilation) => {
compilation.warnings.push(warning);
});
};
/** @type {Set<string>} */
const cacheNames = new Set();
for (const compiler of this.compilers) {
if (compiler.options.cache && "name" in compiler.options.cache) {
const name = /** @type {string} */ (compiler.options.cache.name);
if (cacheNames.has(name)) {
addWarning(
compiler,
new WebpackError(
`${
compiler.name
? `Compiler with name "${compiler.name}" doesn't use unique cache name. `
: ""
}Please set unique "cache.name" option. Name "${name}" already used.`
)
);
} else {
cacheNames.add(name);
}
}
}
}
get options() {
return Object.assign(
this.compilers.map((c) => c.options),
this._options
);
}
get outputPath() {
let commonPath = this.compilers[0].outputPath;
for (const compiler of this.compilers) {
while (
compiler.outputPath.indexOf(commonPath) !== 0 &&
/[/\\]/.test(commonPath)
) {
commonPath = commonPath.replace(/[/\\][^/\\]*$/, "");
}
}
if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/";
return commonPath;
}
get inputFileSystem() {
throw new Error("Cannot read inputFileSystem of a MultiCompiler");
}
/**
* Sets input file system.
* @param {InputFileSystem} value the new input file system
*/
set inputFileSystem(value) {
for (const compiler of this.compilers) {
compiler.inputFileSystem = value;
}
}
get outputFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* Sets output file system.
* @param {OutputFileSystem} value the new output file system
*/
set outputFileSystem(value) {
for (const compiler of this.compilers) {
compiler.outputFileSystem = value;
}
}
get watchFileSystem() {
throw new Error("Cannot read watchFileSystem of a MultiCompiler");
}
/**
* Sets watch file system.
* @param {WatchFileSystem} value the new watch file system
*/
set watchFileSystem(value) {
for (const compiler of this.compilers) {
compiler.watchFileSystem = value;
}
}
/**
* Sets intermediate file system.
* @param {IntermediateFileSystem} value the new intermediate file system
*/
set intermediateFileSystem(value) {
for (const compiler of this.compilers) {
compiler.intermediateFileSystem = value;
}
}
get intermediateFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* Gets infrastructure logger.
* @param {string | (() => string)} name name of the logger, or function called once to get the logger name
* @returns {Logger} a logger with that name
*/
getInfrastructureLogger(name) {
return this.compilers[0].getInfrastructureLogger(name);
}
/**
* Updates dependencies using the provided compiler.
* @param {Compiler} compiler the child compiler
* @param {string[]} dependencies its dependencies
* @returns {void}
*/
setDependencies(compiler, dependencies) {
this.dependencies.set(compiler, dependencies);
}
/**
* Validate dependencies.
* @param {Callback<MultiStats>} callback signals when the validation is complete
* @returns {boolean} true if the dependencies are valid
*/
validateDependencies(callback) {
/** @type {Set<{ source: Compiler, target: Compiler }>} */
const edges = new Set();
/** @type {string[]} */
const missing = [];
/**
* Returns target was found.
* @param {Compiler} compiler compiler
* @returns {boolean} target was found
*/
const targetFound = (compiler) => {
for (const edge of edges) {
if (edge.target === compiler) {
return true;
}
}
return false;
};
/**
* Returns result.
* @param {{ source: Compiler, target: Compiler }} e1 edge 1
* @param {{ source: Compiler, target: Compiler }} e2 edge 2
* @returns {number} result
*/
const sortEdges = (e1, e2) =>
/** @type {string} */
(e1.source.name).localeCompare(/** @type {string} */ (e2.source.name)) ||
/** @type {string} */
(e1.target.name).localeCompare(/** @type {string} */ (e2.target.name));
for (const source of this.compilers) {
const dependencies = this.dependencies.get(source);
if (dependencies) {
for (const dep of dependencies) {
const target = this.compilers.find((c) => c.name === dep);
if (!target) {
missing.push(dep);
} else {
edges.add({
source,
target
});
}
}
}
}
/** @type {string[]} */
const errors = missing.map(
(m) => `Compiler dependency \`${m}\` not found.`
);
const stack = this.compilers.filter((c) => !targetFound(c));
while (stack.length > 0) {
const current = stack.pop();
for (const edge of edges) {
if (edge.source === current) {
edges.delete(edge);
const target = edge.target;
if (!targetFound(target)) {
stack.push(target);
}
}
}
}
if (edges.size > 0) {
/** @type {string[]} */
const lines = [...edges]
.sort(sortEdges)
.map((edge) => `${edge.source.name} -> ${edge.target.name}`);
lines.unshift("Circular dependency found in compiler dependencies.");
errors.unshift(lines.join("\n"));
}
if (errors.length > 0) {
const message = errors.join("\n");
callback(new Error(message));
return false;
}
return true;
}
// TODO webpack 6 remove
/**
* Run with dependencies.
* @deprecated This method should have been private
* @param {Compiler[]} compilers the child compilers
* @param {RunWithDependenciesHandler} fn a handler to run for each compiler
* @param {Callback<Stats[]>} callback the compiler's handler
* @returns {void}
*/
runWithDependencies(compilers, fn, callback) {
/** @type {Set<string>} */
const fulfilledNames = new Set();
let remainingCompilers = compilers;
/**
* Checks whether this multi compiler is dependency fulfilled.
* @param {string} d dependency
* @returns {boolean} when dependency was fulfilled
*/
const isDependencyFulfilled = (d) => fulfilledNames.has(d);
/**
* Gets ready compilers.
* @returns {Compiler[]} compilers
*/
const getReadyCompilers = () => {
/** @type {Compiler[]} */
const readyCompilers = [];
const list = remainingCompilers;
remainingCompilers = [];
for (const c of list) {
const dependencies = this.dependencies.get(c);
const ready =
!dependencies || dependencies.every(isDependencyFulfilled);
if (ready) {
readyCompilers.push(c);
} else {
remainingCompilers.push(c);
}
}
return readyCompilers;
};
/**
* Processes the provided stat.
* @param {Callback<Stats[]>} callback callback
* @returns {void}
*/
const runCompilers = (callback) => {
if (remainingCompilers.length === 0) return callback(null);
asyncLib.map(
getReadyCompilers(),
(compiler, callback) => {
fn(compiler, (err) => {
if (err) return callback(err);
fulfilledNames.add(/** @type {string} */ (compiler.name));
runCompilers(callback);
});
},
(err, results) => {
callback(/** @type {Error | null} */ (err), results);
}
);
};
runCompilers(callback);
}
/**
* Returns result of setup.
* @template SetupResult
* @param {(compiler: Compiler, index: number, doneCallback: Callback<Stats>, isBlocked: () => boolean, setChanged: () => void, setInvalid: () => void) => SetupResult} setup setup a single compiler
* @param {(compiler: Compiler, setupResult: SetupResult, callback: Callback<Stats>) => void} run run/continue a single compiler
* @param {Callback<MultiStats>} callback callback when all compilers are done, result includes Stats of all changed compilers
* @returns {SetupResult[]} result of setup
*/
_runGraph(setup, run, callback) {
/** @typedef {{ compiler: Compiler, setupResult: undefined | SetupResult, result: undefined | Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */
// State transitions for nodes:
// -> blocked (initial)
// blocked -> starting [running++] (when all parents done)
// queued -> starting [running++] (when processing the queue)
// starting -> running (when run has been called)
// running -> done [running--] (when compilation is done)
// done -> pending (when invalidated from file change)
// pending -> blocked [add to queue] (when invalidated from aggregated changes)
// done -> blocked [add to queue] (when invalidated, from parent invalidation)
// running -> running-outdated (when invalidated, either from change or parent invalidation)
// running-outdated -> blocked [running--] (when compilation is done)
/** @type {Node[]} */
const nodes = this.compilers.map((compiler) => ({
compiler,
setupResult: undefined,
result: undefined,
state: "blocked",
children: [],
parents: []
}));
/** @type {Map<string, Node>} */
const compilerToNode = new Map();
for (const node of nodes) {
compilerToNode.set(/** @type {string} */ (node.compiler.name), node);
}
for (const node of nodes) {
const dependencies = this.dependencies.get(node.compiler);
if (!dependencies) continue;
for (const dep of dependencies) {
const parent = /** @type {Node} */ (compilerToNode.get(dep));
node.parents.push(parent);
parent.children.push(node);
}
}
/** @type {ArrayQueue<Node>} */
const queue = new ArrayQueue();
for (const node of nodes) {
if (node.parents.length === 0) {
node.state = "queued";
queue.enqueue(node);
}
}
let errored = false;
let running = 0;
const parallelism = /** @type {number} */ (this._options.parallelism);
/**
* Processes the provided node.
* @param {Node} node node
* @param {(Error | null)=} err error
* @param {Stats=} stats result
* @returns {void}
*/
const nodeDone = (node, err, stats) => {
if (errored) return;
if (err) {
errored = true;
return asyncLib.each(
nodes,
(node, callback) => {
if (node.compiler.watching) {
node.compiler.watching.close(callback);
} else {
callback();
}
},
() => callback(err)
);
}
node.result = stats;
running--;
if (node.state === "running") {
node.state = "done";
for (const child of node.children) {
if (child.state === "blocked") queue.enqueue(child);
}
} else if (node.state === "running-outdated") {
node.state = "blocked";
queue.enqueue(node);
}
processQueue();
};
/**
* Node invalid from parent.
* @param {Node} node node
* @returns {void}
*/
const nodeInvalidFromParent = (node) => {
if (node.state === "done") {
node.state = "blocked";
} else if (node.state === "running") {
node.state = "running-outdated";
}
for (const child of node.children) {
nodeInvalidFromParent(child);
}
};
/**
* Processes the provided node.
* @param {Node} node node
* @returns {void}
*/
const nodeInvalid = (node) => {
if (node.state === "done") {
node.state = "pending";
} else if (node.state === "running") {
node.state = "running-outdated";
}
for (const child of node.children) {
nodeInvalidFromParent(child);
}
};
/**
* Processes the provided node.
* @param {Node} node node
* @returns {void}
*/
const nodeChange = (node) => {
nodeInvalid(node);
if (node.state === "pending") {
node.state = "blocked";
}
if (node.state === "blocked") {
queue.enqueue(node);
processQueue();
}
};
/** @type {SetupResult[]} */
const setupResults = [];
for (const [i, node] of nodes.entries()) {
setupResults.push(
(node.setupResult = setup(
node.compiler,
i,
nodeDone.bind(null, node),
() => node.state !== "starting" && node.state !== "running",
() => nodeChange(node),
() => nodeInvalid(node)
))
);
}
let processing = true;
const processQueue = () => {
if (processing) return;
processing = true;
process.nextTick(processQueueWorker);
};
const processQueueWorker = () => {
// eslint-disable-next-line no-unmodified-loop-condition
while (running < parallelism && queue.length > 0 && !errored) {
const node = /** @type {Node} */ (queue.dequeue());
if (
node.state === "queued" ||
(node.state === "blocked" &&
node.parents.every((p) => p.state === "done"))
) {
running++;
node.state = "starting";
run(
node.compiler,
/** @type {SetupResult} */ (node.setupResult),
nodeDone.bind(null, node)
);
node.state = "running";
}
}
processing = false;
if (
!errored &&
running === 0 &&
nodes.every((node) => node.state === "done")
) {
/** @type {Stats[]} */
const stats = [];
for (const node of nodes) {
const result = node.result;
if (result) {
node.result = undefined;
stats.push(result);
}
}
if (stats.length > 0) {
callback(null, new MultiStats(stats));
}
}
};
processQueueWorker();
return setupResults;
}
/**
* Returns a compiler watcher.
* @param {WatchOptions | WatchOptions[]} watchOptions the watcher's options
* @param {Callback<MultiStats>} handler signals when the call finishes
* @returns {MultiWatching | undefined} a compiler watcher
*/
watch(watchOptions, handler) {
if (this.running) {
handler(new ConcurrentCompilationError());
return;
}
this.running = true;
if (this.validateDependencies(handler)) {
const watchings = this._runGraph(
(compiler, idx, callback, isBlocked, setChanged, setInvalid) => {
const watching = compiler.watch(
Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions,
callback
);
if (watching) {
watching._onInvalid = setInvalid;
watching._onChange = setChanged;
watching._isBlocked = isBlocked;
}
return watching;
},
(compiler, watching, _callback) => {
if (compiler.watching !== watching) return;
if (!watching.running) watching.invalidate();
},
handler
);
return new MultiWatching(watchings, this);
}
return new MultiWatching([], this);
}
/**
* Processes the provided multi stat.
* @param {Callback<MultiStats>} callback signals when the call finishes
* @returns {void}
*/
run(callback) {
if (this.running) {
callback(new ConcurrentCompilationError());
return;
}
this.running = true;
if (this.validateDependencies(callback)) {
this._runGraph(
() => {},
(compiler, setupResult, callback) => compiler.run(callback),
(err, stats) => {
this.running = false;
if (callback !== undefined) {
return callback(err, stats);
}
}
);
}
}
purgeInputFileSystem() {
for (const compiler of this.compilers) {
if (compiler.inputFileSystem && compiler.inputFileSystem.purge) {
compiler.inputFileSystem.purge();
}
}
}
/**
* Processes the provided error callback.
* @param {ErrorCallback} callback signals when the compiler closes
* @returns {void}
*/
close(callback) {
asyncLib.each(
this.compilers,
(compiler, callback) => {
compiler.close(callback);
},
(error) => {
callback(/** @type {Error | null} */ (error));
}
);
}
};

221
node_modules/webpack/lib/MultiStats.js generated vendored Normal file
View File

@@ -0,0 +1,221 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const identifierUtils = require("./util/identifier");
/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
/** @typedef {import("../declarations/WebpackOptions").StatsValue} StatsValue */
/** @typedef {import("./Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */
/** @typedef {import("./Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
/** @typedef {import("./Stats")} Stats */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").KnownStatsCompilation} KnownStatsCompilation */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */
/**
* Returns indent.
* @param {string} str string
* @param {string} prefix pref
* @returns {string} indent
*/
const indent = (str, prefix) => {
const rem = str.replace(/\n([^\n])/g, `\n${prefix}$1`);
return prefix + rem;
};
/** @typedef {StatsOptions} MultiStatsOptions */
/** @typedef {{ version: boolean, hash: boolean, errorsCount: boolean, warningsCount: boolean, errors: boolean, warnings: boolean, children: NormalizedStatsOptions[] }} ChildOptions */
class MultiStats {
/**
* Creates an instance of MultiStats.
* @param {Stats[]} stats the child stats
*/
constructor(stats) {
this.stats = stats;
}
get hash() {
return this.stats.map((stat) => stat.hash).join("");
}
/**
* Checks whether this multi stats has errors.
* @returns {boolean} true if a child compilation encountered an error
*/
hasErrors() {
return this.stats.some((stat) => stat.hasErrors());
}
/**
* Checks whether this multi stats has warnings.
* @returns {boolean} true if a child compilation had a warning
*/
hasWarnings() {
return this.stats.some((stat) => stat.hasWarnings());
}
/**
* Create child options.
* @param {undefined | StatsValue} options stats options
* @param {CreateStatsOptionsContext} context context
* @returns {ChildOptions} context context
*/
_createChildOptions(options, context) {
const getCreateStatsOptions = () => {
if (!options) {
options = {};
}
const { children: childrenOptions = undefined, ...baseOptions } =
typeof options === "string"
? { preset: options }
: /** @type {StatsOptions} */ (options);
return { childrenOptions, baseOptions };
};
const children = this.stats.map((stat, idx) => {
if (typeof options === "boolean") {
return stat.compilation.createStatsOptions(options, context);
}
const { childrenOptions, baseOptions } = getCreateStatsOptions();
const childOptions = Array.isArray(childrenOptions)
? childrenOptions[idx]
: childrenOptions;
if (typeof childOptions === "boolean") {
return stat.compilation.createStatsOptions(childOptions, context);
}
return stat.compilation.createStatsOptions(
{
...baseOptions,
...(typeof childOptions === "string"
? { preset: childOptions }
: childOptions && typeof childOptions === "object"
? childOptions
: undefined)
},
context
);
});
return {
version: children.every((o) => o.version),
hash: children.every((o) => o.hash),
errorsCount: children.every((o) => o.errorsCount),
warningsCount: children.every((o) => o.warningsCount),
errors: children.every((o) => o.errors),
warnings: children.every((o) => o.warnings),
children
};
}
/**
* Returns json output.
* @param {StatsValue=} options stats options
* @returns {StatsCompilation} json output
*/
toJson(options) {
const childOptions = this._createChildOptions(options, {
forToString: false
});
/** @type {KnownStatsCompilation} */
const obj = {};
obj.children = this.stats.map((stat, idx) => {
const obj = stat.toJson(childOptions.children[idx]);
const compilationName = stat.compilation.name;
const name =
compilationName &&
identifierUtils.makePathsRelative(
stat.compilation.compiler.context,
compilationName,
stat.compilation.compiler.root
);
obj.name = name;
return obj;
});
if (childOptions.version) {
obj.version = obj.children[0].version;
}
if (childOptions.hash) {
obj.hash = obj.children.map((j) => j.hash).join("");
}
/**
* Returns result.
* @param {StatsCompilation} j stats error
* @param {StatsError} obj Stats error
* @returns {StatsError} result
*/
const mapError = (j, obj) => ({
...obj,
compilerPath: obj.compilerPath ? `${j.name}.${obj.compilerPath}` : j.name
});
if (childOptions.errors) {
obj.errors = [];
for (const j of obj.children) {
const errors =
/** @type {NonNullable<KnownStatsCompilation["errors"]>} */
(j.errors);
for (const i of errors) {
obj.errors.push(mapError(j, i));
}
}
}
if (childOptions.warnings) {
obj.warnings = [];
for (const j of obj.children) {
const warnings =
/** @type {NonNullable<KnownStatsCompilation["warnings"]>} */
(j.warnings);
for (const i of warnings) {
obj.warnings.push(mapError(j, i));
}
}
}
if (childOptions.errorsCount) {
obj.errorsCount = 0;
for (const j of obj.children) {
obj.errorsCount += /** @type {number} */ (j.errorsCount);
}
}
if (childOptions.warningsCount) {
obj.warningsCount = 0;
for (const j of obj.children) {
obj.warningsCount += /** @type {number} */ (j.warningsCount);
}
}
return obj;
}
/**
* Returns a string representation.
* @param {StatsValue=} options stats options
* @returns {string} string output
*/
toString(options) {
const childOptions = this._createChildOptions(options, {
forToString: true
});
const results = this.stats.map((stat, idx) => {
const str = stat.toString(childOptions.children[idx]);
const compilationName = stat.compilation.name;
const name =
compilationName &&
identifierUtils
.makePathsRelative(
stat.compilation.compiler.context,
compilationName,
stat.compilation.compiler.root
)
.replace(/\|/g, " ");
if (!str) return str;
return name ? `${name}:\n${indent(str, " ")}` : str;
});
return results.filter(Boolean).join("\n\n");
}
}
module.exports = MultiStats;

80
node_modules/webpack/lib/MultiWatching.js generated vendored Normal file
View File

@@ -0,0 +1,80 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
/** @typedef {import("./MultiCompiler")} MultiCompiler */
/** @typedef {import("./Watching")} Watching */
/** @typedef {import("./webpack").ErrorCallback} ErrorCallback */
class MultiWatching {
/**
* Creates an instance of MultiWatching.
* @param {Watching[]} watchings child compilers' watchers
* @param {MultiCompiler} compiler the compiler
*/
constructor(watchings, compiler) {
this.watchings = watchings;
this.compiler = compiler;
}
/**
* Processes the provided error callback.
* @param {ErrorCallback=} callback signals when the build has completed again
* @returns {void}
*/
invalidate(callback) {
if (callback) {
asyncLib.each(
this.watchings,
(watching, callback) => watching.invalidate(callback),
(err) => {
callback(/** @type {Error | null} */ (err));
}
);
} else {
for (const watching of this.watchings) {
watching.invalidate();
}
}
}
suspend() {
for (const watching of this.watchings) {
watching.suspend();
}
}
resume() {
for (const watching of this.watchings) {
watching.resume();
}
}
/**
* Processes the provided error callback.
* @param {ErrorCallback} callback signals when the watcher is closed
* @returns {void}
*/
close(callback) {
asyncLib.each(
this.watchings,
(watching, finishedCallback) => {
watching.close(finishedCallback);
},
(err) => {
this.compiler.hooks.watchClose.call();
if (typeof callback === "function") {
this.compiler.running = false;
callback(/** @type {Error | null} */ (err));
}
}
);
}
}
module.exports = MultiWatching;

30
node_modules/webpack/lib/NoEmitOnErrorsPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "NoEmitOnErrorsPlugin";
class NoEmitOnErrorsPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.shouldEmit.tap(PLUGIN_NAME, (compilation) => {
if (compilation.getStats().hasErrors()) return false;
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.shouldRecord.tap(PLUGIN_NAME, () => {
if (compilation.getStats().hasErrors()) return false;
});
});
}
}
module.exports = NoEmitOnErrorsPlugin;

596
node_modules/webpack/lib/NodeStuffPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,596 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const CachedConstDependency = require("./dependencies/CachedConstDependency");
const ConstDependency = require("./dependencies/ConstDependency");
const ExternalModuleDependency = require("./dependencies/ExternalModuleDependency");
const ExternalModuleInitFragmentDependency = require("./dependencies/ExternalModuleInitFragmentDependency");
const ImportMetaPlugin = require("./dependencies/ImportMetaPlugin");
const NodeStuffInWebError = require("./errors/NodeStuffInWebError");
const { evaluateToString } = require("./javascript/JavascriptParserHelpers");
const { relative } = require("./util/fs");
const { parseResource } = require("./util/identifier");
/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("../declarations/WebpackOptions").NodeOptions} NodeOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Expression} Expression */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const PLUGIN_NAME = "NodeStuffPlugin";
const URL_MODULE_CONSTANT_FUNCTION_NAME = "__webpack_fileURLToPath__";
class NodeStuffPlugin {
/**
* Creates an instance of NodeStuffPlugin.
* @param {NodeOptions} options options
*/
constructor(options) {
this.options = options;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { options } = this;
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ExternalModuleDependency,
new ExternalModuleDependency.Template()
);
compilation.dependencyTemplates.set(
ExternalModuleInitFragmentDependency,
new ExternalModuleInitFragmentDependency.Template()
);
/**
* Processes the provided parser.
* @param {JavascriptParser} parser the parser
* @param {NodeOptions} nodeOptions options
* @returns {void}
*/
const globalHandler = (parser, nodeOptions) => {
/**
* Returns const dependency.
* @param {Expression} expr expression
* @returns {ConstDependency} const dependency
*/
const getGlobalDep = (expr) => {
if (compilation.outputOptions.environment.globalThis) {
return new ConstDependency(
"globalThis",
/** @type {Range} */ (expr.range)
);
}
return new ConstDependency(
RuntimeGlobals.global,
/** @type {Range} */ (expr.range),
[RuntimeGlobals.global]
);
};
const withWarning = nodeOptions.global === "warn";
parser.hooks.expression.for("global").tap(PLUGIN_NAME, (expr) => {
const dep = getGlobalDep(expr);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
if (withWarning) {
parser.state.module.addWarning(
new NodeStuffInWebError(
dep.loc,
"global",
"The global namespace object is a Node.js feature and isn't available in browsers."
)
);
}
});
parser.hooks.rename.for("global").tap(PLUGIN_NAME, (expr) => {
const dep = getGlobalDep(expr);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return false;
});
};
const hooks = ImportMetaPlugin.getCompilationHooks(compilation);
/**
* Sets module constant.
* @param {JavascriptParser} parser the parser
* @param {"__filename" | "__dirname" | "import.meta.filename" | "import.meta.dirname"} expressionName expression name
* @param {(module: NormalModule) => string} fn function
* @param {"filename" | "dirname"} property a property
* @returns {void}
*/
const setModuleConstant = (parser, expressionName, fn, property) => {
parser.hooks.expression
.for(expressionName)
.tap(PLUGIN_NAME, (expr) => {
const dep = new ConstDependency(
fn(parser.state.module),
/** @type {Range} */
(expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
if (
expressionName === "import.meta.filename" ||
expressionName === "import.meta.dirname"
) {
hooks.propertyInDestructuring.tap(PLUGIN_NAME, (usingProperty) => {
if (usingProperty.id === property) {
return `${property}: ${fn(parser.state.module)},`;
}
});
}
};
/**
* Sets cached module constant.
* @param {JavascriptParser} parser the parser
* @param {"__filename" | "__dirname" | "import.meta.filename" | "import.meta.dirname"} expressionName expression name
* @param {(module: NormalModule) => string} fn function
* @param {"filename" | "dirname"} property a property
* @param {string=} warning warning
* @returns {void}
*/
const setCachedModuleConstant = (
parser,
expressionName,
fn,
property,
warning
) => {
parser.hooks.expression
.for(expressionName)
.tap(PLUGIN_NAME, (expr) => {
const dep = new CachedConstDependency(
JSON.stringify(fn(parser.state.module)),
/** @type {Range} */
(expr.range),
`__webpack_${property}__`
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
if (warning) {
parser.state.module.addWarning(
new NodeStuffInWebError(dep.loc, expressionName, warning)
);
}
return true;
});
if (
expressionName === "import.meta.filename" ||
expressionName === "import.meta.dirname"
) {
hooks.propertyInDestructuring.tap(PLUGIN_NAME, (usingProperty) => {
if (property === usingProperty.id) {
if (warning) {
parser.state.module.addWarning(
new NodeStuffInWebError(
usingProperty.loc,
expressionName,
warning
)
);
}
return `${property}: ${JSON.stringify(fn(parser.state.module))},`;
}
});
}
};
/**
* Updates constant using the provided parser.
* @param {JavascriptParser} parser the parser
* @param {"__filename" | "__dirname" | "import.meta.filename" | "import.meta.dirname"} expressionName expression name
* @param {string} value value
* @param {"filename" | "dirname"} property a property
* @param {string=} warning warning
* @returns {void}
*/
const setConstant = (
parser,
expressionName,
value,
property,
warning
) =>
setCachedModuleConstant(
parser,
expressionName,
() => value,
property,
warning
);
/**
* Sets url module constant.
* @param {JavascriptParser} parser the parser
* @param {"__filename" | "__dirname" | "import.meta.filename" | "import.meta.dirname"} expressionName expression name
* @param {"dirname" | "filename"} property property
* @param {() => string} value function to get value
* @returns {void}
*/
const setUrlModuleConstant = (
parser,
expressionName,
property,
value
) => {
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;
// 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
if (
environment.importMetaDirnameAndFilename ||
(compiler.platform.web === null &&
compiler.platform.node === null &&
module)
) {
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);
return true;
});
if (
expressionName === "import.meta.filename" ||
expressionName === "import.meta.dirname"
) {
hooks.propertyInDestructuring.tap(PLUGIN_NAME, (usingProperty) => {
if (property === usingProperty.id) {
const { importMetaName, environment, module } =
compilation.outputOptions;
if (
environment.importMetaDirnameAndFilename ||
(compiler.platform.web === null &&
compiler.platform.node === null &&
module)
) {
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}__,`;
}
const dep = new ExternalModuleDependency(
"url",
[
{
name: "fileURLToPath",
value: URL_MODULE_CONSTANT_FUNCTION_NAME
}
],
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}: __webpack_${property}__,`;
}
});
}
};
/**
* Dirname and filename handler.
* @param {JavascriptParser} parser the parser
* @param {NodeOptions} nodeOptions options
* @param {{ dirname: "__dirname" | "import.meta.dirname", filename: "__filename" | "import.meta.filename" }} identifiers options
* @returns {void}
*/
const dirnameAndFilenameHandler = (
parser,
nodeOptions,
{ dirname, filename }
) => {
// Keep `import.meta.filename` in code
if (
nodeOptions.__filename === false &&
filename === "import.meta.filename"
) {
setModuleConstant(parser, filename, () => filename, "filename");
}
if (nodeOptions.__filename) {
switch (nodeOptions.__filename) {
case "mock":
setConstant(parser, filename, "/index.js", "filename");
break;
case "warn-mock":
setConstant(
parser,
filename,
"/index.js",
"filename",
"__filename is a Node.js feature and isn't available in browsers."
);
break;
case "node-module": {
const importMetaName = compilation.outputOptions.importMetaName;
setUrlModuleConstant(
parser,
filename,
"filename",
() => `${importMetaName}.url`
);
break;
}
case "eval-only":
// Keep `import.meta.filename` in the source code for the ES module output, or create a fallback using `import.meta.url` if possible
if (compilation.outputOptions.module) {
const { importMetaName } = compilation.outputOptions;
setUrlModuleConstant(
parser,
filename,
"filename",
() => `${importMetaName}.url`
);
}
// Replace `import.meta.filename` with `__filename` for the non-ES module output
else if (filename === "import.meta.filename") {
setModuleConstant(
parser,
filename,
() => "__filename",
"filename"
);
}
break;
case true:
setCachedModuleConstant(
parser,
filename,
(module) =>
relative(
/** @type {InputFileSystem} */ (compiler.inputFileSystem),
compiler.context,
module.resource
),
"filename"
);
break;
}
parser.hooks.evaluateIdentifier
.for("__filename")
.tap(PLUGIN_NAME, (expr) => {
if (!parser.state.module) return;
const resource = parseResource(parser.state.module.resource);
return evaluateToString(resource.path)(expr);
});
}
// Keep `import.meta.dirname` in code
if (
nodeOptions.__dirname === false &&
dirname === "import.meta.dirname"
) {
setModuleConstant(parser, dirname, () => dirname, "dirname");
}
if (nodeOptions.__dirname) {
switch (nodeOptions.__dirname) {
case "mock":
setConstant(parser, dirname, "/", "dirname");
break;
case "warn-mock":
setConstant(
parser,
dirname,
"/",
"dirname",
"__dirname is a Node.js feature and isn't available in browsers."
);
break;
case "node-module": {
const importMetaName = compilation.outputOptions.importMetaName;
setUrlModuleConstant(
parser,
dirname,
"dirname",
() => `${importMetaName}.url.replace(/\\/(?:[^\\/]*)$/, "")`
);
break;
}
case "eval-only":
// Keep `import.meta.dirname` in the source code for the ES module output and replace `__dirname` on `import.meta.dirname`
if (compilation.outputOptions.module) {
const { importMetaName } = compilation.outputOptions;
setUrlModuleConstant(
parser,
dirname,
"dirname",
() => `${importMetaName}.url.replace(/\\/(?:[^\\/]*)$/, "")`
);
}
// Replace `import.meta.dirname` with `__dirname` for the non-ES module output
else if (dirname === "import.meta.dirname") {
setModuleConstant(
parser,
dirname,
() => "__dirname",
"dirname"
);
}
break;
case true:
setCachedModuleConstant(
parser,
dirname,
(module) =>
relative(
/** @type {InputFileSystem} */ (compiler.inputFileSystem),
compiler.context,
/** @type {string} */ (module.context)
),
"dirname"
);
break;
}
parser.hooks.evaluateIdentifier
.for(dirname)
.tap(PLUGIN_NAME, (expr) => {
if (!parser.state.module) return;
return evaluateToString(
/** @type {string} */
(parser.state.module.context)
)(expr);
});
}
};
/**
* Handles the hook callback for this code path.
* @param {JavascriptParser} parser the parser
* @param {JavascriptParserOptions} parserOptions the javascript parser options
* @param {boolean} a true when we need to handle `__filename` and `__dirname`, otherwise false
* @param {boolean} b true when we need to handle `import.meta.filename` and `import.meta.dirname`, otherwise false
*/
const handler = (parser, parserOptions, a, b) => {
if (b && parserOptions.node === false) {
// Keep `import.meta.dirname` and `import.meta.filename` in code
setModuleConstant(
parser,
"import.meta.dirname",
() => "import.meta.dirname",
"dirname"
);
setModuleConstant(
parser,
"import.meta.filename",
() => "import.meta.filename",
"filename"
);
return;
}
let localOptions = options;
if (parserOptions.node) {
localOptions = { ...localOptions, ...parserOptions.node };
}
if (localOptions.global !== false) {
globalHandler(parser, localOptions);
}
if (a) {
dirnameAndFilenameHandler(parser, localOptions, {
dirname: "__dirname",
filename: "__filename"
});
}
if (b && parserOptions.importMeta !== false) {
dirnameAndFilenameHandler(parser, localOptions, {
dirname: "import.meta.dirname",
filename: "import.meta.filename"
});
}
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, (parser, parserOptions) => {
handler(parser, parserOptions, true, true);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, (parser, parserOptions) => {
handler(parser, parserOptions, true, false);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, (parser, parserOptions) => {
handler(parser, parserOptions, false, true);
});
}
);
}
}
module.exports = NodeStuffPlugin;

2290
node_modules/webpack/lib/NormalModule.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1519
node_modules/webpack/lib/NormalModuleFactory.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,75 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { dirname, join } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {(resolveData: ResolveData) => void} ModuleReplacer */
const PLUGIN_NAME = "NormalModuleReplacementPlugin";
class NormalModuleReplacementPlugin {
/**
* Create an instance of the plugin
* @param {RegExp} resourceRegExp the resource matcher
* @param {string | ModuleReplacer} newResource the resource replacement
*/
constructor(resourceRegExp, newResource) {
this.resourceRegExp = resourceRegExp;
this.newResource = newResource;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newResource = this.newResource;
compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => {
nmf.hooks.beforeResolve.tap(PLUGIN_NAME, (result) => {
if (resourceRegExp.test(result.request)) {
if (typeof newResource === "function") {
newResource(result);
} else {
result.request = newResource;
}
}
});
nmf.hooks.afterResolve.tap(PLUGIN_NAME, (result) => {
const createData = result.createData;
if (resourceRegExp.test(/** @type {string} */ (createData.resource))) {
if (typeof newResource === "function") {
newResource(result);
} else {
const fs =
/** @type {InputFileSystem} */
(compiler.inputFileSystem);
if (
newResource.startsWith("/") ||
(newResource.length > 1 && newResource[1] === ":")
) {
createData.resource = newResource;
} else {
createData.resource = join(
fs,
dirname(fs, /** @type {string} */ (createData.resource)),
newResource
);
}
}
}
});
});
}
}
module.exports = NormalModuleReplacementPlugin;

25
node_modules/webpack/lib/NullFactory.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ModuleFactory = require("./ModuleFactory");
/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
class NullFactory extends ModuleFactory {
/**
* Processes the provided data.
* @param {ModuleFactoryCreateData} data data object
* @param {ModuleFactoryCallback} callback callback
* @returns {void}
*/
create(data, callback) {
return callback();
}
}
module.exports = NullFactory;

10
node_modules/webpack/lib/OptimizationStages.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Florent Cailhol @ooflorent
*/
"use strict";
module.exports.STAGE_ADVANCED = 10;
module.exports.STAGE_BASIC = -10;
module.exports.STAGE_DEFAULT = 0;

25
node_modules/webpack/lib/OptionsApply.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./config/normalization").WebpackOptionsInterception} WebpackOptionsInterception */
/** @typedef {import("./Compiler")} Compiler */
class OptionsApply {
/**
* Returns options object.
* @param {WebpackOptions} options options object
* @param {Compiler} compiler compiler object
* @param {WebpackOptionsInterception=} interception intercepted options
* @returns {WebpackOptions} options object
*/
process(options, compiler, interception) {
return options;
}
}
module.exports = OptionsApply;

42
node_modules/webpack/lib/Parser.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {Record<string, EXPECTED_ANY>} PreparsedAst */
/**
* Defines the parser state base type used by this module.
* @typedef {object} ParserStateBase
* @property {string | Buffer} source
* @property {NormalModule} current
* @property {NormalModule} module
* @property {Compilation} compilation
* @property {WebpackOptions} options
*/
/** @typedef {ParserStateBase & Record<string, EXPECTED_ANY>} ParserState */
class Parser {
/* istanbul ignore next */
/**
* Parses the provided source and updates the parser state.
* @abstract
* @param {string | Buffer | PreparsedAst} source the source to parse
* @param {ParserState} state the parser state
* @returns {ParserState} the parser state
*/
parse(source, state) {
const AbstractMethodError = require("./errors/AbstractMethodError");
throw new AbstractMethodError();
}
}
module.exports = Parser;

42
node_modules/webpack/lib/PlatformPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Ivan Kopeykin @vankop
*/
"use strict";
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./config/target").PlatformTargetProperties} PlatformTargetProperties */
const PLUGIN_NAME = "PlatformPlugin";
/**
* Should be used only for "target === false" or
* when you want to overwrite platform target properties
*/
class PlatformPlugin {
/**
* Creates an instance of PlatformPlugin.
* @param {Partial<PlatformTargetProperties>} platform target properties
*/
constructor(platform) {
/** @type {Partial<PlatformTargetProperties>} */
this.platform = platform;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.environment.tap(PLUGIN_NAME, () => {
compiler.platform = {
...compiler.platform,
...this.platform
};
});
}
}
module.exports = PlatformPlugin;

57
node_modules/webpack/lib/PrefetchPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,57 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const PrefetchDependency = require("./dependencies/PrefetchDependency");
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "PrefetchPlugin";
class PrefetchPlugin {
/**
* Creates an instance of PrefetchPlugin.
* @param {string} context context or request if context is not set
* @param {string=} request request
*/
constructor(context, request) {
if (request) {
this.context = context;
this.request = request;
} else {
this.context = null;
this.request = context;
}
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
PrefetchDependency,
normalModuleFactory
);
}
);
compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
compilation.addModuleChain(
this.context || compiler.context,
new PrefetchDependency(this.request),
(err) => {
callback(err);
}
);
});
}
}
module.exports = PrefetchPlugin;

812
node_modules/webpack/lib/ProgressPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,812 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Compiler = require("./Compiler");
const MultiCompiler = require("./MultiCompiler");
const NormalModule = require("./NormalModule");
const { contextify } = require("./util/identifier");
const memoize = require("./util/memoize");
const getColors = memoize(() => {
const cli = require("./cli");
return cli.createColors({ useColor: cli.isColorSupported() });
});
const BAR_LENGTH = 25;
const BLOCK_CHAR = "━";
const BULLET_ICON = "●";
/** @typedef {import("tapable").Tap} Tap */
/**
* Defines the hook type used by this module.
* @template T, R, AdditionalOptions
* @typedef {import("tapable").Hook<T, R, AdditionalOptions>} Hook
*/
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */
/** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./cli").Colors} Colors */
/**
* Defines the async queue type used by this module.
* @template T, K, R
* @typedef {import("./util/AsyncQueue")<T, K, R>} AsyncQueue
*/
/**
* Defines the counts data type used by this module.
* @typedef {object} CountsData
* @property {number} modulesCount modules count
* @property {number} dependenciesCount dependencies count
*/
/**
* Returns median.
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @returns {number} median
*/
const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
/** @typedef {(percentage: number, msg: string, ...args: string[]) => void} HandlerFn */
/**
* @param {Logger} logger logger
* @param {{ value: string | undefined, time: number }[]} lastStateInfo mutable state
* @param {number} percentage percentage
* @param {string} msg msg
* @param {string[]} args args
*/
const reportProfile = (logger, lastStateInfo, percentage, msg, args) => {
if (percentage === 0) {
lastStateInfo.length = 0;
}
const fullState = [msg, ...args];
const state = fullState.map((s) => s.replace(/\d+\/\d+ /g, ""));
const now = Date.now();
const len = Math.max(state.length, lastStateInfo.length);
for (let i = len; i >= 0; i--) {
const stateItem = i < state.length ? state[i] : undefined;
const lastStateItem =
i < lastStateInfo.length ? lastStateInfo[i] : undefined;
if (lastStateItem) {
if (stateItem !== lastStateItem.value) {
const diff = now - lastStateItem.time;
if (lastStateItem.value) {
let reportState = lastStateItem.value;
if (i > 0) {
reportState = `${lastStateInfo[i - 1].value} > ${reportState}`;
}
const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`;
const d = diff;
// This depends on timing so we ignore it for coverage
/* eslint-disable no-lone-blocks */
/* istanbul ignore next */
{
if (d > 10000) {
logger.error(stateMsg);
} else if (d > 1000) {
logger.warn(stateMsg);
} else if (d > 10) {
logger.info(stateMsg);
} else if (d > 5) {
logger.log(stateMsg);
} else {
logger.debug(stateMsg);
}
}
/* eslint-enable no-lone-blocks */
}
if (stateItem === undefined) {
lastStateInfo.length = i;
} else {
lastStateItem.value = stateItem;
lastStateItem.time = now;
lastStateInfo.length = i + 1;
}
}
} else {
lastStateInfo[i] = {
value: stateItem,
time: now
};
}
}
};
/**
* @param {string} name progress bar name
* @param {string} color progress bar color
* @returns {(percentage: number) => string} bar renderer
*/
const createReportBar = (name, color) => {
const c = getColors();
return (percentage) => {
const w = Math.round(percentage * BAR_LENGTH);
const filled = BLOCK_CHAR.repeat(w);
const empty = BLOCK_CHAR.repeat(BAR_LENGTH - w);
const colorFn =
color in c ? c[/** @type {keyof Colors} */ (color)] : c.green;
return `${[BULLET_ICON, name, filled].map(colorFn).join(" ")}${c.white(empty)}`;
};
};
/** @typedef {Required<Exclude<NonNullable<ProgressPluginOptions["progressBar"]>, boolean>>} ProgressBarOptions */
/**
* Creates a default handler.
* @param {boolean | null | undefined} profile need profile
* @param {Logger} logger logger
* @param {ProgressBarOptions | false=} progressBar render bar
* @returns {HandlerFn} default handler
*/
const createDefaultHandler = (profile, logger, progressBar) => {
/** @type {{ value: string | undefined, time: number }[]} */
const lastStateInfo = [];
/** @type {HandlerFn} */
const defaultHandler = (percentage, msg, ...args) => {
if (profile) {
reportProfile(logger, lastStateInfo, percentage, msg, args);
}
if (progressBar) {
const reportBar = createReportBar(progressBar.name, progressBar.color);
const c = getColors();
/** @type {string} */
const currentBar = reportBar(percentage);
if (percentage === 1) {
logger.status();
} else if (msg) {
logger.status(
`${currentBar} (${Math.floor(percentage * 100)}%)`,
`\n${[msg, ...args].map(c.gray).join(" ")}`
);
} else {
logger.status(`${currentBar} (${Math.floor(percentage * 100)}%)`);
}
return;
}
logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args);
if (percentage === 1 || (!msg && args.length === 0)) logger.status();
};
return defaultHandler;
};
const SKIPPED_QUEUE_CONTEXTS = ["import-module", "load-module"];
/**
* Defines the report progress callback.
* @callback ReportProgress
* @param {number} p percentage
* @param {...string} args additional arguments
* @returns {void}
*/
/** @type {WeakMap<Compiler, ReportProgress | undefined>} */
const progressReporters = new WeakMap();
const PLUGIN_NAME = "ProgressPlugin";
/** @type {Required<Omit<ProgressPluginOptions, "handler">>} */
const DEFAULT_OPTIONS = {
profile: false,
modulesCount: 5000,
dependenciesCount: 10000,
modules: true,
dependencies: true,
activeModules: false,
entries: true,
percentBy: null,
progressBar: false
};
class ProgressPlugin {
/**
* Returns a progress reporter, if any.
* @param {Compiler} compiler the current compiler
* @returns {ReportProgress | undefined} a progress reporter, if any
*/
static getReporter(compiler) {
return progressReporters.get(compiler);
}
/**
* Creates an instance of ProgressPlugin.
* @param {ProgressPluginArgument} options options
*/
constructor(options = {}) {
if (typeof options === "function") {
options = {
handler: options
};
}
/** @type {ProgressPluginOptions} */
this.options = options;
const merged = { ...DEFAULT_OPTIONS, ...options };
this.profile = merged.profile;
this.handler = merged.handler;
this.modulesCount = merged.modulesCount;
this.dependenciesCount = merged.dependenciesCount;
this.showEntries = merged.entries;
this.showModules = merged.modules;
this.showDependencies = merged.dependencies;
this.showActiveModules = merged.activeModules;
this.percentBy = merged.percentBy;
const progressBar = merged.progressBar === true ? {} : merged.progressBar;
/** @type {ProgressBarOptions | false} */
this.progressBar = progressBar
? { name: "Build", color: "green", ...progressBar }
: false;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler | MultiCompiler} compiler webpack compiler
* @returns {void}
*/
apply(compiler) {
const handler =
this.handler ||
createDefaultHandler(
this.profile,
compiler.getInfrastructureLogger("webpack.Progress"),
this.progressBar
);
if (compiler instanceof MultiCompiler) {
this._applyOnMultiCompiler(compiler, handler);
} else if (compiler instanceof Compiler) {
this._applyOnCompiler(compiler, handler);
}
}
/**
* Apply on multi compiler.
* @param {MultiCompiler} compiler webpack multi-compiler
* @param {HandlerFn} handler function that executes for every progress step
* @returns {void}
*/
_applyOnMultiCompiler(compiler, handler) {
const states = compiler.compilers.map(
() => /** @type {[number, ...string[]]} */ ([0])
);
for (const [idx, item] of compiler.compilers.entries()) {
new ProgressPlugin((p, msg, ...args) => {
states[idx] = [p, msg, ...args];
let sum = 0;
for (const [p] of states) sum += p;
handler(sum / states.length, `[${idx}] ${msg}`, ...args);
}).apply(item);
}
}
/**
* Processes the provided compiler.
* @param {Compiler} compiler webpack compiler
* @param {HandlerFn} handler function that executes for every progress step
* @returns {void}
*/
_applyOnCompiler(compiler, handler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
() => require("../schemas/plugins/ProgressPlugin.json"),
this.options,
{
name: "Progress Plugin",
baseDataPath: "options"
},
(options) => require("../schemas/plugins/ProgressPlugin.check")(options)
);
});
const showEntries = this.showEntries;
const showModules = this.showModules;
const showDependencies = this.showDependencies;
const showActiveModules = this.showActiveModules;
let lastActiveModule = "";
let currentLoader = "";
let lastModulesCount = 0;
let lastDependenciesCount = 0;
let lastEntriesCount = 0;
let modulesCount = 0;
let skippedModulesCount = 0;
let dependenciesCount = 0;
let skippedDependenciesCount = 0;
let entriesCount = 1;
let doneModules = 0;
let doneDependencies = 0;
let doneEntries = 0;
/** @type {Set<string>} */
const activeModules = new Set();
let lastUpdate = 0;
const updateThrottled = () => {
if (lastUpdate + 500 < Date.now()) update();
};
const update = () => {
/** @type {string[]} */
const items = [];
const percentByModules =
doneModules /
Math.max(lastModulesCount || this.modulesCount || 1, modulesCount);
const percentByEntries =
doneEntries /
Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount);
const percentByDependencies =
doneDependencies /
Math.max(lastDependenciesCount || 1, dependenciesCount);
/** @type {number} */
let percentageFactor;
switch (this.percentBy) {
case "entries":
percentageFactor = percentByEntries;
break;
case "dependencies":
percentageFactor = percentByDependencies;
break;
case "modules":
percentageFactor = percentByModules;
break;
default:
percentageFactor = median3(
percentByModules,
percentByEntries,
percentByDependencies
);
}
const percentage = 0.1 + percentageFactor * 0.55;
if (currentLoader) {
items.push(
`import loader ${contextify(
compiler.context,
currentLoader,
compiler.root
)}`
);
} else {
/** @type {string[]} */
const statItems = [];
if (showEntries) {
statItems.push(`${doneEntries}/${entriesCount} entries`);
}
if (showDependencies) {
statItems.push(
`${doneDependencies}/${dependenciesCount} dependencies`
);
}
if (showModules) {
statItems.push(`${doneModules}/${modulesCount} modules`);
}
if (showActiveModules) {
statItems.push(`${activeModules.size} active`);
}
if (statItems.length > 0) {
items.push(statItems.join(" "));
}
if (showActiveModules) {
items.push(lastActiveModule);
}
}
handler(percentage, "building", ...items);
lastUpdate = Date.now();
};
/**
* Processes the provided factorize queue.
* @template T
* @param {AsyncQueue<FactorizeModuleOptions, string, Module | ModuleFactoryResult>} factorizeQueue async queue
* @param {T} _item item
*/
const factorizeAdd = (factorizeQueue, _item) => {
if (SKIPPED_QUEUE_CONTEXTS.includes(factorizeQueue.getContext())) {
skippedDependenciesCount++;
}
dependenciesCount++;
if (dependenciesCount < 50 || dependenciesCount % 100 === 0) {
updateThrottled();
}
};
const factorizeDone = () => {
doneDependencies++;
if (doneDependencies < 50 || doneDependencies % 100 === 0) {
updateThrottled();
}
};
/**
* Processes the provided add module queue.
* @template T
* @param {AsyncQueue<Module, string, Module>} addModuleQueue async queue
* @param {T} _item item
*/
const moduleAdd = (addModuleQueue, _item) => {
if (SKIPPED_QUEUE_CONTEXTS.includes(addModuleQueue.getContext())) {
skippedModulesCount++;
}
modulesCount++;
if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled();
};
// only used when showActiveModules is set
/**
* Processes the provided module.
* @param {Module} module the module
*/
const moduleBuild = (module) => {
const ident = module.identifier();
if (ident) {
activeModules.add(ident);
lastActiveModule = ident;
update();
}
};
/**
* Processes the provided entry.
* @param {Dependency} entry entry dependency
* @param {EntryOptions} options options object
*/
const entryAdd = (entry, options) => {
entriesCount++;
if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled();
};
/**
* Processes the provided module.
* @param {Module} module the module
*/
const moduleDone = (module) => {
doneModules++;
if (showActiveModules) {
const ident = module.identifier();
if (ident) {
activeModules.delete(ident);
if (lastActiveModule === ident) {
lastActiveModule = "";
for (const m of activeModules) {
lastActiveModule = m;
}
update();
return;
}
}
}
if (doneModules < 50 || doneModules % 100 === 0) updateThrottled();
};
/**
* Processes the provided entry.
* @param {Dependency} entry entry dependency
* @param {EntryOptions} options options object
*/
const entryDone = (entry, options) => {
doneEntries++;
update();
};
const cache = compiler.getCache(PLUGIN_NAME).getItemCache("counts", null);
/** @type {Promise<CountsData> | undefined} */
let cacheGetPromise;
compiler.hooks.beforeCompile.tap(PLUGIN_NAME, () => {
if (!cacheGetPromise) {
cacheGetPromise = cache.getPromise().then(
(data) => {
if (data) {
lastModulesCount = lastModulesCount || data.modulesCount;
lastDependenciesCount =
lastDependenciesCount || data.dependenciesCount;
}
return data;
},
(_err) => {
// Ignore error
}
);
}
});
compiler.hooks.afterCompile.tapPromise(PLUGIN_NAME, (compilation) => {
if (compilation.compiler.isChild()) return Promise.resolve();
return /** @type {Promise<CountsData>} */ (cacheGetPromise).then(
async (oldData) => {
const realModulesCount = modulesCount - skippedModulesCount;
const realDependenciesCount =
dependenciesCount - skippedDependenciesCount;
if (
!oldData ||
oldData.modulesCount !== realModulesCount ||
oldData.dependenciesCount !== realDependenciesCount
) {
await cache.storePromise({
modulesCount: realModulesCount,
dependenciesCount: realDependenciesCount
});
}
}
);
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (compilation.compiler.isChild()) return;
lastModulesCount = modulesCount;
lastEntriesCount = entriesCount;
lastDependenciesCount = dependenciesCount;
modulesCount =
skippedModulesCount =
dependenciesCount =
skippedDependenciesCount =
entriesCount =
0;
doneModules = doneDependencies = doneEntries = 0;
compilation.factorizeQueue.hooks.added.tap(PLUGIN_NAME, (item) =>
factorizeAdd(compilation.factorizeQueue, item)
);
compilation.factorizeQueue.hooks.result.tap(PLUGIN_NAME, factorizeDone);
compilation.addModuleQueue.hooks.added.tap(PLUGIN_NAME, (item) =>
moduleAdd(compilation.addModuleQueue, item)
);
compilation.processDependenciesQueue.hooks.result.tap(
PLUGIN_NAME,
moduleDone
);
if (showActiveModules) {
compilation.hooks.buildModule.tap(PLUGIN_NAME, moduleBuild);
}
compilation.hooks.addEntry.tap(PLUGIN_NAME, entryAdd);
compilation.hooks.failedEntry.tap(PLUGIN_NAME, entryDone);
compilation.hooks.succeedEntry.tap(PLUGIN_NAME, entryDone);
// @ts-expect-error avoid dynamic require if bundled with webpack
if (typeof __webpack_require__ !== "function") {
/** @type {Set<string>} */
const requiredLoaders = new Set();
NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(
PLUGIN_NAME,
(loaders) => {
for (const loader of loaders) {
if (
loader.type !== "module" &&
!requiredLoaders.has(loader.loader)
) {
requiredLoaders.add(loader.loader);
currentLoader = loader.loader;
update();
require(loader.loader);
}
}
if (currentLoader) {
currentLoader = "";
update();
}
}
);
}
const hooks = {
finishModules: "finish module graph",
seal: "plugins",
optimizeDependencies: "dependencies optimization",
afterOptimizeDependencies: "after dependencies optimization",
beforeChunks: "chunk graph",
afterChunks: "after chunk graph",
optimize: "optimizing",
optimizeModules: "module optimization",
afterOptimizeModules: "after module optimization",
optimizeChunks: "chunk optimization",
afterOptimizeChunks: "after chunk optimization",
optimizeTree: "module and chunk tree optimization",
afterOptimizeTree: "after module and chunk tree optimization",
optimizeChunkModules: "chunk modules optimization",
afterOptimizeChunkModules: "after chunk modules optimization",
reviveModules: "module reviving",
beforeModuleIds: "before module ids",
moduleIds: "module ids",
optimizeModuleIds: "module id optimization",
afterOptimizeModuleIds: "module id optimization",
reviveChunks: "chunk reviving",
beforeChunkIds: "before chunk ids",
chunkIds: "chunk ids",
optimizeChunkIds: "chunk id optimization",
afterOptimizeChunkIds: "after chunk id optimization",
recordModules: "record modules",
recordChunks: "record chunks",
beforeModuleHash: "module hashing",
beforeCodeGeneration: "code generation",
beforeRuntimeRequirements: "runtime requirements",
beforeHash: "hashing",
afterHash: "after hashing",
recordHash: "record hash",
beforeModuleAssets: "module assets processing",
beforeChunkAssets: "chunk assets processing",
processAssets: "asset processing",
afterProcessAssets: "after asset optimization",
record: "recording",
afterSeal: "after seal"
};
const numberOfHooks = Object.keys(hooks).length;
for (const [idx, name] of Object.keys(hooks).entries()) {
const title = hooks[/** @type {keyof typeof hooks} */ (name)];
const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({
name: PLUGIN_NAME,
call() {
handler(percentage, "sealing", title);
},
done() {
progressReporters.set(compiler, undefined);
handler(percentage, "sealing", title);
},
result() {
handler(percentage, "sealing", title);
},
error() {
handler(percentage, "sealing", title);
},
tap(tap) {
// p is percentage from 0 to 1
// args is any number of messages in a hierarchical matter
progressReporters.set(compilation.compiler, (p, ...args) => {
handler(percentage, "sealing", title, tap.name, ...args);
});
handler(percentage, "sealing", title, tap.name);
}
});
}
});
compiler.hooks.make.intercept({
name: PLUGIN_NAME,
call() {
handler(0.1, "building");
},
done() {
handler(0.65, "building");
}
});
/**
* Processes the provided hook.
* @template {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} T
* @param {T} hook hook
* @param {number} progress progress from 0 to 1
* @param {string} category category
* @param {string} name name
*/
const interceptHook = (hook, progress, category, name) => {
hook.intercept({
name: PLUGIN_NAME,
call() {
handler(progress, category, name);
},
done() {
progressReporters.set(compiler, undefined);
handler(progress, category, name);
},
result() {
handler(progress, category, name);
},
error() {
handler(progress, category, name);
},
/**
* Processes the provided tap.
* @param {Tap} tap tap
*/
tap(tap) {
progressReporters.set(compiler, (p, ...args) => {
handler(progress, category, name, tap.name, ...args);
});
handler(progress, category, name, tap.name);
}
});
};
compiler.cache.hooks.endIdle.intercept({
name: PLUGIN_NAME,
call() {
handler(0, "");
}
});
interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle");
compiler.hooks.beforeRun.intercept({
name: PLUGIN_NAME,
call() {
handler(0, "");
}
});
interceptHook(compiler.hooks.beforeRun, 0.01, "setup", "before run");
interceptHook(compiler.hooks.run, 0.02, "setup", "run");
interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run");
interceptHook(
compiler.hooks.normalModuleFactory,
0.04,
"setup",
"normal module factory"
);
interceptHook(
compiler.hooks.contextModuleFactory,
0.05,
"setup",
"context module factory"
);
interceptHook(
compiler.hooks.beforeCompile,
0.06,
"setup",
"before compile"
);
interceptHook(compiler.hooks.compile, 0.07, "setup", "compile");
interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation");
interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation");
interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish");
interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit");
interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit");
interceptHook(compiler.hooks.done, 0.99, "done", "plugins");
compiler.hooks.done.intercept({
name: PLUGIN_NAME,
done() {
handler(0.99, "");
}
});
interceptHook(
compiler.cache.hooks.storeBuildDependencies,
0.99,
"cache",
"store build dependencies"
);
interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown");
interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle");
interceptHook(
compiler.hooks.watchClose,
0.99,
"end",
"closing watch compilation"
);
compiler.cache.hooks.beginIdle.intercept({
name: PLUGIN_NAME,
done() {
handler(1, "");
}
});
compiler.cache.hooks.shutdown.intercept({
name: PLUGIN_NAME,
done() {
handler(1, "");
}
});
}
}
ProgressPlugin.defaultOptions = DEFAULT_OPTIONS;
ProgressPlugin.createDefaultHandler = createDefaultHandler;
module.exports = ProgressPlugin;

123
node_modules/webpack/lib/ProvidePlugin.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const ConstDependency = require("./dependencies/ConstDependency");
const ProvidedDependency = require("./dependencies/ProvidedDependency");
const { approve } = require("./javascript/JavascriptParserHelpers");
/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
const PLUGIN_NAME = "ProvidePlugin";
class ProvidePlugin {
/**
* Creates an instance of ProvidePlugin.
* @param {Record<string, string | string[]>} definitions the provided identifiers
*/
constructor(definitions) {
this.definitions = definitions;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const definitions = this.definitions;
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.dependencyFactories.set(
ProvidedDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ProvidedDependency,
new ProvidedDependency.Template()
);
/**
* Handles the hook callback for this code path.
* @param {JavascriptParser} parser the parser
* @param {JavascriptParserOptions} parserOptions options
* @returns {void}
*/
const handler = (parser, parserOptions) => {
for (const name of Object.keys(definitions)) {
const request = [
...(Array.isArray(definitions[name])
? definitions[name]
: [definitions[name]])
];
const splittedName = name.split(".");
if (splittedName.length > 0) {
for (const [i, _] of splittedName.slice(1).entries()) {
const name = splittedName.slice(0, i + 1).join(".");
parser.hooks.canRename.for(name).tap(PLUGIN_NAME, approve);
}
}
parser.hooks.expression.for(name).tap(PLUGIN_NAME, (expr) => {
const nameIdentifier = name.includes(".")
? `__webpack_provided_${name.replace(/\./g, "_dot_")}`
: name;
const dep = new ProvidedDependency(
request[0],
nameIdentifier,
request.slice(1),
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
return true;
});
parser.hooks.call.for(name).tap(PLUGIN_NAME, (expr) => {
const nameIdentifier = name.includes(".")
? `__webpack_provided_${name.replace(/\./g, "_dot_")}`
: name;
const dep = new ProvidedDependency(
request[0],
nameIdentifier,
request.slice(1),
/** @type {Range} */ (expr.callee.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.callee.loc);
parser.state.module.addDependency(dep);
parser.walkExpressions(expr.arguments);
return true;
});
}
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = ProvidePlugin;

192
node_modules/webpack/lib/RawModule.js generated vendored Normal file
View File

@@ -0,0 +1,192 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("./Module").Sources} Sources */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
class RawModule extends Module {
/**
* Creates an instance of RawModule.
* @param {string} source source code
* @param {string} identifier unique identifier
* @param {string=} readableIdentifier readable identifier
* @param {ReadOnlyRuntimeRequirements=} runtimeRequirements runtime requirements needed for the source code
*/
constructor(source, identifier, readableIdentifier, runtimeRequirements) {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
this.sourceStr = source;
this.identifierStr = identifier || this.sourceStr;
this.readableIdentifierStr = readableIdentifier || this.identifierStr;
this.runtimeRequirements = runtimeRequirements || null;
}
/**
* Returns the source types this module can generate.
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JAVASCRIPT_TYPES;
}
/**
* Returns the unique identifier used to reference this module.
* @returns {string} a unique identifier of the module
*/
identifier() {
return this.identifierStr;
}
/**
* Returns the estimated size for the requested source type.
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return Math.max(1, this.sourceStr.length);
}
/**
* Returns a human-readable identifier for this module.
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return /** @type {string} */ (
requestShortener.shorten(this.readableIdentifierStr)
);
}
/**
* Checks whether the module needs to be rebuilt for the current build state.
* @param {NeedBuildContext} context context info
* @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, !this.buildMeta);
}
/**
* Builds the module using the provided compilation context.
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {BuildCallback} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = {
cacheable: true
};
callback();
}
/**
* Gets side effects connection state.
* @param {ModuleGraph} moduleGraph the module graph
* @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
*/
getSideEffectsConnectionState(moduleGraph) {
if (this.factoryMeta !== undefined) {
if (this.factoryMeta.sideEffectFree) return false;
if (this.factoryMeta.sideEffectFree === false) return true;
}
return true;
}
/**
* Generates code and runtime requirements for this module.
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration(context) {
/** @type {Sources} */
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set(
JAVASCRIPT_TYPE,
new OriginalSource(this.sourceStr, this.identifier())
);
} else {
sources.set(JAVASCRIPT_TYPE, new RawSource(this.sourceStr));
}
return { sources, runtimeRequirements: this.runtimeRequirements };
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(this.sourceStr);
super.updateHash(hash, context);
}
/**
* Serializes this instance into the provided serializer context.
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.sourceStr);
write(this.identifierStr);
write(this.readableIdentifierStr);
write(this.runtimeRequirements);
super.serialize(context);
}
/**
* Restores this instance from the provided deserializer context.
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.sourceStr = read();
this.identifierStr = read();
this.readableIdentifierStr = read();
this.runtimeRequirements = read();
super.deserialize(context);
}
}
makeSerializable(RawModule, "webpack/lib/RawModule");
module.exports = RawModule;

224
node_modules/webpack/lib/RecordIdsPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,224 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { compareNumbers } = require("./util/comparators");
const identifierUtils = require("./util/identifier");
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module")} Module */
/**
* Defines the records chunks type used by this module.
* @typedef {object} RecordsChunks
* @property {Record<string, number>=} byName
* @property {Record<string, number>=} bySource
* @property {number[]=} usedIds
*/
/**
* Defines the records modules type used by this module.
* @typedef {object} RecordsModules
* @property {Record<string, number>=} byIdentifier
* @property {number[]=} usedIds
*/
/**
* Defines the records type used by this module.
* @typedef {object} Records
* @property {RecordsChunks=} chunks
* @property {RecordsModules=} modules
*/
/**
* Defines the record ids plugin options type used by this module.
* @typedef {object} RecordIdsPluginOptions
* @property {boolean=} portableIds true, when ids need to be portable
*/
/** @typedef {Set<number>} UsedIds */
const PLUGIN_NAME = "RecordIdsPlugin";
class RecordIdsPlugin {
/**
* Creates an instance of RecordIdsPlugin.
* @param {RecordIdsPluginOptions=} options object
*/
constructor(options) {
this.options = options || {};
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the Compiler
* @returns {void}
*/
apply(compiler) {
const portableIds = this.options.portableIds;
const makePathsRelative =
identifierUtils.makePathsRelative.bindContextCache(
compiler.context,
compiler.root
);
/**
* Gets module identifier.
* @param {Module} module the module
* @returns {string} the (portable) identifier
*/
const getModuleIdentifier = (module) => {
if (portableIds) {
return makePathsRelative(module.identifier());
}
return module.identifier();
};
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.recordModules.tap(PLUGIN_NAME, (modules, records) => {
const chunkGraph = compilation.chunkGraph;
if (!records.modules) records.modules = {};
if (!records.modules.byIdentifier) records.modules.byIdentifier = {};
/** @type {UsedIds} */
const usedIds = new Set();
for (const module of modules) {
const moduleId = chunkGraph.getModuleId(module);
if (typeof moduleId !== "number") continue;
const identifier = getModuleIdentifier(module);
records.modules.byIdentifier[identifier] = moduleId;
usedIds.add(moduleId);
}
records.modules.usedIds = [...usedIds].sort(compareNumbers);
});
compilation.hooks.reviveModules.tap(PLUGIN_NAME, (modules, records) => {
if (!records.modules) return;
if (records.modules.byIdentifier) {
const chunkGraph = compilation.chunkGraph;
/** @type {UsedIds} */
const usedIds = new Set();
for (const module of modules) {
const moduleId = chunkGraph.getModuleId(module);
if (moduleId !== null) continue;
const identifier = getModuleIdentifier(module);
const id = records.modules.byIdentifier[identifier];
if (id === undefined) continue;
if (usedIds.has(id)) continue;
usedIds.add(id);
chunkGraph.setModuleId(module, id);
}
}
if (Array.isArray(records.modules.usedIds)) {
compilation.usedModuleIds = new Set(records.modules.usedIds);
}
});
/** @typedef {string[]} ChunkSources */
/**
* Gets chunk sources.
* @param {Chunk} chunk the chunk
* @returns {ChunkSources} sources of the chunk
*/
const getChunkSources = (chunk) => {
/** @type {ChunkSources} */
const sources = [];
for (const chunkGroup of chunk.groupsIterable) {
const index = chunkGroup.chunks.indexOf(chunk);
if (chunkGroup.name) {
sources.push(`${index} ${chunkGroup.name}`);
} else {
for (const origin of chunkGroup.origins) {
if (origin.module) {
if (origin.request) {
sources.push(
`${index} ${getModuleIdentifier(origin.module)} ${
origin.request
}`
);
} else if (typeof origin.loc === "string") {
sources.push(
`${index} ${getModuleIdentifier(origin.module)} ${
origin.loc
}`
);
} else if (
origin.loc &&
typeof origin.loc === "object" &&
"start" in origin.loc
) {
sources.push(
`${index} ${getModuleIdentifier(
origin.module
)} ${JSON.stringify(origin.loc.start)}`
);
}
}
}
}
}
return sources;
};
compilation.hooks.recordChunks.tap(PLUGIN_NAME, (chunks, records) => {
if (!records.chunks) records.chunks = {};
if (!records.chunks.byName) records.chunks.byName = {};
if (!records.chunks.bySource) records.chunks.bySource = {};
/** @type {UsedIds} */
const usedIds = new Set();
for (const chunk of chunks) {
if (typeof chunk.id !== "number") continue;
const name = chunk.name;
if (name) records.chunks.byName[name] = chunk.id;
const sources = getChunkSources(chunk);
for (const source of sources) {
records.chunks.bySource[source] = chunk.id;
}
usedIds.add(chunk.id);
}
records.chunks.usedIds = [...usedIds].sort(compareNumbers);
});
compilation.hooks.reviveChunks.tap(PLUGIN_NAME, (chunks, records) => {
if (!records.chunks) return;
/** @type {UsedIds} */
const usedIds = new Set();
if (records.chunks.byName) {
for (const chunk of chunks) {
if (chunk.id !== null) continue;
if (!chunk.name) continue;
const id = records.chunks.byName[chunk.name];
if (id === undefined) continue;
if (usedIds.has(id)) continue;
usedIds.add(id);
chunk.id = id;
chunk.ids = [id];
}
}
if (records.chunks.bySource) {
for (const chunk of chunks) {
if (chunk.id !== null) continue;
const sources = getChunkSources(chunk);
for (const source of sources) {
const id = records.chunks.bySource[source];
if (id === undefined) continue;
if (usedIds.has(id)) continue;
usedIds.add(id);
chunk.id = id;
chunk.ids = [id];
break;
}
}
}
if (Array.isArray(records.chunks.usedIds)) {
compilation.usedChunkIds = new Set(records.chunks.usedIds);
}
});
});
}
}
module.exports = RecordIdsPlugin;

44
node_modules/webpack/lib/RequestShortener.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { contextify } = require("./util/identifier");
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/**
* Shortens absolute or verbose request strings so diagnostics and stats output
* can be rendered relative to a chosen base directory.
*/
class RequestShortener {
/**
* Binds a context-aware shortening function to the provided directory and
* optional cache owner.
* @param {string} dir the directory
* @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
*/
constructor(dir, associatedObjectForCache) {
this.contextify = contextify.bindContextCache(
dir,
associatedObjectForCache
);
}
/**
* Returns a request string rewritten relative to the configured directory
* when one is provided.
* @param {string | undefined | null} request the request to shorten
* @returns {string | undefined | null} the shortened request
*/
shorten(request) {
if (!request) {
return request;
}
return this.contextify(request);
}
}
module.exports = RequestShortener;

161
node_modules/webpack/lib/ResolverFactory.js generated vendored Normal file
View File

@@ -0,0 +1,161 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Factory = require("enhanced-resolve").ResolverFactory;
const { HookMap, SyncHook, SyncWaterfallHook } = require("tapable");
const {
cachedCleverMerge,
removeOperations,
resolveByProperty
} = require("./util/cleverMerge");
/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */
/** @typedef {import("enhanced-resolve").Resolver} Resolver */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */
/** @typedef {WebpackResolveOptions & { dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */
/**
* Defines the with options type used by this module.
* @typedef {object} WithOptions
* @property {(options: Partial<ResolveOptionsWithDependencyType>) => ResolverWithOptions} withOptions create a resolver with additional/different options
*/
/** @typedef {Resolver & WithOptions} ResolverWithOptions */
// need to be hoisted on module level for caching identity
/** @type {ResolveOptionsWithDependencyType} */
const EMPTY_RESOLVE_OPTIONS = {};
/**
* Convert to resolve options.
* @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options
* @returns {ResolveOptions} merged options
*/
const convertToResolveOptions = (resolveOptionsWithDepType) => {
const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType;
// check type compat
/** @type {Partial<ResolveOptionsWithDependencyType>} */
const partialOptions = {
...remaining,
plugins:
plugins &&
/** @type {ResolvePluginInstance[]} */ (
plugins.filter((item) => item !== "...")
)
};
if (!partialOptions.fileSystem) {
throw new Error(
"fileSystem is missing in resolveOptions, but it's required for enhanced-resolve"
);
}
// These weird types validate that we checked all non-optional properties
const options =
/** @type {Partial<ResolveOptionsWithDependencyType> & Pick<ResolveOptionsWithDependencyType, "fileSystem">} */ (
partialOptions
);
return /** @type {ResolveOptions} */ (
removeOperations(
resolveByProperty(options, "byDependency", dependencyType),
// Keep the `unsafeCache` because it can be a `Proxy`
["unsafeCache"]
)
);
};
/**
* Represents the resolver factory runtime component.
* @typedef {object} ResolverCache
* @property {WeakMap<ResolveOptionsWithDependencyType, ResolverWithOptions>} direct
* @property {Map<string, ResolverWithOptions>} stringified
*/
module.exports = class ResolverFactory {
constructor() {
this.hooks = Object.freeze({
/** @type {HookMap<SyncWaterfallHook<[ResolveOptionsWithDependencyType]>>} */
resolveOptions: new HookMap(
() => new SyncWaterfallHook(["resolveOptions"])
),
/** @type {HookMap<SyncHook<[Resolver, ResolveOptions, ResolveOptionsWithDependencyType]>>} */
resolver: new HookMap(
() => new SyncHook(["resolver", "resolveOptions", "userResolveOptions"])
)
});
/** @type {Map<string, ResolverCache>} */
this.cache = new Map();
}
/**
* Returns the resolver.
* @param {string} type type of resolver
* @param {ResolveOptionsWithDependencyType=} resolveOptions options
* @returns {ResolverWithOptions} the resolver
*/
get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) {
let typedCaches = this.cache.get(type);
if (!typedCaches) {
typedCaches = {
direct: new WeakMap(),
stringified: new Map()
};
this.cache.set(type, typedCaches);
}
const cachedResolver = typedCaches.direct.get(resolveOptions);
if (cachedResolver) {
return cachedResolver;
}
const ident = JSON.stringify(resolveOptions);
const resolver = typedCaches.stringified.get(ident);
if (resolver) {
typedCaches.direct.set(resolveOptions, resolver);
return resolver;
}
const newResolver = this._create(type, resolveOptions);
typedCaches.direct.set(resolveOptions, newResolver);
typedCaches.stringified.set(ident, newResolver);
return newResolver;
}
/**
* Returns the resolver.
* @param {string} type type of resolver
* @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType options
* @returns {ResolverWithOptions} the resolver
*/
_create(type, resolveOptionsWithDepType) {
/** @type {ResolveOptionsWithDependencyType} */
const originalResolveOptions = { ...resolveOptionsWithDepType };
const resolveOptions = convertToResolveOptions(
this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType)
);
const resolver = /** @type {ResolverWithOptions} */ (
Factory.createResolver(resolveOptions)
);
if (!resolver) {
throw new Error("No resolver created");
}
/** @type {WeakMap<Partial<ResolveOptionsWithDependencyType>, ResolverWithOptions>} */
const childCache = new WeakMap();
resolver.withOptions = (options) => {
const cacheEntry = childCache.get(options);
if (cacheEntry !== undefined) return cacheEntry;
const mergedOptions = cachedCleverMerge(originalResolveOptions, options);
const resolver = this.get(type, mergedOptions);
childCache.set(options, resolver);
return resolver;
};
this.hooks.resolver
.for(type)
.call(resolver, resolveOptions, originalResolveOptions);
return resolver;
}
};

457
node_modules/webpack/lib/RuntimeGlobals.js generated vendored Normal file
View File

@@ -0,0 +1,457 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/**
* the AMD define function
*/
module.exports.amdDefine = "__webpack_require__.amdD";
/**
* the AMD options
*/
module.exports.amdOptions = "__webpack_require__.amdO";
/**
* Creates an async module. The body function must be a async function.
* "module.exports" will be decorated with an AsyncModulePromise.
* The body function will be called.
* To handle async dependencies correctly do this: "([a, b, c] = await handleDependencies([a, b, c]));".
* If "hasAwaitAfterDependencies" is truthy, "handleDependencies()" must be called at the end of the body function.
* Signature: function(
* module: Module,
* body: (handleDependencies: (deps: AsyncModulePromise[]) => Promise<any[]> & () => void,
* hasAwaitAfterDependencies?: boolean
* ) => void
*/
module.exports.asyncModule = "__webpack_require__.a";
/**
* The internal symbol that asyncModule is using.
*/
module.exports.asyncModuleDoneSymbol = "__webpack_require__.aD";
/**
* The internal symbol that asyncModule is using.
*/
module.exports.asyncModuleExportSymbol = "__webpack_require__.aE";
/**
* the baseURI of current document
*/
module.exports.baseURI = "__webpack_require__.b";
/**
* global callback functions for installing chunks
*/
module.exports.chunkCallback = "webpackChunk";
/**
* the chunk name of the chunk with the runtime
*/
module.exports.chunkName = "__webpack_require__.cn";
/**
* compatibility get default export
*/
module.exports.compatGetDefaultExport = "__webpack_require__.n";
/**
* compile a wasm module from id and hash, returning WebAssembly.Module
*/
module.exports.compileWasm = "__webpack_require__.vs";
/**
* create a fake namespace object
*/
module.exports.createFakeNamespaceObject = "__webpack_require__.t";
/**
* function to promote a string to a TrustedScript using webpack's Trusted
* Types policy
* Arguments: (script: string) => TrustedScript
*/
module.exports.createScript = "__webpack_require__.ts";
/**
* function to promote a string to a TrustedScriptURL using webpack's Trusted
* Types policy
* Arguments: (url: string) => TrustedScriptURL
*/
module.exports.createScriptUrl = "__webpack_require__.tu";
module.exports.cssInjectStyle = "__webpack_require__.is";
/**
* The current scope when getting a module from a remote
*/
module.exports.currentRemoteGetScope = "__webpack_require__.R";
/**
* resolve async transitive dependencies for deferred module
*/
module.exports.deferredModuleAsyncTransitiveDependencies =
"__webpack_require__.zT";
/**
* the internal symbol for getting the async transitive dependencies for deferred module
*/
module.exports.deferredModuleAsyncTransitiveDependenciesSymbol =
"__webpack_require__.zS";
/**
* the exported property define getters function
*/
module.exports.definePropertyGetters = "__webpack_require__.d";
/**
* the chunk ensure function
*/
module.exports.ensureChunk = "__webpack_require__.e";
/**
* an object with handlers to ensure a chunk
*/
module.exports.ensureChunkHandlers = "__webpack_require__.f";
/**
* a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries
*/
module.exports.ensureChunkIncludeEntries =
"__webpack_require__.f (include entries)";
/**
* the module id of the entry point
*/
module.exports.entryModuleId = "__webpack_require__.s";
/**
* esm module id
*/
module.exports.esmId = "__webpack_esm_id__";
/**
* esm module ids
*/
module.exports.esmIds = "__webpack_esm_ids__";
/**
* esm modules
*/
module.exports.esmModules = "__webpack_esm_modules__";
/**
* esm runtime
*/
module.exports.esmRuntime = "__webpack_esm_runtime__";
/**
* the internal exports object
*/
module.exports.exports = "__webpack_exports__";
/**
* method to install a chunk that was loaded somehow
* Signature: ({ id, ids, modules, runtime }) => void
*/
module.exports.externalInstallChunk = "__webpack_require__.C";
/**
* the filename of the css part of the chunk
*/
module.exports.getChunkCssFilename = "__webpack_require__.k";
/**
* the filename of the script part of the chunk
*/
module.exports.getChunkScriptFilename = "__webpack_require__.u";
/**
* the filename of the css part of the hot update chunk
*/
module.exports.getChunkUpdateCssFilename = "__webpack_require__.hk";
/**
* the filename of the script part of the hot update chunk
*/
module.exports.getChunkUpdateScriptFilename = "__webpack_require__.hu";
/**
* the webpack hash
*/
module.exports.getFullHash = "__webpack_require__.h";
/**
* function to return webpack's Trusted Types policy
* Arguments: () => TrustedTypePolicy
*/
module.exports.getTrustedTypesPolicy = "__webpack_require__.tt";
/**
* the filename of the HMR manifest
*/
module.exports.getUpdateManifestFilename = "__webpack_require__.hmrF";
/**
* the global object
*/
module.exports.global = "__webpack_require__.g";
/**
* harmony module decorator
*/
module.exports.harmonyModuleDecorator = "__webpack_require__.hmd";
/**
* a flag when a module/chunk/tree has css modules
*/
module.exports.hasCssModules = "has css modules";
/**
* a flag when a chunk has a fetch priority
*/
module.exports.hasFetchPriority = "has fetch priority";
/**
* the shorthand for Object.prototype.hasOwnProperty
* using of it decreases the compiled bundle size
*/
module.exports.hasOwnProperty = "__webpack_require__.o";
/**
* function downloading the update manifest
*/
module.exports.hmrDownloadManifest = "__webpack_require__.hmrM";
/**
* array with handler functions to download chunk updates
*/
module.exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC";
/**
* array with handler functions when a module should be invalidated
*/
module.exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI";
/**
* object with all hmr module data for all modules
*/
module.exports.hmrModuleData = "__webpack_require__.hmrD";
/**
* the prefix for storing state of runtime modules when hmr is enabled
*/
module.exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS";
/**
* The sharing init sequence function (only runs once per share scope).
* Has one argument, the name of the share scope.
* Creates a share scope if not existing
*/
module.exports.initializeSharing = "__webpack_require__.I";
/**
* instantiate a wasm instance from module exports object, id, hash and importsObject
*/
module.exports.instantiateWasm = "__webpack_require__.v";
/**
* interceptor for module executions
*/
module.exports.interceptModuleExecution = "__webpack_require__.i";
/**
* function to load a script tag.
* Arguments: (url: string, done: (event) => void), key?: string | number, chunkId?: string | number) => void
* done function is called when loading has finished or timeout occurred.
* It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url.
*/
module.exports.loadScript = "__webpack_require__.l";
/**
* make a deferred namespace object
*/
module.exports.makeDeferredNamespaceObject = "__webpack_require__.z";
/**
* define compatibility on export
*/
module.exports.makeNamespaceObject = "__webpack_require__.r";
/**
* make a optimized deferred namespace object
*/
module.exports.makeOptimizedDeferredNamespaceObject = "__webpack_require__.zO";
/**
* the internal module object
*/
module.exports.module = "module";
/**
* the module cache
*/
module.exports.moduleCache = "__webpack_require__.c";
/**
* the module functions
*/
module.exports.moduleFactories = "__webpack_require__.m";
/**
* the module functions, with only write access
*/
module.exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)";
/**
* the internal module object
*/
module.exports.moduleId = "module.id";
/**
* the internal module object
*/
module.exports.moduleLoaded = "module.loaded";
/**
* node.js module decorator
*/
module.exports.nodeModuleDecorator = "__webpack_require__.nmd";
/**
* register deferred code, which will run when certain
* chunks are loaded.
* Signature: (chunkIds: Id[], fn: () => any, priority: int >= 0 = 0) => any
* Returned value will be returned directly when all chunks are already loaded
* When (priority & 1) it will wait for all other handlers with lower priority to
* be executed before itself is executed
*/
module.exports.onChunksLoaded = "__webpack_require__.O";
/**
* the chunk prefetch function
*/
module.exports.prefetchChunk = "__webpack_require__.E";
/**
* an object with handlers to prefetch a chunk
*/
module.exports.prefetchChunkHandlers = "__webpack_require__.F";
/**
* the chunk preload function
*/
module.exports.preloadChunk = "__webpack_require__.G";
/**
* an object with handlers to preload a chunk
*/
module.exports.preloadChunkHandlers = "__webpack_require__.H";
/**
* the bundle public path
*/
module.exports.publicPath = "__webpack_require__.p";
/**
* a RelativeURL class when relative URLs are used
*/
module.exports.relativeUrl = "__webpack_require__.U";
/**
* the internal require function
*/
module.exports.require = "__webpack_require__";
/**
* access to properties of the internal require function/object
*/
module.exports.requireScope = "__webpack_require__.*";
/**
* runtime need to return the exports of the last entry module
*/
module.exports.returnExportsFromRuntime = "return-exports-from-runtime";
/**
* the runtime id of the current runtime
*/
module.exports.runtimeId = "__webpack_require__.j";
/**
* the script nonce
*/
module.exports.scriptNonce = "__webpack_require__.nc";
/**
* set .name to "default" for anonymous default exports per ES spec
*/
module.exports.setAnonymousDefaultName = "__webpack_require__.dn";
/**
* an object with all share scopes
*/
module.exports.shareScopeMap = "__webpack_require__.S";
/**
* startup signal from runtime
* This will be called when the runtime chunk has been loaded.
*/
module.exports.startup = "__webpack_require__.x";
/**
* method to startup an entrypoint with needed chunks.
* Signature: (moduleId: Id, chunkIds: Id[]) => any.
* Returns the exports of the module or a Promise
*/
module.exports.startupEntrypoint = "__webpack_require__.X";
/**
* Describes how this item operation behaves.
* @deprecated
* creating a default startup function with the entry modules
*/
module.exports.startupNoDefault = "__webpack_require__.x (no default handler)";
/**
* startup signal from runtime but only used to add logic after the startup
*/
module.exports.startupOnlyAfter = "__webpack_require__.x (only after)";
/**
* startup signal from runtime but only used to add sync logic before the startup
*/
module.exports.startupOnlyBefore = "__webpack_require__.x (only before)";
/**
* the System polyfill object
*/
module.exports.system = "__webpack_require__.System";
/**
* the System.register context object
*/
module.exports.systemContext = "__webpack_require__.y";
/**
* top-level this need to be the exports object
*/
module.exports.thisAsExports = "top-level-this-exports";
/**
* to binary helper, convert base64 to Uint8Array
*/
module.exports.toBinary = "__webpack_require__.tb";
/**
* the uncaught error handler for the webpack runtime
*/
module.exports.uncaughtErrorHandler = "__webpack_require__.oe";
/**
* an object containing all installed WebAssembly.Instance export objects keyed by module id
*/
module.exports.wasmInstances = "__webpack_require__.w";

257
node_modules/webpack/lib/RuntimeModule.js generated vendored Normal file
View File

@@ -0,0 +1,257 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { RawSource } = require("webpack-sources");
const OriginalSource = require("webpack-sources").OriginalSource;
const Module = require("./Module");
const {
JAVASCRIPT_TYPES,
RUNTIME_TYPES
} = require("./ModuleSourceTypeConstants");
const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").Sources} Sources */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./Module").BasicSourceTypes} BasicSourceTypes */
class RuntimeModule extends Module {
/**
* Creates an instance of RuntimeModule.
* @param {string} name a readable name
* @param {number=} stage an optional stage
*/
constructor(name, stage = 0) {
super(WEBPACK_MODULE_TYPE_RUNTIME);
/** @type {string} */
this.name = name;
/** @type {number} */
this.stage = stage;
/** @type {BuildMeta} */
this.buildMeta = {};
/** @type {BuildInfo} */
this.buildInfo = {};
/** @type {Compilation | undefined} */
this.compilation = undefined;
/** @type {Chunk | undefined} */
this.chunk = undefined;
/** @type {ChunkGraph | undefined} */
this.chunkGraph = undefined;
/** @type {boolean} */
this.fullHash = false;
/** @type {boolean} */
this.dependentHash = false;
/** @type {string | undefined | null} */
this._cachedGeneratedCode = undefined;
}
/**
* Processes the provided compilation.
* @param {Compilation} compilation the compilation
* @param {Chunk} chunk the chunk
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {void}
*/
attach(compilation, chunk, chunkGraph = compilation.chunkGraph) {
this.compilation = compilation;
this.chunk = chunk;
this.chunkGraph = chunkGraph;
}
/**
* Returns the unique identifier used to reference this module.
* @returns {string} a unique identifier of the module
*/
identifier() {
return `webpack/runtime/${this.name}`;
}
/**
* Returns a human-readable identifier for this module.
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return `webpack/runtime/${this.name}`;
}
/**
* Checks whether the module needs to be rebuilt for the current build state.
* @param {NeedBuildContext} context context info
* @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, false);
}
/**
* Builds the module using the provided compilation context.
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {BuildCallback} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
// do nothing
// should not be called as runtime modules are added later to the compilation
callback();
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(this.name);
hash.update(`${this.stage}`);
try {
const code =
this.fullHash || this.dependentHash
? // Do not use getGeneratedCode here, because i. e. compilation hash might be not
// ready at this point. We will cache it later instead.
this.generate()
: this.getGeneratedCode();
if (code !== null && code !== undefined) {
hash.update(code);
}
} catch (err) {
hash.update(/** @type {Error} */ (err).message);
}
super.updateHash(hash, context);
}
/**
* Returns the source types this module can generate.
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return RUNTIME_TYPES;
}
/**
* Basic source types are high-level categories like javascript, css, webassembly, etc.
* We only have built-in knowledge about the javascript basic type here; other basic types may be
* added or changed over time by generators and do not need to be handled or detected here.
*
* Some modules, e.g. RemoteModule, may return non-basic source types like "remote" and "share-init"
* from getSourceTypes(), but their generated output is still JavaScript, i.e. their basic type is JS.
* @returns {BasicSourceTypes} types available (do not mutate)
*/
getSourceBasicTypes() {
return JAVASCRIPT_TYPES;
}
/**
* Generates code and runtime requirements for this module.
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration(context) {
/** @type {Sources} */
const sources = new Map();
const generatedCode = this.getGeneratedCode();
if (generatedCode) {
sources.set(
WEBPACK_MODULE_TYPE_RUNTIME,
this.useSourceMap || this.useSimpleSourceMap
? new OriginalSource(generatedCode, this.identifier())
: new RawSource(generatedCode)
);
}
return {
sources,
runtimeRequirements: null
};
}
/**
* Returns the estimated size for the requested source type.
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
try {
const source = this.getGeneratedCode();
return source ? source.length : 0;
} catch (_err) {
return 0;
}
}
/* istanbul ignore next */
/**
* Generates runtime code for this runtime module.
* @abstract
* @returns {string | null} runtime code
*/
generate() {
const AbstractMethodError = require("./errors/AbstractMethodError");
throw new AbstractMethodError();
}
/**
* Gets generated code.
* @returns {string | null} runtime code
*/
getGeneratedCode() {
if (this._cachedGeneratedCode) {
return this._cachedGeneratedCode;
}
return (this._cachedGeneratedCode = this.generate());
}
/**
* Returns true, if the runtime module should get it's own scope.
* @returns {boolean} true, if the runtime module should get it's own scope
*/
shouldIsolate() {
return true;
}
}
/**
* Runtime modules without any dependencies to other runtime modules
*/
RuntimeModule.STAGE_NORMAL = 0;
/**
* Runtime modules with simple dependencies on other runtime modules
*/
RuntimeModule.STAGE_BASIC = 5;
/**
* Runtime modules which attach to handlers of other runtime modules
*/
RuntimeModule.STAGE_ATTACH = 10;
/**
* Runtime modules which trigger actions on bootstrap
*/
RuntimeModule.STAGE_TRIGGER = 20;
module.exports = RuntimeModule;

560
node_modules/webpack/lib/RuntimePlugin.js generated vendored Normal file
View File

@@ -0,0 +1,560 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RuntimeGlobals = require("./RuntimeGlobals");
const RuntimeRequirementsDependency = require("./dependencies/RuntimeRequirementsDependency");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const AsyncModuleRuntimeModule = require("./runtime/AsyncModuleRuntimeModule");
const AutoPublicPathRuntimeModule = require("./runtime/AutoPublicPathRuntimeModule");
const BaseUriRuntimeModule = require("./runtime/BaseUriRuntimeModule");
const CompatGetDefaultExportRuntimeModule = require("./runtime/CompatGetDefaultExportRuntimeModule");
const CompatRuntimeModule = require("./runtime/CompatRuntimeModule");
const CreateFakeNamespaceObjectRuntimeModule = require("./runtime/CreateFakeNamespaceObjectRuntimeModule");
const CreateScriptRuntimeModule = require("./runtime/CreateScriptRuntimeModule");
const CreateScriptUrlRuntimeModule = require("./runtime/CreateScriptUrlRuntimeModule");
const DefinePropertyGettersRuntimeModule = require("./runtime/DefinePropertyGettersRuntimeModule");
const EnsureChunkRuntimeModule = require("./runtime/EnsureChunkRuntimeModule");
const GetChunkFilenameRuntimeModule = require("./runtime/GetChunkFilenameRuntimeModule");
const GetMainFilenameRuntimeModule = require("./runtime/GetMainFilenameRuntimeModule");
const GetTrustedTypesPolicyRuntimeModule = require("./runtime/GetTrustedTypesPolicyRuntimeModule");
const GlobalRuntimeModule = require("./runtime/GlobalRuntimeModule");
const HasOwnPropertyRuntimeModule = require("./runtime/HasOwnPropertyRuntimeModule");
const LoadScriptRuntimeModule = require("./runtime/LoadScriptRuntimeModule");
const {
MakeDeferredNamespaceObjectRuntimeModule,
MakeOptimizedDeferredNamespaceObjectRuntimeModule
} = require("./runtime/MakeDeferredNamespaceObjectRuntime");
const MakeNamespaceObjectRuntimeModule = require("./runtime/MakeNamespaceObjectRuntimeModule");
const NonceRuntimeModule = require("./runtime/NonceRuntimeModule");
const OnChunksLoadedRuntimeModule = require("./runtime/OnChunksLoadedRuntimeModule");
const PublicPathRuntimeModule = require("./runtime/PublicPathRuntimeModule");
const RelativeUrlRuntimeModule = require("./runtime/RelativeUrlRuntimeModule");
const RuntimeIdRuntimeModule = require("./runtime/RuntimeIdRuntimeModule");
const SetAnonymousDefaultNameRuntimeModule = require("./runtime/SetAnonymousDefaultNameRuntimeModule");
const SystemContextRuntimeModule = require("./runtime/SystemContextRuntimeModule");
const ToBinaryRuntimeModule = require("./runtime/ToBinaryRuntimeModule");
const ShareRuntimeModule = require("./sharing/ShareRuntimeModule");
const StringXor = require("./util/StringXor");
const memoize = require("./util/memoize");
/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compiler")} Compiler */
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
const getCssModulesPlugin = memoize(() => require("./css/CssModulesPlugin"));
const GLOBALS_ON_REQUIRE = [
RuntimeGlobals.chunkName,
RuntimeGlobals.runtimeId,
RuntimeGlobals.compatGetDefaultExport,
RuntimeGlobals.createFakeNamespaceObject,
RuntimeGlobals.createScript,
RuntimeGlobals.createScriptUrl,
RuntimeGlobals.getTrustedTypesPolicy,
RuntimeGlobals.definePropertyGetters,
RuntimeGlobals.ensureChunk,
RuntimeGlobals.entryModuleId,
RuntimeGlobals.getFullHash,
RuntimeGlobals.global,
RuntimeGlobals.makeNamespaceObject,
RuntimeGlobals.moduleCache,
RuntimeGlobals.moduleFactories,
RuntimeGlobals.moduleFactoriesAddOnly,
RuntimeGlobals.interceptModuleExecution,
RuntimeGlobals.publicPath,
RuntimeGlobals.baseURI,
RuntimeGlobals.relativeUrl,
// TODO webpack 6 - rename to nonce, because we use it for CSS too
RuntimeGlobals.scriptNonce,
RuntimeGlobals.uncaughtErrorHandler,
RuntimeGlobals.asyncModule,
RuntimeGlobals.wasmInstances,
RuntimeGlobals.instantiateWasm,
RuntimeGlobals.shareScopeMap,
RuntimeGlobals.initializeSharing,
RuntimeGlobals.loadScript,
RuntimeGlobals.setAnonymousDefaultName,
RuntimeGlobals.systemContext,
RuntimeGlobals.onChunksLoaded,
RuntimeGlobals.makeOptimizedDeferredNamespaceObject,
RuntimeGlobals.makeDeferredNamespaceObject
];
const MODULE_DEPENDENCIES = {
[RuntimeGlobals.moduleLoaded]: [RuntimeGlobals.module],
[RuntimeGlobals.moduleId]: [RuntimeGlobals.module]
};
const TREE_DEPENDENCIES = {
[RuntimeGlobals.definePropertyGetters]: [RuntimeGlobals.hasOwnProperty],
[RuntimeGlobals.compatGetDefaultExport]: [
RuntimeGlobals.definePropertyGetters
],
[RuntimeGlobals.createFakeNamespaceObject]: [
RuntimeGlobals.definePropertyGetters,
RuntimeGlobals.makeNamespaceObject,
RuntimeGlobals.require
],
[RuntimeGlobals.makeOptimizedDeferredNamespaceObject]: [
RuntimeGlobals.require
],
[RuntimeGlobals.makeDeferredNamespaceObject]: [
RuntimeGlobals.createFakeNamespaceObject,
RuntimeGlobals.require
],
[RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap],
[RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty]
};
const FULLHASH_REGEXP = /\[(?:full)?hash(?::\d+)?\]/;
const PLUGIN_NAME = "RuntimePlugin";
class RuntimePlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the Compiler
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const globalChunkLoading = compilation.outputOptions.chunkLoading;
/**
* Checks whether this runtime plugin is chunk loading disabled for chunk.
* @param {Chunk} chunk chunk
* @returns {boolean} true, when chunk loading is disabled for the chunk
*/
const isChunkLoadingDisabledForChunk = (chunk) => {
const options = chunk.getEntryOptions();
const chunkLoading =
options && options.chunkLoading !== undefined
? options.chunkLoading
: globalChunkLoading;
return chunkLoading === false;
};
compilation.dependencyTemplates.set(
RuntimeRequirementsDependency,
new RuntimeRequirementsDependency.Template()
);
for (const req of GLOBALS_ON_REQUIRE) {
compilation.hooks.runtimeRequirementInModule
.for(req)
.tap(PLUGIN_NAME, (module, set) => {
set.add(RuntimeGlobals.requireScope);
});
compilation.hooks.runtimeRequirementInTree
.for(req)
.tap(PLUGIN_NAME, (module, set) => {
set.add(RuntimeGlobals.requireScope);
});
}
for (const req of Object.keys(TREE_DEPENDENCIES)) {
const deps =
TREE_DEPENDENCIES[/** @type {keyof TREE_DEPENDENCIES} */ (req)];
compilation.hooks.runtimeRequirementInTree
.for(req)
.tap(PLUGIN_NAME, (chunk, set) => {
for (const dep of deps) set.add(dep);
});
}
for (const req of Object.keys(MODULE_DEPENDENCIES)) {
const deps =
MODULE_DEPENDENCIES[/** @type {keyof MODULE_DEPENDENCIES} */ (req)];
compilation.hooks.runtimeRequirementInModule
.for(req)
.tap(PLUGIN_NAME, (chunk, set) => {
for (const dep of deps) set.add(dep);
});
}
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.definePropertyGetters)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new DefinePropertyGettersRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.makeNamespaceObject)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new MakeNamespaceObjectRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.createFakeNamespaceObject)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new CreateFakeNamespaceObjectRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.makeOptimizedDeferredNamespaceObject)
.tap("RuntimePlugin", (chunk, runtimeRequirement) => {
compilation.addRuntimeModule(
chunk,
new MakeOptimizedDeferredNamespaceObjectRuntimeModule(
runtimeRequirement.has(RuntimeGlobals.asyncModule)
)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.makeDeferredNamespaceObject)
.tap("RuntimePlugin", (chunk, runtimeRequirement) => {
compilation.addRuntimeModule(
chunk,
new MakeDeferredNamespaceObjectRuntimeModule(
runtimeRequirement.has(RuntimeGlobals.asyncModule)
)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.hasOwnProperty)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new HasOwnPropertyRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.compatGetDefaultExport)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new CompatGetDefaultExportRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.setAnonymousDefaultName)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(
chunk,
new SetAnonymousDefaultNameRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.runtimeId)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new RuntimeIdRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.publicPath)
.tap(PLUGIN_NAME, (chunk, set) => {
const { outputOptions } = compilation;
const { publicPath: globalPublicPath, scriptType } = outputOptions;
const entryOptions = chunk.getEntryOptions();
const publicPath =
entryOptions && entryOptions.publicPath !== undefined
? entryOptions.publicPath
: globalPublicPath;
if (publicPath === "auto") {
const module = new AutoPublicPathRuntimeModule();
if (
scriptType !== "module" &&
!outputOptions.environment.globalThis
) {
set.add(RuntimeGlobals.global);
}
compilation.addRuntimeModule(chunk, module);
} else {
const module = new PublicPathRuntimeModule(publicPath);
if (
typeof publicPath !== "string" ||
FULLHASH_REGEXP.test(publicPath)
) {
module.fullHash = true;
}
compilation.addRuntimeModule(chunk, module);
}
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.global)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new GlobalRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.asyncModule)
.tap(PLUGIN_NAME, (chunk) => {
const experiments = compilation.options.experiments;
compilation.addRuntimeModule(
chunk,
new AsyncModuleRuntimeModule(experiments.deferImport)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.systemContext)
.tap(PLUGIN_NAME, (chunk) => {
const entryOptions = chunk.getEntryOptions();
const libraryType =
entryOptions && entryOptions.library !== undefined
? entryOptions.library.type
: /** @type {LibraryOptions} */
(compilation.outputOptions.library).type;
if (libraryType === "system") {
compilation.addRuntimeModule(
chunk,
new SystemContextRuntimeModule()
);
}
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getChunkScriptFilename)
.tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
if (
typeof compilation.outputOptions.chunkFilename === "string" &&
FULLHASH_REGEXP.test(compilation.outputOptions.chunkFilename)
) {
set.add(RuntimeGlobals.getFullHash);
}
compilation.addRuntimeModule(
chunk,
new GetChunkFilenameRuntimeModule(
"javascript",
"javascript",
RuntimeGlobals.getChunkScriptFilename,
(chunk) =>
getJavascriptModulesPlugin().chunkHasJs(chunk, chunkGraph) &&
(chunk.filenameTemplate ||
(chunk.canBeInitial()
? compilation.outputOptions.filename
: compilation.outputOptions.chunkFilename)),
set.has(RuntimeGlobals.hmrDownloadUpdateHandlers)
)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getChunkCssFilename)
.tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
if (
typeof compilation.outputOptions.cssChunkFilename === "string" &&
FULLHASH_REGEXP.test(compilation.outputOptions.cssChunkFilename)
) {
set.add(RuntimeGlobals.getFullHash);
}
compilation.addRuntimeModule(
chunk,
new GetChunkFilenameRuntimeModule(
"css",
"css",
RuntimeGlobals.getChunkCssFilename,
(chunk) => {
const cssModulePlugin = getCssModulesPlugin();
return (
cssModulePlugin.chunkHasCss(chunk, chunkGraph) &&
cssModulePlugin.getChunkFilenameTemplate(
chunk,
compilation.outputOptions
)
);
},
set.has(RuntimeGlobals.hmrDownloadUpdateHandlers)
)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getChunkUpdateScriptFilename)
.tap(PLUGIN_NAME, (chunk, set) => {
if (
FULLHASH_REGEXP.test(
compilation.outputOptions.hotUpdateChunkFilename
)
) {
set.add(RuntimeGlobals.getFullHash);
}
compilation.addRuntimeModule(
chunk,
new GetChunkFilenameRuntimeModule(
"javascript",
"javascript update",
RuntimeGlobals.getChunkUpdateScriptFilename,
(_chunk) => compilation.outputOptions.hotUpdateChunkFilename,
true
)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getUpdateManifestFilename)
.tap(PLUGIN_NAME, (chunk, set) => {
if (
FULLHASH_REGEXP.test(
compilation.outputOptions.hotUpdateMainFilename
)
) {
set.add(RuntimeGlobals.getFullHash);
}
compilation.addRuntimeModule(
chunk,
new GetMainFilenameRuntimeModule(
"update manifest",
RuntimeGlobals.getUpdateManifestFilename,
compilation.outputOptions.hotUpdateMainFilename
)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.ensureChunk)
.tap(PLUGIN_NAME, (chunk, set) => {
const hasAsyncChunks = chunk.hasAsyncChunks();
if (hasAsyncChunks) {
set.add(RuntimeGlobals.ensureChunkHandlers);
}
compilation.addRuntimeModule(
chunk,
new EnsureChunkRuntimeModule(set)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.ensureChunkIncludeEntries)
.tap(PLUGIN_NAME, (chunk, set) => {
set.add(RuntimeGlobals.ensureChunkHandlers);
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.shareScopeMap)
.tap(PLUGIN_NAME, (chunk, set) => {
compilation.addRuntimeModule(chunk, new ShareRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.loadScript)
.tap(PLUGIN_NAME, (chunk, set) => {
const withCreateScriptUrl = Boolean(
compilation.outputOptions.trustedTypes
);
if (withCreateScriptUrl) {
set.add(RuntimeGlobals.createScriptUrl);
}
const withFetchPriority = set.has(RuntimeGlobals.hasFetchPriority);
compilation.addRuntimeModule(
chunk,
new LoadScriptRuntimeModule(withCreateScriptUrl, withFetchPriority)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.createScript)
.tap(PLUGIN_NAME, (chunk, set) => {
if (compilation.outputOptions.trustedTypes) {
set.add(RuntimeGlobals.getTrustedTypesPolicy);
}
compilation.addRuntimeModule(chunk, new CreateScriptRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.createScriptUrl)
.tap(PLUGIN_NAME, (chunk, set) => {
if (compilation.outputOptions.trustedTypes) {
set.add(RuntimeGlobals.getTrustedTypesPolicy);
}
compilation.addRuntimeModule(
chunk,
new CreateScriptUrlRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getTrustedTypesPolicy)
.tap(PLUGIN_NAME, (chunk, set) => {
compilation.addRuntimeModule(
chunk,
new GetTrustedTypesPolicyRuntimeModule(set)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.relativeUrl)
.tap(PLUGIN_NAME, (chunk, _set) => {
compilation.addRuntimeModule(chunk, new RelativeUrlRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.onChunksLoaded)
.tap(PLUGIN_NAME, (chunk, _set) => {
compilation.addRuntimeModule(
chunk,
new OnChunksLoadedRuntimeModule()
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.baseURI)
.tap(PLUGIN_NAME, (chunk) => {
if (isChunkLoadingDisabledForChunk(chunk)) {
compilation.addRuntimeModule(chunk, new BaseUriRuntimeModule());
return true;
}
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.scriptNonce)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new NonceRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.toBinary)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new ToBinaryRuntimeModule());
return true;
});
// TODO webpack 6: remove CompatRuntimeModule
compilation.hooks.additionalTreeRuntimeRequirements.tap(
PLUGIN_NAME,
(chunk, _set) => {
const { mainTemplate } = compilation;
if (
mainTemplate.hooks.bootstrap.isUsed() ||
mainTemplate.hooks.localVars.isUsed() ||
mainTemplate.hooks.requireEnsure.isUsed() ||
mainTemplate.hooks.requireExtensions.isUsed()
) {
compilation.addRuntimeModule(chunk, new CompatRuntimeModule());
}
}
);
JavascriptModulesPlugin.getCompilationHooks(compilation).chunkHash.tap(
PLUGIN_NAME,
(chunk, hash, { chunkGraph }) => {
const xor = new StringXor();
for (const m of chunkGraph.getChunkRuntimeModulesIterable(chunk)) {
xor.add(chunkGraph.getModuleHash(m, chunk.runtime));
}
xor.updateHash(hash);
}
);
});
}
}
module.exports = RuntimePlugin;

1322
node_modules/webpack/lib/RuntimeTemplate.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

35
node_modules/webpack/lib/SelfModuleFactory.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
class SelfModuleFactory {
/**
* Creates an instance of SelfModuleFactory.
* @param {ModuleGraph} moduleGraph module graph
*/
constructor(moduleGraph) {
this.moduleGraph = moduleGraph;
}
/**
* Processes the provided data.
* @param {ModuleFactoryCreateData} data data object
* @param {ModuleFactoryCallback} callback callback
* @returns {void}
*/
create(data, callback) {
const module = this.moduleGraph.getParentModule(data.dependencies[0]);
callback(null, {
module
});
}
}
module.exports = SelfModuleFactory;

8
node_modules/webpack/lib/SingleEntryPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sean Larkin @thelarkinn
*/
"use strict";
module.exports = require("./EntryPlugin");

View File

@@ -0,0 +1,54 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("./Compilation")} Compilation */
const PLUGIN_NAME = "SourceMapDevToolModuleOptionsPlugin";
class SourceMapDevToolModuleOptionsPlugin {
/**
* Creates an instance of SourceMapDevToolModuleOptionsPlugin.
* @param {SourceMapDevToolPluginOptions=} options options
*/
constructor(options = {}) {
/** @type {SourceMapDevToolPluginOptions} */
this.options = options;
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compilation} compilation the compiler instance
* @returns {void}
*/
apply(compilation) {
const options = this.options;
if (options.module !== false) {
compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => {
module.useSourceMap = true;
});
compilation.hooks.runtimeModule.tap(PLUGIN_NAME, (module) => {
module.useSourceMap = true;
});
} else {
compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => {
module.useSimpleSourceMap = true;
});
compilation.hooks.runtimeModule.tap(PLUGIN_NAME, (module) => {
module.useSimpleSourceMap = true;
});
}
JavascriptModulesPlugin.getCompilationHooks(compilation).useSourceMap.tap(
PLUGIN_NAME,
() => true
);
}
}
module.exports = SourceMapDevToolModuleOptionsPlugin;

928
node_modules/webpack/lib/SourceMapDevToolPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,928 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const { ConcatSource, RawSource } = require("webpack-sources");
const Compilation = require("./Compilation");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const ProgressPlugin = require("./ProgressPlugin");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
const createHash = require("./util/createHash");
const { dirname, relative } = require("./util/fs");
const generateDebugId = require("./util/generateDebugId");
const { makePathsAbsolute } = require("./util/identifier");
/** @typedef {import("webpack-sources").MapOptions} MapOptions */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").DevtoolNamespace} DevtoolNamespace */
/** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */
/** @typedef {import("../declarations/WebpackOptions").DevtoolFallbackModuleFilenameTemplate} DevtoolFallbackModuleFilenameTemplate */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").Rules} Rules */
/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation").Asset} Asset */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./NormalModule").RawSourceMap} RawSourceMap */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} SourceMappingURLComment */
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
/**
* Defines the source map task type used by this module.
* @typedef {object} SourceMapTask
* @property {AssetInfo} assetInfo
* @property {(string | Module)[]} modules
* @property {string} source
* @property {string} file
* @property {RawSourceMap} sourceMap
* @property {Source} mapSource the Source instance whose `sourceAndMap` we called (the current asset or, when its map was already stripped, the pinned original from `originalSources`) — what `clearCache` should target
* @property {ItemCacheFacade} cacheItem cache item
*/
const METACHARACTERS_REGEXP = /[-[\]\\/{}()*+?.^$|]/g;
const CONTENT_HASH_DETECT_REGEXP = /\[contenthash(?::\w+)?\]/;
const CSS_AND_JS_MODULE_EXTENSIONS_REGEXP = /\.((c|m)?js|css)($|\?)/i;
const CSS_EXTENSION_DETECT_REGEXP = /\.css(?:$|\?)/i;
const MAP_URL_COMMENT_REGEXP = /\[map\]/g;
const URL_COMMENT_REGEXP = /\[url\]/g;
const URL_FORMATTING_REGEXP = /^\n\/\/(.*)$/;
/**
* Reset's .lastIndex of stateful Regular Expressions
* For when `test` or `exec` is called on them
* @param {RegExp} regexp Stateful Regular Expression to be reset
* @returns {void}
*/
const resetRegexpState = (regexp) => {
regexp.lastIndex = -1;
};
/**
* Escapes regular expression metacharacters
* @param {string} str String to quote
* @returns {string} Escaped string
*/
const quoteMeta = (str) => str.replace(METACHARACTERS_REGEXP, "\\$&");
/**
* Compilation-scoped registry of original asset sources for multi-plugin
* cooperation. The first SourceMapDevToolPlugin instance to see a file pins a
* reference to the asset's still-unwrapped {@link Source} object; later
* instances whose `asset.source.sourceAndMap()` would now return `null` (the
* earlier instance replaced the asset with a `RawSource`) can re-extract the
* map from this pinned reference. We keep the registry on a module-scoped
* `WeakMap` so the entries are reclaimed automatically when the compilation
* itself becomes unreachable; we never store anything on the compilation
* object directly.
*
* Stashing the `Source` object itself rather than an extracted map keeps the
* fast path free of cloning and source-map serialization work — the
* extraction only happens if a subsequent plugin actually needs the map.
* @type {WeakMap<Compilation, Map<string, Source>>}
*/
const originalSourceRegistry = new WeakMap();
/**
* Returns (creating if necessary) the per-compilation registry of original
* asset {@link Source} objects.
* @param {Compilation} compilation compilation
* @returns {Map<string, Source>} registry
*/
const getOriginalSourceRegistry = (compilation) => {
let registry = originalSourceRegistry.get(compilation);
if (registry === undefined) {
registry = new Map();
originalSourceRegistry.set(compilation, registry);
}
return registry;
};
/**
* Extracts source and source map from a Source object, falling back to a
* registered original source for assets that another SourceMapDevToolPlugin
* instance has already wrapped (whose internal map is now `null`).
*
* The returned source is read from the asset as it currently stands — that way
* any `sourceMappingURL` comments appended by earlier plugin instances survive
* — while the map is taken from the pinned original Source when the current
* one no longer carries it. `mapSource` identifies which Source instance was
* actually queried for the map (the current asset, or the pinned original);
* that's the one whose internal caches the caller should release.
* @param {string} file file name
* @param {Source} asset source object as currently held by the compilation
* @param {MapOptions} options map extraction options
* @param {Map<string, Source>} registry compilation-scoped original-source registry
* @returns {{ source: string, sourceMap: RawSourceMap, mapSource: Source } | undefined} extracted pair or `undefined` when no map is recoverable
*/
const extractSourceAndMap = (file, asset, options, registry) => {
/** @type {string | Buffer} */
let source;
/** @type {null | RawSourceMap} */
let sourceMap;
if (asset.sourceAndMap) {
const sourceAndMap = asset.sourceAndMap(options);
source = sourceAndMap.source;
sourceMap = sourceAndMap.map;
} else {
source = asset.source();
sourceMap = asset.map(options);
}
// Bail before touching the registry if we can't return a usable string
// source — pinning a non-string-producing asset would only waste the slot.
if (typeof source !== "string") return;
if (sourceMap) {
// The current asset still owns the original map — pin a reference so
// that a later plugin instance (which will see a rewrapped asset
// without a map) can recover it on demand.
if (!registry.has(file)) registry.set(file, asset);
return { source, sourceMap, mapSource: asset };
}
// The current asset (typically a `RawSource` left by an earlier
// SourceMapDevToolPlugin instance) has no internal map. Re-extract
// the map from the original Source we pinned earlier. We keep using
// `source` from the current asset so that any prior wrappers (e.g.
// appended sourceMappingURL comments) are preserved.
const original = registry.get(file);
if (!original) return;
sourceMap = original.sourceAndMap
? original.sourceAndMap(options).map
: original.map(options);
if (!sourceMap) return;
return { source, sourceMap, mapSource: original };
};
/**
* Creating {@link SourceMapTask} for given file
* @param {string} file current compiled file
* @param {Source} asset the asset
* @param {AssetInfo} assetInfo the asset info
* @param {MapOptions} options source map options
* @param {Compilation} compilation compilation instance
* @param {ItemCacheFacade} cacheItem cache item
* @param {Map<string, Source>} registry compilation-scoped original-source registry
* @returns {SourceMapTask | undefined} created task instance or `undefined`
*/
const getTaskForFile = (
file,
asset,
assetInfo,
options,
compilation,
cacheItem,
registry
) => {
const extracted = extractSourceAndMap(file, asset, options, registry);
if (!extracted) return;
const { source, sourceMap, mapSource } = extracted;
const context = compilation.options.context;
const root = compilation.compiler.root;
const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root);
const modules = sourceMap.sources.map((source) => {
if (!source.startsWith("webpack://")) return source;
source = cachedAbsolutify(source.slice(10));
const module = compilation.findModule(source);
return module || source;
});
return {
file,
source: /** @type {string} */ (source),
assetInfo,
sourceMap,
mapSource,
modules,
cacheItem
};
};
const PLUGIN_NAME = "SourceMapDevToolPlugin";
/**
* Maps a configuration value (string, RegExp, function, nullish, or array of
* such) into a JSON-serializable form. Functions and RegExps are turned into
* their `.toString()` representation so that changes to inline callbacks
* invalidate caches; everything else is returned as-is so that the surrounding
* `JSON.stringify` does the escaping.
*
* The result is used through `JSON.stringify` to build cache identifiers, so
* we deliberately avoid any homemade `|` / `,` separators that could collide
* with characters appearing inside user-provided values such as `publicPath`,
* template strings, or `sourceRoot`.
* @param {EXPECTED_ANY} value option value
* @returns {EXPECTED_ANY} JSON-serializable representation
*/
const toCacheKeyValue = (value) => {
if (value === undefined || value === null) return value;
if (Array.isArray(value)) return value.map(toCacheKeyValue);
if (value instanceof RegExp || typeof value === "function") {
return value.toString();
}
return value;
};
class SourceMapDevToolPlugin {
/**
* Creates an instance of SourceMapDevToolPlugin.
* @param {SourceMapDevToolPluginOptions=} options options object
* @throws {Error} throws error, if got more than 1 arguments
*/
constructor(options = {}) {
/** @type {undefined | null | false | string} */
this.sourceMapFilename = options.filename;
/** @type {false | SourceMappingURLComment} */
this.sourceMappingURLComment =
options.append === false
? false
: // eslint-disable-next-line no-useless-concat
options.append || "\n//# source" + "MappingURL=[url]";
/** @type {DevtoolModuleFilenameTemplate} */
this.moduleFilenameTemplate =
options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]";
/** @type {DevtoolFallbackModuleFilenameTemplate} */
this.fallbackModuleFilenameTemplate =
options.fallbackModuleFilenameTemplate ||
"webpack://[namespace]/[resourcePath]?[hash]";
/** @type {DevtoolNamespace} */
this.namespace = options.namespace || "";
/** @type {SourceMapDevToolPluginOptions} */
this.options = options;
// Cache salt derived from output-affecting options, so that two
// SourceMapDevToolPlugin instances (or `devtool` + a plugin) operating
// on the same asset don't share a cache entry. We serialize via
// `JSON.stringify` rather than a homemade separator so that any
// special characters (e.g. `|` inside a publicPath or sourceRoot)
// can't accidentally make two different option sets collide.
/** @type {string} */
this._cacheSalt = JSON.stringify([
toCacheKeyValue(options.filename),
toCacheKeyValue(options.append),
toCacheKeyValue(this.moduleFilenameTemplate),
toCacheKeyValue(this.fallbackModuleFilenameTemplate),
toCacheKeyValue(this.namespace),
options.module !== false,
options.columns !== false,
Boolean(options.noSources),
Boolean(options.debugIds),
options.sourceRoot || "",
toCacheKeyValue(options.ignoreList),
options.publicPath || "",
options.fileContext || ""
]);
}
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.validate.tap(PLUGIN_NAME, () => {
compiler.validate(
() => require("../schemas/plugins/SourceMapDevToolPlugin.json"),
this.options,
{
name: "SourceMap DevTool Plugin",
baseDataPath: "options"
},
(options) =>
require("../schemas/plugins/SourceMapDevToolPlugin.check")(options)
);
});
const outputFs =
/** @type {OutputFileSystem} */
(compiler.outputFileSystem);
const sourceMapFilename = this.sourceMapFilename;
const sourceMappingURLComment = this.sourceMappingURLComment;
const moduleFilenameTemplate = this.moduleFilenameTemplate;
const namespace = this.namespace;
const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
const requestShortener = compiler.requestShortener;
const options = this.options;
options.test = options.test || CSS_AND_JS_MODULE_EXTENSIONS_REGEXP;
/** @type {(filename: string) => boolean} */
const matchObject = ModuleFilenameHelpers.matchObject.bind(
undefined,
options
);
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
// All SourceMapDevToolPlugin instances on the same compilation share
// a registry of pristine asset sources, so the second instance to
// run can still recover the original map after the first instance
// has replaced the asset with a `RawSource`. The registry lives on a
// module-scoped `WeakMap` keyed by compilation so it is released
// automatically and never pollutes the compilation object.
const originalSources = getOriginalSourceRegistry(compilation);
compilation.hooks.processAssets.tapAsync(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
additionalAssets: true
},
(assets, callback) => {
const chunkGraph = compilation.chunkGraph;
const cache = compilation.getCache(PLUGIN_NAME);
/** @type {Map<string | Module, string>} */
const moduleToSourceNameMapping = new Map();
const reportProgress =
ProgressPlugin.getReporter(compilation.compiler) || (() => {});
/** @type {Map<string, Chunk>} */
const fileToChunk = new Map();
for (const chunk of compilation.chunks) {
for (const file of chunk.files) {
fileToChunk.set(file, chunk);
}
for (const file of chunk.auxiliaryFiles) {
fileToChunk.set(file, chunk);
}
}
/** @type {string[]} */
const files = [];
for (const file of Object.keys(assets)) {
if (matchObject(file)) {
files.push(file);
}
}
reportProgress(0);
/** @type {SourceMapTask[]} */
const tasks = [];
let fileIndex = 0;
// Shared deduplication set for `Source#clearCache` calls below.
// Webpack chunks routinely share module-level `CachedSource`
// instances. A per-call WeakSet would re-walk those shared
// subtrees once per chunk — 50 chunks × thousands of shared
// modules in dev/non-minified setups — and worse, every
// chunk's `sourceAndMap` would have to recompute the cleared
// caches, churning allocations (measured: +700 MB peak RSS,
// +6 s wall time on a 50×1000 synthetic build).
//
// Sharing one set lets each shared subtree be walked exactly
// once. The trade-off is that subsequent chunks' `sourceAndMap`
// calls can repopulate a shared module's `_cachedMaps` after
// its own clear was skipped (because the module is already in
// the visited set), leaving at most one populated cache entry
// per shared module at the end of the run — bounded to a few
// MB even at the scale of #20961. That's strictly preferable
// to the alternative's hundreds of MB of transient peak RSS.
const clearCacheVisited = new WeakSet();
asyncLib.each(
files,
(file, callback) => {
const asset =
/** @type {Readonly<Asset>} */
(compilation.getAsset(file));
const chunk = fileToChunk.get(file);
const sourceMapNamespace = compilation.getPath(this.namespace, {
chunk
});
// The cache item identifier must include the per-instance
// salt so two SourceMapDevToolPlugin instances that target
// the same `file` don't collide in the persistent cache —
// they'd otherwise write different content to the same key
// and invalidate every pack on each build. We encode via
// `JSON.stringify` so that special characters (e.g. `|`)
// in an asset filename can't be spoofed to collide with the
// salt portion of the identifier.
const cacheItem = cache.getItemCache(
JSON.stringify([file, this._cacheSalt]),
cache.mergeEtags(
cache.getLazyHashedEtag(asset.source),
sourceMapNamespace
)
);
cacheItem.get((err, cacheEntry) => {
if (err) {
return callback(err);
}
/**
* If presented in cache, reassigns assets. Cache assets already have source maps.
*/
if (cacheEntry) {
// Pin the still-unwrapped asset source in the registry
// before `compilation.updateAsset` replaces it. This is a
// pointer assignment — no source-map extraction work — and
// it lets a subsequent SourceMapDevToolPlugin instance
// extract the original map on demand even though the
// persistent cache hit lets us skip processing here.
if (!originalSources.has(file)) {
originalSources.set(file, asset.source);
}
const { assets, assetsInfo } = cacheEntry;
for (const cachedFile of Object.keys(assets)) {
if (cachedFile === file) {
compilation.updateAsset(
cachedFile,
assets[cachedFile],
assetsInfo[cachedFile]
);
} else {
compilation.emitAsset(
cachedFile,
assets[cachedFile],
assetsInfo[cachedFile]
);
}
/**
* Add file to chunk, if not presented there
*/
if (cachedFile !== file && chunk !== undefined) {
chunk.auxiliaryFiles.add(cachedFile);
}
}
reportProgress(
(0.5 * ++fileIndex) / files.length,
file,
"restored cached SourceMap"
);
return callback();
}
reportProgress(
(0.5 * fileIndex) / files.length,
file,
"generate SourceMap"
);
/** @type {SourceMapTask | undefined} */
const task = getTaskForFile(
file,
asset.source,
asset.info,
{
module: options.module,
columns: options.columns
},
compilation,
cacheItem,
originalSources
);
// Release the per-instance caches that `sourceAndMap`
// just populated. The composed map (and, for
// `SourceMapSource`, the parsed `_sourceMapAsObject` /
// `_innerSourceMapAsObject`) otherwise sit on the
// CachedSource — and every shared child — until phase
// 2 replaces the asset, which is what causes the OOM
// spike on builds with thousands of chunks
// (webpack#20961). Keep `source` since downstream
// consumers reading the original asset still need it;
// `hash`/`size` default to retained because they're
// cheap to keep but expensive to rebuild.
// `clearCacheVisited` is shared across every call (see
// its declaration above for the rationale).
//
// Target `task.mapSource` (not `asset.source`): when
// `extractSourceAndMap` falls back to the pinned
// original (the current asset is a `RawSource` left
// by an earlier plugin instance), the `sourceAndMap`
// call populated the original's caches, not the
// current asset's.
//
// Feature-detected: `clearCache` landed in
// `webpack-sources` 3.5, but `compilation.assets` may
// hold `Source`-like instances from a third-party
// plugin built against an older copy of
// `webpack-sources` (or a hand-rolled implementation).
// Calling it unconditionally would throw on those.
if (task && typeof task.mapSource.clearCache === "function") {
task.mapSource.clearCache(
{
maps: true,
source: false,
parsedMap: true
},
clearCacheVisited
);
}
if (task) {
const modules = task.modules;
for (let idx = 0; idx < modules.length; idx++) {
const module = modules[idx];
if (
typeof module === "string" &&
/^(?:data|https?):/.test(module)
) {
moduleToSourceNameMapping.set(module, module);
continue;
}
if (!moduleToSourceNameMapping.get(module)) {
moduleToSourceNameMapping.set(
module,
ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate,
namespace: sourceMapNamespace
},
{
requestShortener,
chunkGraph,
hashFunction: compilation.outputOptions.hashFunction
}
)
);
}
}
tasks.push(task);
}
reportProgress(
(0.5 * ++fileIndex) / files.length,
file,
"generated SourceMap"
);
callback();
});
},
(err) => {
if (err) {
return callback(err);
}
reportProgress(0.5, "resolve sources");
/** @type {Set<string>} */
const usedNamesSet = new Set(moduleToSourceNameMapping.values());
/** @type {Set<string>} */
const conflictDetectionSet = new Set();
/**
* all modules in defined order (longest identifier first)
* @type {(string | Module)[]}
*/
const allModules = [...moduleToSourceNameMapping.keys()].sort(
(a, b) => {
const ai = typeof a === "string" ? a : a.identifier();
const bi = typeof b === "string" ? b : b.identifier();
return ai.length - bi.length;
}
);
// find modules with conflicting source names
for (let idx = 0; idx < allModules.length; idx++) {
const module = allModules[idx];
let sourceName =
/** @type {string} */
(moduleToSourceNameMapping.get(module));
let hasName = conflictDetectionSet.has(sourceName);
if (!hasName) {
conflictDetectionSet.add(sourceName);
continue;
}
// try the fallback name first
sourceName = ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: fallbackModuleFilenameTemplate,
namespace
},
{
requestShortener,
chunkGraph,
hashFunction: compilation.outputOptions.hashFunction
}
);
hasName = usedNamesSet.has(sourceName);
if (!hasName) {
moduleToSourceNameMapping.set(module, sourceName);
usedNamesSet.add(sourceName);
continue;
}
// otherwise just append stars until we have a valid name
while (hasName) {
sourceName += "*";
hasName = usedNamesSet.has(sourceName);
}
moduleToSourceNameMapping.set(module, sourceName);
usedNamesSet.add(sourceName);
}
let taskIndex = 0;
asyncLib.each(
tasks,
(task, callback) => {
/** @type {Record<string, Source>} */
const assets = Object.create(null);
/** @type {Record<string, AssetInfo | undefined>} */
const assetsInfo = Object.create(null);
const file = task.file;
const chunk = fileToChunk.get(file);
const sourceMap = task.sourceMap;
const source = task.source;
const modules = task.modules;
reportProgress(
0.5 + (0.5 * taskIndex) / tasks.length,
file,
"attach SourceMap"
);
const moduleFilenames =
/** @type {string[]} */
(modules.map((m) => moduleToSourceNameMapping.get(m)));
// We deliberately do NOT mutate `sourceMap` in place: the
// task's `sourceMap` reference may be shared with a
// `SourceMapSource` whose internal map cache is the same
// object (webpack-sources keeps it cached). A second
// `SourceMapDevToolPlugin` instance that reads the original
// source through the registry would otherwise see our
// rewrites. Instead we build a fresh `outputSourceMap` for
// the .map file and leave the original alone.
/** @type {number[] | undefined} */
let ignoreList;
if (options.ignoreList) {
const list = moduleFilenames.reduce(
/** @type {(acc: number[], sourceName: string, idx: number) => number[]} */ (
(acc, sourceName, idx) => {
const rule = /** @type {Rules} */ (
options.ignoreList
);
if (
ModuleFilenameHelpers.matchPart(sourceName, rule)
) {
acc.push(idx);
}
return acc;
}
),
[]
);
if (list.length > 0) ignoreList = list;
}
const usesContentHash =
sourceMapFilename &&
CONTENT_HASH_DETECT_REGEXP.test(sourceMapFilename);
resetRegexpState(CONTENT_HASH_DETECT_REGEXP);
let outputFile = file;
// If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file`
if (usesContentHash && task.assetInfo.contenthash) {
const contenthash = task.assetInfo.contenthash;
const pattern = Array.isArray(contenthash)
? contenthash.map(quoteMeta).join("|")
: quoteMeta(contenthash);
outputFile = outputFile.replace(
new RegExp(pattern, "g"),
(m) => "x".repeat(m.length)
);
}
/** @type {false | SourceMappingURLComment} */
let currentSourceMappingURLComment = sourceMappingURLComment;
const cssExtensionDetected =
CSS_EXTENSION_DETECT_REGEXP.test(file);
resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
if (
currentSourceMappingURLComment !== false &&
typeof currentSourceMappingURLComment !== "function" &&
cssExtensionDetected
) {
currentSourceMappingURLComment =
currentSourceMappingURLComment.replace(
URL_FORMATTING_REGEXP,
"\n/*$1*/"
);
}
/** @type {string | undefined} */
let debugIdValue;
if (options.debugIds) {
const debugId = generateDebugId(source, outputFile);
debugIdValue = debugId;
const debugIdComment = `\n//# debugId=${debugId}`;
if (currentSourceMappingURLComment === false) {
currentSourceMappingURLComment = debugIdComment;
} else if (
typeof currentSourceMappingURLComment === "function"
) {
// Wrap the user's append function so the debug-id
// comment is prepended at call time. Template-string
// concatenation would coerce the function to a string
// and lose its dynamic behavior.
const wrappedFn = currentSourceMappingURLComment;
currentSourceMappingURLComment = (pathData, assetInfo) =>
`${debugIdComment}${wrappedFn(pathData, assetInfo)}`;
} else {
currentSourceMappingURLComment = `${debugIdComment}${currentSourceMappingURLComment}`;
}
}
/** @type {RawSourceMap} */
const outputSourceMap = {
...sourceMap,
sources: moduleFilenames,
sourceRoot: options.sourceRoot || "",
file: outputFile
};
if (ignoreList !== undefined) {
outputSourceMap.ignoreList = ignoreList;
}
if (options.noSources) {
outputSourceMap.sourcesContent = undefined;
}
if (debugIdValue !== undefined) {
outputSourceMap.debugId = debugIdValue;
}
if (sourceMapFilename) {
// External `.map` file: hold the serialized map as a
// `Buffer` instead of a V8 string. `RawSource` accepts
// a buffer directly, and the emitted asset stays in
// `compilation.assets` until the build finishes — so
// storing the bytes off the V8 heap (where Buffers
// live, accounted as `external` memory) avoids keeping
// a large V8 string alive for the rest of the build
// and reduces heap pressure on `--max-old-space-size`.
const sourceMapBuffer = Buffer.from(
JSON.stringify(outputSourceMap),
"utf8"
);
const filename = file;
const sourceMapContentHash = usesContentHash
? createHash(compilation.outputOptions.hashFunction)
.update(sourceMapBuffer)
.digest("hex")
: undefined;
const pathParams = {
chunk,
filename: options.fileContext
? relative(
outputFs,
`/${options.fileContext}`,
`/${filename}`
)
: filename,
contentHash: sourceMapContentHash
};
const { path: sourceMapFile, info: sourceMapInfo } =
compilation.getPathWithInfo(
sourceMapFilename,
pathParams
);
const sourceMapUrl = options.publicPath
? options.publicPath + sourceMapFile
: relative(
outputFs,
dirname(outputFs, `/${file}`),
`/${sourceMapFile}`
);
/** @type {Source} */
let asset = new RawSource(source);
if (currentSourceMappingURLComment !== false) {
// Add source map url to compilation asset, if currentSourceMappingURLComment is set
asset = new ConcatSource(
asset,
compilation.getPath(currentSourceMappingURLComment, {
url: sourceMapUrl,
...pathParams
})
);
}
// Preserve any existing related.sourceMap entries from
// earlier SourceMapDevToolPlugin runs on the same asset so
// that all generated maps remain discoverable via asset
// info (the schema allows string or string[]).
const existingSourceMap =
task.assetInfo.related &&
task.assetInfo.related.sourceMap;
/** @type {string | string[]} */
let relatedSourceMap;
if (
existingSourceMap === undefined ||
existingSourceMap === null
) {
relatedSourceMap = sourceMapFile;
} else if (Array.isArray(existingSourceMap)) {
relatedSourceMap = existingSourceMap.includes(
sourceMapFile
)
? existingSourceMap
: [...existingSourceMap, sourceMapFile];
} else {
relatedSourceMap =
existingSourceMap === sourceMapFile
? existingSourceMap
: [existingSourceMap, sourceMapFile];
}
const assetInfo = {
related: { sourceMap: relatedSourceMap }
};
assets[file] = asset;
assetsInfo[file] = assetInfo;
compilation.updateAsset(file, asset, assetInfo);
// Add source map file to compilation assets and chunk files
const sourceMapAsset = new RawSource(sourceMapBuffer);
const sourceMapAssetInfo = {
...sourceMapInfo,
development: true
};
assets[sourceMapFile] = sourceMapAsset;
assetsInfo[sourceMapFile] = sourceMapAssetInfo;
compilation.emitAsset(
sourceMapFile,
sourceMapAsset,
sourceMapAssetInfo
);
if (chunk !== undefined) {
chunk.auxiliaryFiles.add(sourceMapFile);
}
} else {
if (currentSourceMappingURLComment === false) {
throw new Error(
`${PLUGIN_NAME}: append can't be false when no filename is provided`
);
}
if (typeof currentSourceMappingURLComment === "function") {
throw new Error(
`${PLUGIN_NAME}: append can't be a function when no filename is provided`
);
}
// Inline data-URL form: `[map]` gets the raw JSON, `[url]`
// gets the same JSON base64-encoded. `URL_COMMENT_REGEXP`
// is a `/g` regex, so a user `append` template with more
// than one `[url]` placeholder would otherwise re-encode
// the same JSON per match. Pre-compute both once.
const sourceMapString = JSON.stringify(outputSourceMap);
const sourceMapBase64 = Buffer.from(
sourceMapString,
"utf8"
).toString("base64");
/**
* Add source map as data url to asset
*/
const asset = new ConcatSource(
new RawSource(source),
currentSourceMappingURLComment
.replace(MAP_URL_COMMENT_REGEXP, () => sourceMapString)
.replace(
URL_COMMENT_REGEXP,
() =>
`data:application/json;charset=utf-8;base64,${sourceMapBase64}`
)
);
assets[file] = asset;
assetsInfo[file] = undefined;
compilation.updateAsset(file, asset);
}
task.cacheItem.store({ assets, assetsInfo }, (err) => {
reportProgress(
0.5 + (0.5 * ++taskIndex) / tasks.length,
task.file,
"attached SourceMap"
);
if (err) {
return callback(err);
}
callback();
});
},
(err) => {
reportProgress(1);
callback(err);
}
);
}
);
}
);
});
}
}
module.exports = SourceMapDevToolPlugin;

94
node_modules/webpack/lib/Stats.js generated vendored Normal file
View File

@@ -0,0 +1,94 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
/** @typedef {import("../declarations/WebpackOptions").StatsValue} StatsValue */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */
class Stats {
/**
* Creates an instance of Stats.
* @param {Compilation} compilation webpack compilation
*/
constructor(compilation) {
this.compilation = compilation;
}
get hash() {
return this.compilation.hash;
}
get startTime() {
return this.compilation.startTime;
}
get endTime() {
return this.compilation.endTime;
}
/**
* Checks whether this stats has warnings.
* @returns {boolean} true if the compilation had a warning
*/
hasWarnings() {
return (
this.compilation.getWarnings().length > 0 ||
this.compilation.children.some((child) => child.getStats().hasWarnings())
);
}
/**
* Checks whether this stats has errors.
* @returns {boolean} true if the compilation encountered an error
*/
hasErrors() {
return (
this.compilation.errors.length > 0 ||
this.compilation.children.some((child) => child.getStats().hasErrors())
);
}
/**
* Returns json output.
* @param {StatsValue=} options stats options
* @returns {StatsCompilation} json output
*/
toJson(options) {
const normalizedOptions = this.compilation.createStatsOptions(options, {
forToString: false
});
const statsFactory = this.compilation.createStatsFactory(normalizedOptions);
return statsFactory.create("compilation", this.compilation, {
compilation: this.compilation
});
}
/**
* Returns a string representation.
* @param {StatsValue=} options stats options
* @returns {string} string output
*/
toString(options) {
const normalizedOptions = this.compilation.createStatsOptions(options, {
forToString: true
});
const statsFactory = this.compilation.createStatsFactory(normalizedOptions);
const statsPrinter = this.compilation.createStatsPrinter(normalizedOptions);
const data = statsFactory.create("compilation", this.compilation, {
compilation: this.compilation
});
const result = statsPrinter.print("compilation", data);
return result === undefined ? "" : result;
}
}
module.exports = Stats;

447
node_modules/webpack/lib/Template.js generated vendored Normal file
View File

@@ -0,0 +1,447 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, PrefixSource } = require("webpack-sources");
const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./RuntimeModule")} RuntimeModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $
const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9
const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g;
const INDENT_MULTILINE_REGEX = /^\t/gm;
const LINE_SEPARATOR_REGEX = /\r?\n/g;
const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-z$_])/i;
const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-z0-9$]+/gi;
const COMMENT_END_REGEX = /\*\//g;
const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-z0-9_!§$()=\-^°]+/gi;
const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
/**
* Defines the render manifest options type used by this module.
* @typedef {object} RenderManifestOptions
* @property {Chunk} chunk the chunk used to render
* @property {string} hash
* @property {string} fullHash
* @property {OutputOptions} outputOptions
* @property {CodeGenerationResults} codeGenerationResults
* @property {{ javascript: ModuleTemplate }} moduleTemplates
* @property {DependencyTemplates} dependencyTemplates
* @property {RuntimeTemplate} runtimeTemplate
* @property {ModuleGraph} moduleGraph
* @property {ChunkGraph} chunkGraph
*/
/** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */
/**
* Defines the render manifest entry templated type used by this module.
* @typedef {object} RenderManifestEntryTemplated
* @property {() => Source} render
* @property {string | import("./TemplatedPathPlugin").TemplatePathFn<EXPECTED_ANY>} filenameTemplate
* @property {PathData=} pathOptions
* @property {AssetInfo=} info
* @property {string} identifier
* @property {string=} hash
* @property {boolean=} auxiliary
*/
/**
* Defines the render manifest entry static type used by this module.
* @typedef {object} RenderManifestEntryStatic
* @property {() => Source} render
* @property {string} filename
* @property {AssetInfo} info
* @property {string} identifier
* @property {string=} hash
* @property {boolean=} auxiliary
*/
/**
* Defines the module filter predicate type used by this module.
* @typedef {(module: Module) => boolean} ModuleFilterPredicate
*/
/**
* Represents the template runtime component.
* @typedef {object} Stringable
* @property {() => string} toString
*/
class Template {
/**
* Gets function content.
* @param {Stringable} fn a runtime function (.runtime.js) "template"
* @returns {string} the updated and normalized function string
*/
static getFunctionContent(fn) {
return fn
.toString()
.replace(FUNCTION_CONTENT_REGEX, "")
.replace(INDENT_MULTILINE_REGEX, "")
.replace(LINE_SEPARATOR_REGEX, "\n");
}
/**
* Returns created identifier.
* @param {string} str the string converted to identifier
* @returns {string} created identifier
*/
static toIdentifier(str) {
if (typeof str !== "string") return "";
return str
.replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1")
.replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
}
/**
* Returns a commented version of string.
* @param {string} str string to be converted to commented in bundle code
* @returns {string} returns a commented version of string
*/
static toComment(str) {
if (!str) return "";
return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`;
}
/**
* Returns a commented version of string.
* @param {string} str string to be converted to "normal comment"
* @returns {string} returns a commented version of string
*/
static toNormalComment(str) {
if (!str) return "";
return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`;
}
/**
* Returns normalized bundle-safe path.
* @param {string} str string path to be normalized
* @returns {string} normalized bundle-safe path
*/
static toPath(str) {
if (typeof str !== "string") return "";
return str
.replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-")
.replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
}
// map number to a single character a-z, A-Z or multiple characters if number is too big
/**
* Number to identifier.
* @param {number} n number to convert to ident
* @returns {string} returns single character ident
*/
static numberToIdentifier(n) {
if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) {
// use multiple letters
return (
Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) +
Template.numberToIdentifierContinuation(
Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS)
)
);
}
// lower case
if (n < DELTA_A_TO_Z) {
return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
}
n -= DELTA_A_TO_Z;
// upper case
if (n < DELTA_A_TO_Z) {
return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
}
if (n === DELTA_A_TO_Z) return "_";
return "$";
}
/**
* Number to identifier continuation.
* @param {number} n number to convert to ident
* @returns {string} returns single character ident
*/
static numberToIdentifierContinuation(n) {
if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) {
// use multiple letters
return (
Template.numberToIdentifierContinuation(
n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS
) +
Template.numberToIdentifierContinuation(
Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS)
)
);
}
// lower case
if (n < DELTA_A_TO_Z) {
return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
}
n -= DELTA_A_TO_Z;
// upper case
if (n < DELTA_A_TO_Z) {
return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
}
n -= DELTA_A_TO_Z;
// numbers
if (n < 10) {
return `${n}`;
}
if (n === 10) return "_";
return "$";
}
/**
* Returns converted identity.
* @param {string | string[]} s string to convert to identity
* @returns {string} converted identity
*/
static indent(s) {
if (Array.isArray(s)) {
return s.map(Template.indent).join("\n");
}
const str = s.trimEnd();
if (!str) return "";
const ind = str[0] === "\n" ? "" : "\t";
return ind + str.replace(/\n([^\n])/g, "\n\t$1");
}
/**
* Returns new prefix string.
* @param {string | string[]} s string to create prefix for
* @param {string} prefix prefix to compose
* @returns {string} returns new prefix string
*/
static prefix(s, prefix) {
const str = Template.asString(s).trim();
if (!str) return "";
const ind = str[0] === "\n" ? "" : prefix;
return ind + str.replace(/\n([^\n])/g, `\n${prefix}$1`);
}
/**
* Returns a single string from array.
* @param {string | string[]} str string or string collection
* @returns {string} returns a single string from array
*/
static asString(str) {
if (Array.isArray(str)) {
return str.join("\n");
}
return str;
}
/**
* Defines the with id type used by this module.
* @typedef {object} WithId
* @property {string | number} id
*/
/**
* Gets modules array bounds.
* @param {WithId[]} modules a collection of modules to get array bounds for
* @returns {[number, number] | false} returns the upper and lower array bounds
* or false if not every module has a number based id
*/
static getModulesArrayBounds(modules) {
let maxId = -Infinity;
let minId = Infinity;
for (const module of modules) {
const moduleId = module.id;
if (typeof moduleId !== "number") return false;
if (maxId < moduleId) maxId = moduleId;
if (minId > moduleId) minId = moduleId;
}
if (minId < 16 + String(minId).length) {
// add minId x ',' instead of 'Array(minId).concat(…)'
minId = 0;
}
// start with -1 because the first module needs no comma
let objectOverhead = -1;
for (const module of modules) {
// module id + colon + comma
objectOverhead += `${module.id}`.length + 2;
}
// number of commas, or when starting non-zero the length of Array(minId).concat()
const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId;
return arrayOverhead < objectOverhead ? [minId, maxId] : false;
}
/**
* Renders chunk modules.
* @param {ChunkRenderContext} renderContext render context
* @param {Module[]} modules modules to render (should be ordered by identifier)
* @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
*/
static renderChunkModules(renderContext, modules, renderModule, prefix = "") {
const { chunkGraph } = renderContext;
const source = new ConcatSource();
if (modules.length === 0) {
return null;
}
/** @type {{ id: ModuleId, module: Module }[]} */
const modulesWithId = modules.map((m) => ({
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(m)),
module: m
}));
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];
const maxId = bounds[1];
if (minId !== 0) {
source.add(`Array(${minId}).concat(`);
}
source.add("[\n");
/** @type {Map<ModuleId, { id: ModuleId, source: Source | "false" }>} */
const modules = new Map();
for (const module of allModules) {
modules.set(module.id, module);
}
for (let idx = minId; idx <= maxId; idx++) {
const module = modules.get(idx);
if (idx !== minId) {
source.add(",\n");
}
source.add(`/* ${idx} */`);
if (module) {
source.add("\n");
source.add(module.source);
}
}
source.add(`\n${prefix}]`);
if (minId !== 0) {
source.add(")");
}
} else {
// Render an object
source.add("{\n");
for (let i = 0; i < allModules.length; i++) {
const module = allModules[i];
if (i !== 0) {
source.add(",\n");
}
source.add(
`\n/***/ ${JSON.stringify(module.id)}${renderContext.runtimeTemplate.supportsMethodShorthand() && module.source !== "false" ? "" : ":"}\n`
);
source.add(module.source);
}
source.add(`\n\n${prefix}}`);
}
return source;
}
/**
* Renders runtime modules.
* @param {RuntimeModule[]} runtimeModules array of runtime modules in order
* @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context
* @returns {Source} rendered runtime modules in a Source object
*/
static renderRuntimeModules(runtimeModules, renderContext) {
const source = new ConcatSource();
for (const module of runtimeModules) {
const codeGenerationResults = renderContext.codeGenerationResults;
/** @type {undefined | Source} */
let runtimeSource;
if (codeGenerationResults) {
runtimeSource = codeGenerationResults.getSource(
module,
renderContext.chunk.runtime,
WEBPACK_MODULE_TYPE_RUNTIME
);
} else {
const codeGenResult = module.codeGeneration({
chunkGraph: renderContext.chunkGraph,
dependencyTemplates: renderContext.dependencyTemplates,
moduleGraph: renderContext.moduleGraph,
runtimeTemplate: renderContext.runtimeTemplate,
runtime: renderContext.chunk.runtime,
runtimes: [renderContext.chunk.runtime],
codeGenerationResults
});
if (!codeGenResult) continue;
runtimeSource = codeGenResult.sources.get("runtime");
}
if (runtimeSource) {
source.add(`${Template.toNormalComment(module.identifier())}\n`);
if (!module.shouldIsolate()) {
source.add(runtimeSource);
source.add("\n\n");
} else if (renderContext.runtimeTemplate.supportsArrowFunction()) {
source.add("(() => {\n");
source.add(new PrefixSource("\t", runtimeSource));
source.add("\n})();\n\n");
} else {
source.add("!function() {\n");
source.add(new PrefixSource("\t", runtimeSource));
source.add("\n}();\n\n");
}
}
}
return source;
}
/**
* Renders chunk runtime modules.
* @param {RuntimeModule[]} runtimeModules array of runtime modules in order
* @param {RenderContext} renderContext render context
* @returns {Source} rendered chunk runtime modules in a Source object
*/
static renderChunkRuntimeModules(runtimeModules, renderContext) {
return new PrefixSource(
"/******/ ",
new ConcatSource(
`function(${RuntimeGlobals.require}) { // webpackRuntimeModules\n`,
this.renderRuntimeModules(runtimeModules, renderContext),
"}\n"
)
);
}
}
module.exports = Template;
module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS;
module.exports.NUMBER_OF_IDENTIFIER_START_CHARS =
NUMBER_OF_IDENTIFIER_START_CHARS;

426
node_modules/webpack/lib/TemplatedPathPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,426 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Jason Anderson @diurnalist
*/
"use strict";
const { basename, extname } = require("path");
const util = require("util");
const Chunk = require("./Chunk");
const Module = require("./Module");
const { parseResource } = require("./util/identifier");
const memoize = require("./util/memoize");
const getMimeTypes = memoize(() => require("./util/mimeTypes"));
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./Compilation").PathDataChunk} PathDataChunk */
/** @typedef {import("./Compilation").PathDataModule} PathDataModule */
/** @typedef {import("./Compiler")} Compiler */
const REGEXP = /\[\\*([\w:]+)\\*\]/g;
/** @type {PathData["prepareId"]} */
const prepareId = (id) => {
if (typeof id !== "string") return id;
if (/^"\s\+*.*\+\s*"$/.test(id)) {
const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id);
return `" + (${
/** @type {string[]} */ (match)[1]
} + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`;
}
return id.replace(/(^[.-]|[^a-z0-9_-])+/gi, "_");
};
/**
* Defines the replacer function callback.
* @callback ReplacerFunction
* @param {string} match
* @param {string | undefined} arg
* @param {string} input
*/
/**
* Returns hash replacer function.
* @param {ReplacerFunction} replacer replacer
* @param {((arg0: number) => string) | undefined} handler handler
* @param {AssetInfo | undefined} assetInfo asset info
* @param {string} hashName hash name
* @returns {Replacer} hash replacer function
*/
const hashLength = (replacer, handler, assetInfo, hashName) => {
/** @type {Replacer} */
const fn = (match, arg, input) => {
/** @type {string} */
let result;
const length = arg && Number.parseInt(arg, 10);
if (length && handler) {
result = handler(length);
} else {
const hash = replacer(match, arg, input);
result = length ? hash.slice(0, length) : hash;
}
if (assetInfo) {
assetInfo.immutable = true;
if (Array.isArray(assetInfo[hashName])) {
assetInfo[hashName] = [...assetInfo[hashName], result];
} else if (assetInfo[hashName]) {
assetInfo[hashName] = [assetInfo[hashName], result];
} else {
assetInfo[hashName] = result;
}
}
return result;
};
return fn;
};
/** @typedef {(match: string, arg: string | undefined, input: string) => string} Replacer */
/**
* Returns replacer.
* @param {string | number | null | undefined | (() => string | number | null | undefined)} value value
* @param {boolean=} allowEmpty allow empty
* @returns {Replacer} replacer
*/
const replacer = (value, allowEmpty) => {
/** @type {Replacer} */
const fn = (match, arg, input) => {
if (typeof value === "function") {
value = value();
}
if (value === null || value === undefined) {
if (!allowEmpty) {
throw new Error(
`Path variable ${match} not implemented in this context: ${input}`
);
}
return "";
}
return `${value}`;
};
return fn;
};
/** @type {Map<string, (...args: EXPECTED_ANY[]) => EXPECTED_ANY>} */
const deprecationCache = new Map();
const deprecatedFunction = (() => () => {})();
/**
* Returns function with deprecation output.
* @template {(...args: EXPECTED_ANY[]) => EXPECTED_ANY} T
* @param {T} fn function
* @param {string} message message
* @param {string} code code
* @returns {T} function with deprecation output
*/
const deprecated = (fn, message, code) => {
let d = deprecationCache.get(message);
if (d === undefined) {
d = util.deprecate(deprecatedFunction, message, code);
deprecationCache.set(message, d);
}
return /** @type {T} */ (
(...args) => {
d();
return fn(...args);
}
);
};
/**
* Callback used to compute a path from contextual data. The type parameter
* narrows the `pathData` shape when the caller knows it operates in a chunk
* (`PathDataChunk`) or module (`PathDataModule`) context — defaults to the
* fully-optional `PathData` for backward compatibility.
* @template {PathData} [T=PathData]
* @typedef {(pathData: T, assetInfo?: AssetInfo) => string} TemplatePathFn
*/
/**
* Either a raw template string (e.g. `"[name].[contenthash].js"`) or a
* generic `TemplatePathFn`. Method signatures that need to thread a narrowed
* `PathData` shape spell the function side out as `TemplatePathFn<T>`
* directly — `TemplatePath` itself stays a plain alias so local JSDoc
* re-imports keep a single shared identity.
* @typedef {string | TemplatePathFn} TemplatePath
*/
/**
* Returns the interpolated path.
* @template {PathData} [T=PathData]
* @param {string | TemplatePathFn<T>} path the raw path
* @param {T} data context data
* @param {AssetInfo=} assetInfo extra info about the asset (will be written to)
* @returns {string} the interpolated path
*/
const interpolate = (path, data, assetInfo) => {
const chunkGraph = data.chunkGraph;
/** @type {Map<string, Replacer>} */
const replacements = new Map();
// Filename context
//
// Placeholders
//
// for /some/path/file.js?query#fragment:
// [file] - /some/path/file.js
// [query] - ?query
// [fragment] - #fragment
// [base] - file.js
// [path] - /some/path/
// [name] - file
// [ext] - .js
if (typeof data.filename === "string") {
// check that filename is data uri
const match = data.filename.match(/^data:([^;,]+)/);
if (match) {
const ext = getMimeTypes().extension(match[1]);
const emptyReplacer = replacer("", true);
// "XXXX" used for `updateHash`, so we don't need it here
const contentHash =
data.contentHash && !/X+/.test(data.contentHash)
? data.contentHash
: false;
const baseReplacer = contentHash ? replacer(contentHash) : emptyReplacer;
replacements.set("file", emptyReplacer);
replacements.set("query", emptyReplacer);
replacements.set("fragment", emptyReplacer);
replacements.set("path", emptyReplacer);
replacements.set("base", baseReplacer);
replacements.set("name", baseReplacer);
replacements.set("ext", replacer(ext ? `.${ext}` : "", true));
// Legacy
replacements.set(
"filebase",
deprecated(
baseReplacer,
"[filebase] is now [base]",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
)
);
} else {
const { path: file, query, fragment } = parseResource(data.filename);
const ext = extname(file);
const base = basename(file);
const name = base.slice(0, base.length - ext.length);
const path = file.slice(0, file.length - base.length);
replacements.set("file", replacer(file));
replacements.set("query", replacer(query, true));
replacements.set("fragment", replacer(fragment, true));
replacements.set("path", replacer(path, true));
replacements.set("base", replacer(base));
replacements.set("name", replacer(name));
replacements.set("ext", replacer(ext, true));
// Legacy
replacements.set(
"filebase",
deprecated(
replacer(base),
"[filebase] is now [base]",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
)
);
}
}
// Compilation context
//
// Placeholders
//
// [fullhash] - data.hash (3a4b5c6e7f)
//
// Legacy Placeholders
//
// [hash] - data.hash (3a4b5c6e7f)
if (data.hash) {
const hashReplacer = hashLength(
replacer(data.hash),
data.hashWithLength,
assetInfo,
"fullhash"
);
replacements.set("fullhash", hashReplacer);
// Legacy
replacements.set(
"hash",
deprecated(
hashReplacer,
"[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH"
)
);
}
// Chunk Context
//
// Placeholders
//
// [id] - chunk.id (0.js)
// [name] - chunk.name (app.js)
// [chunkhash] - chunk.hash (7823t4t4.js)
// [contenthash] - chunk.contentHash[type] (3256u3zg.js)
if (data.chunk) {
const chunk = data.chunk;
const contentHashType = data.contentHashType;
const idReplacer = replacer(chunk.id);
const nameReplacer = replacer(chunk.name || chunk.id);
const chunkhashReplacer = hashLength(
replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash),
"hashWithLength" in chunk ? chunk.hashWithLength : undefined,
assetInfo,
"chunkhash"
);
const contenthashReplacer = hashLength(
replacer(
data.contentHash ||
(contentHashType &&
chunk.contentHash &&
chunk.contentHash[contentHashType])
),
data.contentHashWithLength ||
("contentHashWithLength" in chunk && chunk.contentHashWithLength
? chunk.contentHashWithLength[/** @type {string} */ (contentHashType)]
: undefined),
assetInfo,
"contenthash"
);
replacements.set("id", idReplacer);
replacements.set("name", nameReplacer);
replacements.set("chunkhash", chunkhashReplacer);
replacements.set("contenthash", contenthashReplacer);
}
// Module Context
//
// Placeholders
//
// [id] - module.id (2.png)
// [hash] - module.hash (6237543873.png)
//
// Legacy Placeholders
//
// [moduleid] - module.id (2.png)
// [modulehash] - module.hash (6237543873.png)
if (data.module) {
const module = data.module;
const idReplacer = replacer(() =>
(data.prepareId || prepareId)(
module instanceof Module
? /** @type {ModuleId} */
(/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
: module.id
)
);
const moduleHashReplacer = hashLength(
replacer(() =>
module instanceof Module
? /** @type {ChunkGraph} */
(chunkGraph).getRenderedModuleHash(module, data.runtime)
: module.hash
),
"hashWithLength" in module ? module.hashWithLength : undefined,
assetInfo,
"modulehash"
);
const contentHashReplacer = hashLength(
replacer(/** @type {string} */ (data.contentHash)),
undefined,
assetInfo,
"contenthash"
);
replacements.set("id", idReplacer);
replacements.set("modulehash", moduleHashReplacer);
replacements.set("contenthash", contentHashReplacer);
replacements.set(
"hash",
data.contentHash ? contentHashReplacer : moduleHashReplacer
);
// Legacy
replacements.set(
"moduleid",
deprecated(
idReplacer,
"[moduleid] is now [id]",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID"
)
);
}
// Other things
if (data.url) {
replacements.set("url", replacer(data.url));
}
if (typeof data.runtime === "string") {
replacements.set(
"runtime",
replacer(() =>
(data.prepareId || prepareId)(/** @type {string} */ (data.runtime))
)
);
} else {
replacements.set("runtime", replacer("_"));
}
if (typeof path === "function") {
path = path(data, assetInfo);
}
path = path.replace(REGEXP, (match, content) => {
if (content.length + 2 === match.length) {
const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content);
if (!contentMatch) return match;
const [, kind, arg] = contentMatch;
const replacer = replacements.get(kind);
if (replacer !== undefined) {
return replacer(match, arg, /** @type {string} */ (path));
}
} else if (match.startsWith("[\\") && match.endsWith("\\]")) {
return `[${match.slice(2, -2)}]`;
}
return match;
});
return path;
};
const plugin = "TemplatedPathPlugin";
class TemplatedPathPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(plugin, (compilation) => {
compilation.hooks.assetPath.tap(plugin, interpolate);
});
}
}
module.exports = TemplatedPathPlugin;
module.exports.interpolate = interpolate;

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