| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793 |
- /*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
- "use strict";
- const { OriginalSource, RawSource } = require("webpack-sources");
- const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
- const Module = require("./Module");
- const {
- JAVASCRIPT_TYPE,
- JAVASCRIPT_TYPES
- } = require("./ModuleSourceTypeConstants");
- const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
- const RuntimeGlobals = require("./RuntimeGlobals");
- const Template = require("./Template");
- const {
- getOutgoingAsyncModules
- } = require("./async-modules/AsyncModuleHelpers");
- const { ImportPhase, ImportPhaseUtils } = require("./dependencies/ImportPhase");
- const { makeWebpackError } = require("./errors/HookWebpackError");
- const WebpackError = require("./errors/WebpackError");
- const {
- compareLocations,
- compareModulesById,
- compareSelect,
- concatComparators,
- keepOriginalOrder
- } = require("./util/comparators");
- const {
- contextify,
- makePathsRelative,
- parseResource
- } = require("./util/identifier");
- const makeSerializable = require("./util/makeSerializable");
- const { propertyAccess } = require("./util/property");
- /** @import { Source } from "webpack-sources" */
- /** @import { ResolveOptions } from "../declarations/WebpackOptions" */
- /**
- * @import {
- * WebpackOptionsNormalizedWithDefaults as WebpackOptions
- * } from "./config/defaults"
- */
- /** @import Chunk, { ChunkId, ChunkName } from "./Chunk" */
- /** @import ChunkGraph, { ModuleId } from "./ChunkGraph" */
- /** @import { RawChunkGroupOptions } from "./ChunkGroup" */
- /** @import Compilation, { FileSystemDependencies } from "./Compilation" */
- /** @import Dependency, { RawReferencedExports } from "./Dependency" */
- /** @import { Snapshot } from "./FileSystemInfo" */
- /**
- * @import {
- * BuildCallback,
- * BuildInfo,
- * BuildMeta,
- * CodeGenerationContext,
- * CodeGenerationResult,
- * LibIdentOptions,
- * LibIdent,
- * NeedBuildCallback,
- * NeedBuildContext,
- * RuntimeRequirements,
- * Sources,
- * SourceTypes
- * } from "./Module"
- */
- /** @import RequestShortener from "./RequestShortener" */
- /** @import { ResolverWithOptions } from "./ResolverFactory" */
- /** @import RuntimeTemplate from "./RuntimeTemplate" */
- /** @import ContextElementDependency from "./dependencies/ContextElementDependency" */
- /** @import { ImportAttributes } from "./javascript/JavascriptParser" */
- /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext<[string, boolean]>} ObjectDeserializerContext */
- /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext<[string, boolean]>} ObjectSerializerContext */
- /** @import { InputFileSystem } from "./util/fs" */
- /** @import { ImportPhaseType } from "./dependencies/ImportPhase" */
- /** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */
- /**
- * @typedef {object} ContextOptions
- * @property {ContextMode} mode
- * @property {boolean} recursive
- * @property {RegExp | false | null} regExp
- * @property {"strict" | boolean=} namespaceObject
- * @property {string=} addon
- * @property {ChunkName=} chunkName
- * @property {RegExp | null=} include
- * @property {RegExp | null=} exclude
- * @property {RawChunkGroupOptions=} groupOptions
- * @property {string=} typePrefix
- * @property {string=} category
- * @property {RawReferencedExports | null=} referencedExports exports referenced from modules (won't be mangled)
- * @property {string | null=} layer
- * @property {ImportAttributes=} attributes
- * @property {ImportPhaseType=} phase
- * @property {string[]=} patterns glob patterns for import.meta.glob
- * @property {string=} requestContext importer context for import.meta.glob
- * @property {string=} importName import selection for import.meta.glob
- * @property {boolean=} exhaustive exhaustive mode for import.meta.glob
- * @property {boolean=} caseSensitive case-sensitive matching for import.meta.glob
- */
- /**
- * @typedef {object} ContextModuleOptionsExtras
- * @property {string=} request the request of the context as written by the user, before it was resolved
- * @property {false | string | string[]} resource
- * @property {string=} resourceQuery
- * @property {string=} resourceFragment
- * @property {ResolveOptions=} resolveOptions
- */
- /** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */
- /**
- * @callback ResolveDependenciesCallback
- * @param {Error | null} err
- * @param {ContextElementDependency[]=} dependencies
- * @returns {void}
- */
- /**
- * @callback ResolveDependencies
- * @param {InputFileSystem} fs
- * @param {ContextModuleOptions} options
- * @param {ResolveDependenciesCallback} callback
- */
- /** @typedef {1 | 3 | 7 | 9} FakeMapType */
- /** @typedef {Record<ModuleId, FakeMapType>} FakeMap */
- /** @typedef {Record<string, ModuleId>} UserRequestMap */
- /** @typedef {Record<ModuleId, ModuleId[]>} UserRequestsMap */
- /**
- * Defines the build info properties specific to context modules.
- * @typedef {object} KnownContextModuleBuildInfo
- * @property {(InstanceType<Snapshot> | null)=} snapshot
- */
- /** @typedef {BuildInfo & KnownContextModuleBuildInfo} ContextModuleBuildInfo */
- class ContextModule extends Module {
- /**
- * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context
- * @param {ContextModuleOptions} options options object
- */
- constructor(resolveDependencies, options) {
- if (!options || typeof options.resource === "string") {
- const parsed = parseResource(
- options ? /** @type {string} */ (options.resource) : ""
- );
- const resource = parsed.path;
- const resourceQuery = (options && options.resourceQuery) || parsed.query;
- const resourceFragment =
- (options && options.resourceFragment) || parsed.fragment;
- const layer = options && options.layer;
- super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, resource, layer);
- /** @type {ContextModuleOptions} */
- this.options = {
- ...options,
- resource,
- resourceQuery,
- resourceFragment
- };
- } else {
- super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, undefined, options.layer);
- /** @type {ContextModuleOptions} */
- this.options = {
- ...options,
- resource: options.resource,
- resourceQuery: options.resourceQuery || "",
- resourceFragment: options.resourceFragment || ""
- };
- }
- // Redeclared with the context module specific shape
- /** @type {ContextModuleBuildInfo | undefined} */
- this.buildInfo = undefined;
- // Info from Factory
- /** @type {ResolveDependencies | undefined} */
- this.resolveDependencies = resolveDependencies;
- if (options && options.resolveOptions !== undefined) {
- /** @type {ResolveOptions | undefined} */
- this.resolveOptions = options.resolveOptions;
- }
- if (options && typeof options.mode !== "string") {
- throw new Error("options.mode is a required option");
- }
- /** @type {string} */
- this._identifier = this._createIdentifier();
- /** @type {boolean} */
- this._forceBuild = true;
- }
- /**
- * Returns the source types this module can generate.
- * @returns {SourceTypes} types available (do not mutate)
- */
- getSourceTypes() {
- return JAVASCRIPT_TYPES;
- }
- /**
- * Assuming this module is in the cache. Update the (cached) module with
- * the fresh module from the factory. Usually updates internal references
- * and properties.
- * @param {Module} module fresh module
- * @returns {void}
- */
- updateCacheModule(module) {
- const m = /** @type {ContextModule} */ (module);
- this.resolveDependencies = m.resolveDependencies;
- this.options = m.options;
- }
- /**
- * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
- */
- cleanupForCache() {
- super.cleanupForCache();
- this.resolveDependencies = undefined;
- }
- /**
- * @private
- * @param {RegExp} regexString RegExp as a string
- * @param {boolean=} stripSlash do we need to strip a slsh
- * @returns {string} pretty RegExp
- */
- _prettyRegExp(regexString, stripSlash = true) {
- const str = stripSlash
- ? regexString.source + regexString.flags
- : `${regexString}`;
- // Escape chars that are structural in the identifier/source-name URL
- // (`!`/`|` separators, `?` query, `#` fragment) so a regex like
- // `(?:a|b)` isn't misread and truncated when it becomes a source name.
- return str
- .replace(/!/g, "%21")
- .replace(/\|/g, "%7C")
- .replace(/\?/g, "%3F")
- .replace(/#/g, "%23");
- }
- _createIdentifier() {
- let identifier =
- this.context ||
- (typeof this.options.resource === "string" ||
- this.options.resource === false
- ? `${this.options.resource}`
- : this.options.resource.join("|"));
- if (this.options.resourceQuery) {
- identifier += `|${this.options.resourceQuery}`;
- }
- if (this.options.resourceFragment) {
- identifier += `|${this.options.resourceFragment}`;
- }
- if (this.options.mode) {
- identifier += `|${this.options.mode}`;
- }
- if (!this.options.recursive) {
- identifier += "|nonrecursive";
- }
- if (this.options.addon) {
- identifier += `|${this.options.addon}`;
- }
- if (this.options.regExp) {
- identifier += `|${this._prettyRegExp(this.options.regExp, false)}`;
- } else if (this.options.patterns) {
- identifier += `|patterns: ${this.options.patterns.join(", ")}`;
- }
- if (this.options.requestContext) {
- identifier += `|requestContext: ${this.options.requestContext}`;
- }
- if (this.options.include) {
- identifier += `|include: ${this._prettyRegExp(
- this.options.include,
- false
- )}`;
- }
- if (this.options.exclude) {
- identifier += `|exclude: ${this._prettyRegExp(
- this.options.exclude,
- false
- )}`;
- }
- if (this.options.referencedExports) {
- identifier += `|referencedExports: ${JSON.stringify(
- this.options.referencedExports
- )}`;
- }
- if (this.options.importName) {
- identifier += `|import: ${this.options.importName}`;
- }
- if (this.options.exhaustive) {
- identifier += "|exhaustive";
- }
- if (this.options.caseSensitive === false) {
- identifier += "|case-insensitive";
- }
- if (this.options.chunkName) {
- identifier += `|chunkName: ${this.options.chunkName}`;
- }
- if (this.options.groupOptions) {
- identifier += `|groupOptions: ${JSON.stringify(
- this.options.groupOptions
- )}`;
- }
- if (this.options.namespaceObject === "strict") {
- identifier += "|strict namespace object";
- } else if (this.options.namespaceObject) {
- identifier += "|namespace object";
- }
- if (this.options.attributes) {
- identifier += `|importAttributes: ${JSON.stringify(this.options.attributes)}`;
- }
- if (this.options.phase) {
- identifier += `|importPhase: ${this.options.phase}`;
- }
- if (this.layer) {
- identifier += `|layer: ${this.layer}`;
- }
- return identifier;
- }
- /**
- * Returns the unique identifier used to reference this module.
- * @returns {string} a unique identifier of the module
- */
- identifier() {
- return this._identifier;
- }
- /**
- * 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) {
- /** @type {string} */
- let identifier;
- if (this.context) {
- identifier = `${requestShortener.shorten(this.context)}/`;
- } else if (
- typeof this.options.resource === "string" ||
- this.options.resource === false
- ) {
- identifier = `${requestShortener.shorten(`${this.options.resource}`)}/`;
- } else {
- identifier = this.options.resource
- .map((r) => `${requestShortener.shorten(r)}/`)
- .join(" ");
- }
- if (this.options.resourceQuery) {
- identifier += ` ${this.options.resourceQuery}`;
- }
- if (this.options.mode) {
- identifier += ` ${this.options.mode}`;
- }
- if (!this.options.recursive) {
- identifier += " nonrecursive";
- }
- if (this.options.addon) {
- identifier += ` ${requestShortener.shorten(this.options.addon)}`;
- }
- if (this.options.regExp) {
- identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
- } else if (this.options.patterns) {
- identifier += ` patterns: ${this.options.patterns.join(", ")}`;
- }
- if (this.options.requestContext) {
- identifier += ` requestContext: ${this.options.requestContext}`;
- }
- if (this.options.exhaustive) {
- identifier += " exhaustive";
- }
- if (this.options.caseSensitive === false) {
- identifier += " case-insensitive";
- }
- if (this.options.include) {
- identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
- }
- if (this.options.exclude) {
- identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
- }
- if (this.options.referencedExports) {
- identifier += ` referencedExports: ${this.options.referencedExports
- .map((e) => e.join("."))
- .join(", ")}`;
- }
- if (this.options.chunkName) {
- identifier += ` chunkName: ${this.options.chunkName}`;
- }
- if (this.options.groupOptions) {
- const groupOptions = this.options.groupOptions;
- for (const key of Object.keys(groupOptions)) {
- identifier += ` ${key}: ${
- groupOptions[/** @type {keyof RawChunkGroupOptions} */ (key)]
- }`;
- }
- }
- if (this.options.namespaceObject === "strict") {
- identifier += " strict namespace object";
- } else if (this.options.namespaceObject) {
- identifier += " namespace object";
- }
- return identifier;
- }
- /**
- * Gets the library identifier.
- * @param {LibIdentOptions} options options
- * @returns {LibIdent | null} an identifier for library inclusion
- */
- libIdent(options) {
- /** @type {string} */
- let identifier;
- if (this.context) {
- identifier = contextify(
- options.context,
- this.context,
- options.associatedObjectForCache
- );
- } else if (typeof this.options.resource === "string") {
- identifier = contextify(
- options.context,
- this.options.resource,
- options.associatedObjectForCache
- );
- } else if (this.options.resource === false) {
- identifier = "false";
- } else {
- identifier = this.options.resource
- .map((res) =>
- contextify(options.context, res, options.associatedObjectForCache)
- )
- .join(" ");
- }
- if (this.layer) identifier = `(${this.layer})/${identifier}`;
- if (this.options.mode) {
- identifier += ` ${this.options.mode}`;
- }
- if (this.options.recursive) {
- identifier += " recursive";
- }
- if (this.options.addon) {
- identifier += ` ${contextify(
- options.context,
- this.options.addon,
- options.associatedObjectForCache
- )}`;
- }
- if (this.options.regExp) {
- identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
- } else if (this.options.patterns) {
- identifier += ` patterns: ${this.options.patterns.join(", ")}`;
- }
- if (this.options.requestContext) {
- identifier += ` requestContext: ${this.options.requestContext}`;
- }
- if (this.options.exhaustive) {
- identifier += " exhaustive";
- }
- if (this.options.caseSensitive === false) {
- identifier += " case-insensitive";
- }
- if (this.options.include) {
- identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
- }
- if (this.options.exclude) {
- identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
- }
- if (this.options.referencedExports) {
- identifier += ` referencedExports: ${this.options.referencedExports
- .map((e) => e.join("."))
- .join(", ")}`;
- }
- return identifier;
- }
- /**
- * Invalidates the cached state associated with this value.
- * @returns {void}
- */
- invalidateBuild() {
- this._forceBuild = true;
- }
- /**
- * 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({ fileSystemInfo }, callback) {
- // build if enforced
- if (this._forceBuild) return callback(null, true);
- const buildInfo = /** @type {ContextModuleBuildInfo} */ (this.buildInfo);
- // always build when we have no snapshot and context
- if (!buildInfo.snapshot) {
- return callback(null, Boolean(this.context || this.options.resource));
- }
- fileSystemInfo.checkSnapshotValid(buildInfo.snapshot, (err, valid) => {
- callback(err, !valid);
- });
- }
- /**
- * 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._forceBuild = false;
- /** @type {BuildMeta} */
- this.buildMeta = {
- exportsType: "default",
- defaultObject: "redirect-warn"
- };
- // Respect the global module parser `overrideStrict` option
- const overrideStrict =
- options.module.parser &&
- options.module.parser.javascript &&
- options.module.parser.javascript.overrideStrict;
- this.buildInfo = {
- strict: overrideStrict ? overrideStrict === "strict" : undefined,
- snapshot: undefined
- };
- this.dependencies.length = 0;
- this.blocks.length = 0;
- const startTime = Date.now();
- /** @type {ResolveDependencies} */
- (this.resolveDependencies)(fs, this.options, (err, dependencies) => {
- if (err) {
- return callback(
- makeWebpackError(err, "ContextModule.resolveDependencies")
- );
- }
- // abort if something failed
- // this will create an empty context
- if (!dependencies) {
- callback();
- return;
- }
- // enhance dependencies with meta info
- for (const dep of dependencies) {
- dep.loc = {
- name: dep.userRequest
- };
- dep.request = this.options.addon + dep.request;
- }
- dependencies.sort(
- concatComparators(
- compareSelect((a) => a.loc, compareLocations),
- keepOriginalOrder(this.dependencies)
- )
- );
- if (this.options.mode === "sync" || this.options.mode === "eager") {
- // if we have an sync or eager context
- // just add all dependencies and continue
- this.dependencies = dependencies;
- } else if (this.options.mode === "lazy-once") {
- // for the lazy-once mode create a new async dependency block
- // and add that block to this context
- if (dependencies.length > 0) {
- const block = new AsyncDependenciesBlock({
- ...this.options.groupOptions,
- name: this.options.chunkName
- });
- for (const dep of dependencies) {
- block.addDependency(dep);
- }
- this.addBlock(block);
- }
- } else if (
- this.options.mode === "weak" ||
- this.options.mode === "async-weak"
- ) {
- // we mark all dependencies as weak
- for (const dep of dependencies) {
- dep.weak = true;
- }
- this.dependencies = dependencies;
- } else if (this.options.mode === "lazy") {
- // if we are lazy create a new async dependency block per dependency
- // and add all blocks to this context
- let index = 0;
- for (const dep of dependencies) {
- let chunkName = this.options.chunkName;
- if (chunkName) {
- if (!/\[(?:index|request)\]/.test(chunkName)) {
- chunkName += "[index]";
- }
- chunkName = chunkName.replace(/\[index\]/g, `${index++}`);
- chunkName = chunkName.replace(
- /\[request\]/g,
- Template.toPath(dep.userRequest)
- );
- }
- const block = new AsyncDependenciesBlock(
- {
- ...this.options.groupOptions,
- name: chunkName
- },
- dep.loc,
- dep.userRequest
- );
- block.addDependency(dep);
- this.addBlock(block);
- }
- } else {
- callback(
- new WebpackError(`Unsupported mode "${this.options.mode}" in context`)
- );
- return;
- }
- if (!this.context && !this.options.resource) return callback();
- const snapshotOptions = compilation.options.snapshot.contextModule;
- compilation.fileSystemInfo.createSnapshot(
- startTime,
- null,
- this.context
- ? [this.context]
- : typeof this.options.resource === "string"
- ? [this.options.resource]
- : /** @type {string[]} */ (this.options.resource),
- null,
- snapshotOptions,
- (err, snapshot) => {
- if (err) return callback(err);
- /** @type {BuildInfo} */
- (this.buildInfo).snapshot = snapshot;
- callback();
- }
- );
- });
- }
- /**
- * Adds the provided file dependencies to the module.
- * @param {FileSystemDependencies} fileDependencies set where file dependencies are added to
- * @param {FileSystemDependencies} contextDependencies set where context dependencies are added to
- * @param {FileSystemDependencies} missingDependencies set where missing dependencies are added to
- * @param {FileSystemDependencies} buildDependencies set where build dependencies are added to
- */
- addCacheDependencies(
- fileDependencies,
- contextDependencies,
- missingDependencies,
- buildDependencies
- ) {
- if (this.context) {
- contextDependencies.add(this.context);
- } else if (typeof this.options.resource === "string") {
- contextDependencies.add(this.options.resource);
- } else if (this.options.resource === false) {
- // Do nothing
- } else {
- for (const res of this.options.resource) contextDependencies.add(res);
- }
- }
- /**
- * @param {Dependency[]} dependencies all dependencies
- * @param {ChunkGraph} chunkGraph chunk graph
- * @returns {UserRequestMap} map with user requests
- */
- getUserRequestMap(dependencies, chunkGraph) {
- const moduleGraph = chunkGraph.moduleGraph;
- // if we filter first we get a new array
- // therefore we don't need to create a clone of dependencies explicitly
- // therefore the order of this is !important!
- const sortedDependencies =
- /** @type {ContextElementDependency[]} */
- (dependencies)
- .filter((dependency) => moduleGraph.getModule(dependency))
- .sort((a, b) => {
- if (a.userRequest === b.userRequest) {
- return 0;
- }
- return a.userRequest < b.userRequest ? -1 : 1;
- });
- /** @type {UserRequestMap} */
- const map = Object.create(null);
- for (const dep of sortedDependencies) {
- const module = /** @type {Module} */ (moduleGraph.getModule(dep));
- map[dep.userRequest] =
- /** @type {ModuleId} */
- (chunkGraph.getModuleId(module));
- }
- return map;
- }
- /**
- * @param {Dependency[]} dependencies all dependencies
- * @param {ChunkGraph} chunkGraph chunk graph
- * @returns {FakeMap | FakeMapType} fake map
- */
- getFakeMap(dependencies, chunkGraph) {
- if (!this.options.namespaceObject) {
- return 9;
- }
- const moduleGraph = chunkGraph.moduleGraph;
- // bitfield
- let hasType = 0;
- const comparator = compareModulesById(chunkGraph);
- // if we filter first we get a new array
- // therefore we don't need to create a clone of dependencies explicitly
- // therefore the order of this is !important!
- const sortedModules = dependencies
- .map(
- (dependency) =>
- /** @type {Module} */ (moduleGraph.getModule(dependency))
- )
- .filter(Boolean)
- .sort(comparator);
- /** @type {FakeMap} */
- const fakeMap = Object.create(null);
- for (const module of sortedModules) {
- const exportsType = module.getExportsType(
- moduleGraph,
- this.options.namespaceObject === "strict"
- );
- const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
- switch (exportsType) {
- case "namespace":
- fakeMap[id] = 9;
- hasType |= 1;
- break;
- case "dynamic":
- fakeMap[id] = 7;
- hasType |= 2;
- break;
- case "default-only":
- fakeMap[id] = 1;
- hasType |= 4;
- break;
- case "default-with-named":
- fakeMap[id] = 3;
- hasType |= 8;
- break;
- default:
- throw new Error(`Unexpected exports type ${exportsType}`);
- }
- }
- if (hasType === 1) {
- return 9;
- }
- if (hasType === 2) {
- return 7;
- }
- if (hasType === 4) {
- return 1;
- }
- if (hasType === 8) {
- return 3;
- }
- if (hasType === 0) {
- return 9;
- }
- return fakeMap;
- }
- /**
- * @param {FakeMap | FakeMapType} fakeMap fake map
- * @param {RuntimeTemplate=} runtimeTemplate the runtime template
- * @returns {string} fake map init statement
- */
- getFakeMapInitStatement(fakeMap, runtimeTemplate) {
- const decl = runtimeTemplate ? runtimeTemplate.renderConst() : "var";
- return typeof fakeMap === "object"
- ? `${decl} fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
- : "";
- }
- /**
- * @param {Dependency[]} dependencies all dependencies
- * @param {ChunkGraph} chunkGraph chunk graph
- * @returns {UserRequestsMap} map with user requests
- */
- getModuleDeferredAsyncDepsMap(dependencies, chunkGraph) {
- const moduleGraph = chunkGraph.moduleGraph;
- const comparator = compareModulesById(chunkGraph);
- // if we filter first we get a new array
- // therefore we don't need to create a clone of dependencies explicitly
- // therefore the order of this is !important!
- const sortedModules = dependencies
- .map(
- (dependency) =>
- /** @type {Module} */ (moduleGraph.getModule(dependency))
- )
- .filter(Boolean)
- .sort(comparator);
- /** @type {UserRequestsMap} */
- const map = Object.create(null);
- for (const module of sortedModules) {
- if (!(/** @type {BuildMeta} */ (module.buildMeta).async)) {
- const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
- map[id] = Array.from(
- getOutgoingAsyncModules(chunkGraph.moduleGraph, module),
- (m) => chunkGraph.getModuleId(m)
- ).filter((id) => id !== null);
- }
- }
- return map;
- }
- /**
- * @param {false | UserRequestsMap} asyncDepsMap fake map
- * @param {RuntimeTemplate=} runtimeTemplate the runtime template
- * @returns {string} async deps map init statement
- */
- getModuleDeferredAsyncDepsMapInitStatement(asyncDepsMap, runtimeTemplate) {
- const decl = runtimeTemplate ? runtimeTemplate.renderConst() : "var";
- return typeof asyncDepsMap === "object"
- ? `${decl} asyncDepsMap = ${JSON.stringify(asyncDepsMap, null, "\t")};`
- : "";
- }
- /**
- * @param {FakeMapType} type type
- * @param {boolean=} asyncModule is async module
- * @returns {string} return result
- */
- getReturn(type, asyncModule) {
- if (type === 9) {
- return `${RuntimeGlobals.require}(id)`;
- }
- return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${
- asyncModule ? " | 16" : ""
- })`;
- }
- /**
- * @param {FakeMap | FakeMapType} fakeMap fake map
- * @param {boolean=} asyncModule is async module
- * @param {string=} asyncDeps async deps for deferred module
- * @param {string=} fakeMapDataExpression fake map data expression
- * @returns {string} module object source
- */
- getReturnModuleObjectSource(
- fakeMap,
- asyncModule,
- asyncDeps,
- fakeMapDataExpression = "fakeMap[id]"
- ) {
- const source =
- typeof fakeMap === "number"
- ? this.getReturn(fakeMap, asyncModule)
- : `${RuntimeGlobals.createFakeNamespaceObject}(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`;
- if (asyncDeps) {
- if (!asyncModule) {
- throw new Error("Must be async when module is deferred");
- }
- const type =
- typeof fakeMap === "number" ? fakeMap : fakeMapDataExpression;
- return `${asyncDeps} ? ${asyncDeps}.length ? ${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${asyncDeps}).then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, id, ${type} ^ 1, true)) : ${RuntimeGlobals.makeDeferredNamespaceObject}(id, ${type} ^ 1 | 16) : ${source}`;
- }
- return source;
- }
- /**
- * @param {Dependency[]} dependencies dependencies
- * @param {ModuleId} id module id
- * @param {ChunkGraph} chunkGraph the chunk graph
- * @param {RuntimeTemplate=} runtimeTemplate the runtime template
- * @returns {string} source code
- */
- getSyncSource(dependencies, id, chunkGraph, runtimeTemplate) {
- const map = this.getUserRequestMap(dependencies, chunkGraph);
- const fakeMap = this.getFakeMap(dependencies, chunkGraph);
- const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
- const cst = runtimeTemplate ? runtimeTemplate.renderConst() : "var";
- return `${cst} map = ${JSON.stringify(map, null, "\t")};
- ${this.getFakeMapInitStatement(fakeMap, runtimeTemplate)}
- function webpackContext(req) {
- ${cst} id = webpackContextResolve(req);
- return ${returnModuleObject};
- }
- function webpackContextResolve(req) {
- if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
- ${cst} e = new Error("Cannot find module '" + req + "'");
- e.code = 'MODULE_NOT_FOUND';
- throw e;
- }
- return map[req];
- }
- webpackContext.keys = function webpackContextKeys() {
- return Object.keys(map);
- };
- webpackContext.resolve = webpackContextResolve;
- module.exports = webpackContext;
- webpackContext.id = ${JSON.stringify(id)};`;
- }
- /**
- * @param {Dependency[]} dependencies dependencies
- * @param {ModuleId} id module id
- * @param {ChunkGraph} chunkGraph the chunk graph
- * @param {RuntimeTemplate=} runtimeTemplate the runtime template
- * @returns {string} source code
- */
- getWeakSyncSource(dependencies, id, chunkGraph, runtimeTemplate) {
- const map = this.getUserRequestMap(dependencies, chunkGraph);
- const fakeMap = this.getFakeMap(dependencies, chunkGraph);
- const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
- const cst = runtimeTemplate ? runtimeTemplate.renderConst() : "var";
- return `${cst} map = ${JSON.stringify(map, null, "\t")};
- ${this.getFakeMapInitStatement(fakeMap, runtimeTemplate)}
- function webpackContext(req) {
- ${cst} id = webpackContextResolve(req);
- if(!${RuntimeGlobals.moduleFactories}[id]) {
- ${cst} e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
- e.code = 'MODULE_NOT_FOUND';
- throw e;
- }
- return ${returnModuleObject};
- }
- function webpackContextResolve(req) {
- if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
- ${cst} e = new Error("Cannot find module '" + req + "'");
- e.code = 'MODULE_NOT_FOUND';
- throw e;
- }
- return map[req];
- }
- webpackContext.keys = function webpackContextKeys() {
- return Object.keys(map);
- };
- webpackContext.resolve = webpackContextResolve;
- webpackContext.id = ${JSON.stringify(id)};
- module.exports = webpackContext;`;
- }
- /**
- * @param {Dependency[]} dependencies dependencies
- * @param {ModuleId} id module id
- * @param {ImportPhaseType} phase import phase
- * @param {object} context context
- * @param {ChunkGraph} context.chunkGraph the chunk graph
- * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
- * @returns {string} source code
- */
- getAsyncWeakSource(dependencies, id, phase, { chunkGraph, runtimeTemplate }) {
- const map = this.getUserRequestMap(dependencies, chunkGraph);
- const fakeMap = this.getFakeMap(dependencies, chunkGraph);
- const asyncDepsMap =
- ImportPhaseUtils.isDefer(phase) &&
- this.getModuleDeferredAsyncDepsMap(dependencies, chunkGraph);
- const returnModuleObject = this.getReturnModuleObjectSource(
- fakeMap,
- true,
- asyncDepsMap ? "asyncDepsMap[id]" : undefined
- );
- const cst = runtimeTemplate.renderConst();
- return `${cst} map = ${JSON.stringify(map, null, "\t")};
- ${this.getFakeMapInitStatement(fakeMap, runtimeTemplate)}
- ${this.getModuleDeferredAsyncDepsMapInitStatement(asyncDepsMap, runtimeTemplate)}
- function webpackAsyncContext(req) {
- return webpackAsyncContextResolve(req).then(${runtimeTemplate.basicFunction(
- "id",
- [
- `if(!${RuntimeGlobals.moduleFactories}[id]) {`,
- Template.indent([
- `${cst} e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");`,
- "e.code = 'MODULE_NOT_FOUND';",
- "throw e;"
- ]),
- "}",
- `return ${returnModuleObject};`
- ]
- )});
- }
- function webpackAsyncContextResolve(req) {
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
- // uncaught exception popping up in devtools
- return Promise.resolve().then(${runtimeTemplate.basicFunction("", [
- `if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {`,
- Template.indent([
- `${cst} e = new Error("Cannot find module '" + req + "'");`,
- "e.code = 'MODULE_NOT_FOUND';",
- "throw e;"
- ]),
- "}",
- "return map[req];"
- ])});
- }
- webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
- "Object.keys(map)"
- )};
- webpackAsyncContext.resolve = webpackAsyncContextResolve;
- webpackAsyncContext.id = ${JSON.stringify(id)};
- module.exports = webpackAsyncContext;`;
- }
- /**
- * @param {Dependency[]} dependencies dependencies
- * @param {ModuleId} id module id
- * @param {ImportPhaseType} phase import phase
- * @param {object} context context
- * @param {ChunkGraph} context.chunkGraph the chunk graph
- * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
- * @returns {string} source code
- */
- getEagerSource(dependencies, id, phase, { chunkGraph, runtimeTemplate }) {
- const map = this.getUserRequestMap(dependencies, chunkGraph);
- const fakeMap = this.getFakeMap(dependencies, chunkGraph);
- const asyncDepsMap =
- ImportPhaseUtils.isDefer(phase) &&
- this.getModuleDeferredAsyncDepsMap(dependencies, chunkGraph);
- const thenFunction = runtimeTemplate.returningFunction(
- this.getReturnModuleObjectSource(
- fakeMap,
- true,
- asyncDepsMap ? "asyncDepsMap[id]" : undefined
- ),
- "id"
- );
- const cst = runtimeTemplate.renderConst();
- return `${cst} map = ${JSON.stringify(map, null, "\t")};
- ${this.getFakeMapInitStatement(fakeMap, runtimeTemplate)}
- ${this.getModuleDeferredAsyncDepsMapInitStatement(asyncDepsMap, runtimeTemplate)}
- function webpackAsyncContext(req) {
- return webpackAsyncContextResolve(req).then(${thenFunction});
- }
- function webpackAsyncContextResolve(req) {
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
- // uncaught exception popping up in devtools
- return Promise.resolve().then(${runtimeTemplate.basicFunction("", [
- `if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {`,
- Template.indent([
- `${cst} e = new Error("Cannot find module '" + req + "'");`,
- "e.code = 'MODULE_NOT_FOUND';",
- "throw e;"
- ]),
- "}",
- "return map[req];"
- ])});
- }
- webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
- "Object.keys(map)"
- )};
- webpackAsyncContext.resolve = webpackAsyncContextResolve;
- webpackAsyncContext.id = ${JSON.stringify(id)};
- module.exports = webpackAsyncContext;`;
- }
- /**
- * @param {AsyncDependenciesBlock} block block
- * @param {Dependency[]} dependencies dependencies
- * @param {ModuleId} id module id
- * @param {ImportPhaseType} phase import phase
- * @param {object} options options object
- * @param {RuntimeTemplate} options.runtimeTemplate the runtime template
- * @param {ChunkGraph} options.chunkGraph the chunk graph
- * @param {RuntimeRequirements} options.runtimeRequirements runtime requirements
- * @returns {string} source code
- */
- getLazyOnceSource(
- block,
- dependencies,
- id,
- phase,
- { runtimeTemplate, chunkGraph, runtimeRequirements }
- ) {
- const promise = runtimeTemplate.blockPromise({
- chunkGraph,
- block,
- message: "lazy-once context",
- runtimeRequirements,
- originModule: this
- });
- const map = this.getUserRequestMap(dependencies, chunkGraph);
- const fakeMap = this.getFakeMap(dependencies, chunkGraph);
- const asyncDepsMap =
- ImportPhaseUtils.isDefer(phase) &&
- this.getModuleDeferredAsyncDepsMap(dependencies, chunkGraph);
- const thenFunction = runtimeTemplate.returningFunction(
- this.getReturnModuleObjectSource(
- fakeMap,
- true,
- asyncDepsMap ? "asyncDepsMap[id]" : undefined
- ),
- "id"
- );
- const cst = runtimeTemplate.renderConst();
- return `${cst} map = ${JSON.stringify(map, null, "\t")};
- ${this.getFakeMapInitStatement(fakeMap, runtimeTemplate)}
- ${this.getModuleDeferredAsyncDepsMapInitStatement(asyncDepsMap, runtimeTemplate)}
- function webpackAsyncContext(req) {
- return webpackAsyncContextResolve(req).then(${thenFunction});
- }
- function webpackAsyncContextResolve(req) {
- return ${promise}.then(${runtimeTemplate.basicFunction("", [
- `if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {`,
- Template.indent([
- `${cst} e = new Error("Cannot find module '" + req + "'");`,
- "e.code = 'MODULE_NOT_FOUND';",
- "throw e;"
- ]),
- "}",
- "return map[req];"
- ])});
- }
- webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
- "Object.keys(map)"
- )};
- webpackAsyncContext.resolve = webpackAsyncContextResolve;
- webpackAsyncContext.id = ${JSON.stringify(id)};
- module.exports = webpackAsyncContext;`;
- }
- /**
- * @param {AsyncDependenciesBlock[]} blocks blocks
- * @param {ModuleId} id module id
- * @param {ImportPhaseType} phase import phase
- * @param {object} context context
- * @param {ChunkGraph} context.chunkGraph the chunk graph
- * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
- * @param {RuntimeRequirements} context.runtimeRequirements runtime requirements
- * @returns {string} source code
- */
- getLazySource(
- blocks,
- id,
- phase,
- { chunkGraph, runtimeTemplate, runtimeRequirements }
- ) {
- const moduleGraph = chunkGraph.moduleGraph;
- let hasMultipleOrNoChunks = false;
- let hasNoChunk = true;
- let hasNoModuleDeferred = true;
- const fakeMap = this.getFakeMap(
- blocks.map((b) => b.dependencies[0]),
- chunkGraph
- );
- const hasFakeMap = typeof fakeMap === "object";
- /** @typedef {{ userRequest: string, dependency: ContextElementDependency, chunks: undefined | Chunk[], module: Module, block: AsyncDependenciesBlock, asyncDeps: undefined | ModuleId[] }} Item */
- /**
- * @type {Item[]}
- */
- const items = blocks
- .map((block) => {
- const dependency =
- /** @type {ContextElementDependency} */
- (block.dependencies[0]);
- return {
- dependency,
- module: /** @type {Module} */ (moduleGraph.getModule(dependency)),
- block,
- userRequest: dependency.userRequest,
- chunks: undefined,
- asyncDeps: undefined
- };
- })
- .filter((item) => item.module);
- for (const item of items) {
- const chunkGroup = chunkGraph.getBlockChunkGroup(item.block);
- const chunks = (chunkGroup && chunkGroup.chunks) || [];
- item.chunks = chunks;
- if (chunks.length > 0) {
- hasNoChunk = false;
- }
- if (chunks.length !== 1) {
- hasMultipleOrNoChunks = true;
- }
- const isModuleDeferred =
- ImportPhaseUtils.isDefer(phase) &&
- !(/** @type {BuildMeta} */ (item.module.buildMeta).async);
- if (isModuleDeferred) {
- const asyncDeps = Array.from(
- getOutgoingAsyncModules(chunkGraph.moduleGraph, item.module),
- (m) => chunkGraph.getModuleId(m)
- ).filter((id) => id !== null);
- item.asyncDeps = asyncDeps;
- hasNoModuleDeferred = false;
- }
- }
- const shortMode = hasNoChunk && hasNoModuleDeferred && !hasFakeMap;
- // Sorted before anything is keyed by request, so two items sharing one leave the
- // same last writer in the map and in the loaders beside it.
- const sortedItems = items.sort((a, b) => {
- if (a.userRequest === b.userRequest) return 0;
- return a.userRequest < b.userRequest ? -1 : 1;
- });
- let needEnsureChunk = !hasNoChunk;
- /** @type {Map<string, string[]> | undefined} */
- let loaders;
- // Only module output can name a chunk in an `import()`, so nothing else pays for
- // building the loaders just to throw them away.
- if (!hasNoChunk && runtimeTemplate.isModule()) {
- /** @type {Map<string, string[]>} */
- const perRequest = new Map();
- let hasAnalyzable = false;
- let hasFallback = false;
- /**
- * @param {Chunk} chunk one chunk a request needs
- * @returns {string} a thunk loading it, by literal name where the chunk has one
- */
- const loaderFor = (chunk) => {
- // `.ei` always imports, where `.e` skips a chunk already loaded — the same
- // filter `blockPromise` applies before reaching for it.
- const analyzable =
- chunk.hasRuntime() || chunk.id === null
- ? null
- : runtimeTemplate.analyzableChunkImport(
- chunk,
- "",
- runtimeRequirements,
- this,
- chunkGraph
- );
- if (analyzable !== null) {
- hasAnalyzable = true;
- return runtimeTemplate.returningFunction(analyzable);
- }
- hasFallback = true;
- return runtimeTemplate.returningFunction(
- `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)})`
- );
- };
- for (const item of sortedItems) {
- perRequest.set(
- item.userRequest,
- /** @type {Chunk[]} */ (item.chunks).map(loaderFor)
- );
- }
- // Nothing gained when no chunk can be spelled out, and the plain id map is
- // smaller, so the loaders are only written when at least one names its chunk.
- if (hasAnalyzable) {
- loaders = perRequest;
- needEnsureChunk = hasFallback;
- }
- }
- /** @type {Record<string, ModuleId | (ModuleId | FakeMapType | ChunkId[] | (ModuleId[] | undefined))[]>} */
- const map = Object.create(null);
- for (const item of sortedItems) {
- const moduleId =
- /** @type {ModuleId} */
- (chunkGraph.getModuleId(item.module));
- if (shortMode) {
- map[item.userRequest] = moduleId;
- } else {
- /** @type {(ModuleId | FakeMapType | ChunkId[] | (ModuleId[] | undefined))[]} */
- const array = [moduleId];
- if (hasFakeMap) {
- array.push(fakeMap[moduleId]);
- }
- if (!hasNoChunk) {
- array.push(
- /** @type {Chunk[]} */ (item.chunks).map(
- (chunk) => /** @type {ChunkId} */ (chunk.id)
- )
- );
- }
- if (!hasNoModuleDeferred) {
- array.push(item.asyncDeps);
- }
- map[item.userRequest] = array;
- }
- }
- const chunksPosition = hasFakeMap ? 2 : 1;
- // No chunks slot is pushed when `hasNoChunk`, so `asyncDeps` sits at `chunksPosition`.
- const asyncDepsPosition = hasNoChunk ? chunksPosition : chunksPosition + 1;
- const requestPrefix = hasNoChunk
- ? "Promise.resolve()"
- : loaders !== undefined
- ? hasMultipleOrNoChunks
- ? `Promise.all(ids[${chunksPosition}].map(${runtimeTemplate.returningFunction("load()", "load")}))`
- : `ids[${chunksPosition}][0]()`
- : hasMultipleOrNoChunks
- ? `Promise.all(ids[${chunksPosition}].map(${RuntimeGlobals.ensureChunk}))`
- : `${RuntimeGlobals.ensureChunk}(ids[${chunksPosition}][0])`;
- // Only the id map reads it; nothing loads a chunk when there is none to load, and
- // a map of loaders spells out every one it could reach for.
- if (needEnsureChunk) {
- runtimeRequirements.add(RuntimeGlobals.ensureChunk);
- }
- const returnModuleObject = this.getReturnModuleObjectSource(
- fakeMap,
- true,
- hasNoModuleDeferred ? undefined : `ids[${asyncDepsPosition}]`,
- shortMode ? "invalid" : "ids[1]"
- );
- const cst = runtimeTemplate.renderConst();
- const webpackAsyncContext =
- requestPrefix === "Promise.resolve()"
- ? `
- function webpackAsyncContext(req) {
- return Promise.resolve().then(${runtimeTemplate.basicFunction("", [
- `if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {`,
- Template.indent([
- `${cst} e = new Error("Cannot find module '" + req + "'");`,
- "e.code = 'MODULE_NOT_FOUND';",
- "throw e;"
- ]),
- "}",
- shortMode ? `${cst} id = map[req];` : `${cst} ids = map[req], id = ids[0];`,
- `return ${returnModuleObject};`
- ])});
- }`
- : `function webpackAsyncContext(req) {
- try {
- if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
- return Promise.resolve().then(${runtimeTemplate.basicFunction("", [
- `${cst} e = new Error("Cannot find module '" + req + "'");`,
- "e.code = 'MODULE_NOT_FOUND';",
- "throw e;"
- ])});
- }
- } catch(err) {
- return Promise.reject(err);
- }
- ${cst} ids = map[req], id = ids[0];
- return ${requestPrefix}.then(${runtimeTemplate.returningFunction(returnModuleObject)});
- }`;
- // A loader is source, not data, so the map holding one is written out rather than
- // serialized — one entry per line, keeping the request next to what loads it.
- const mapSource =
- loaders === undefined
- ? JSON.stringify(map, null, "\t")
- : `{\n${Object.keys(map)
- .map((request) => {
- const slots =
- /** @type {(ModuleId | FakeMapType | ChunkId[] | (ModuleId[] | undefined))[]} */
- (map[request]).map((slot, index) =>
- index === chunksPosition
- ? `[${/** @type {string[]} */ (loaders.get(request)).join(", ")}]`
- : // An absent `asyncDeps` slot is `null` to `JSON.stringify`.
- slot === undefined
- ? "null"
- : JSON.stringify(slot)
- );
- return `\t${JSON.stringify(request)}: [${slots.join(", ")}]`;
- })
- .join(",\n")}\n}`;
- return `${cst} map = ${mapSource};
- ${webpackAsyncContext}
- webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
- "Object.keys(map)"
- )};
- webpackAsyncContext.id = ${JSON.stringify(id)};
- module.exports = webpackAsyncContext;`;
- }
- /**
- * @param {ModuleId} id module id
- * @param {RuntimeTemplate} runtimeTemplate runtime template
- * @returns {string} source for empty async context
- */
- getSourceForEmptyContext(id, runtimeTemplate) {
- return `function webpackEmptyContext(req) {
- ${runtimeTemplate.renderConst()} e = new Error("Cannot find module '" + req + "'");
- e.code = 'MODULE_NOT_FOUND';
- throw e;
- }
- webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")};
- webpackEmptyContext.resolve = webpackEmptyContext;
- webpackEmptyContext.id = ${JSON.stringify(id)};
- module.exports = webpackEmptyContext;`;
- }
- /**
- * @param {ModuleId} id module id
- * @param {RuntimeTemplate} runtimeTemplate runtime template
- * @returns {string} source for empty async context
- */
- getSourceForEmptyAsyncContext(id, runtimeTemplate) {
- return `function webpackEmptyAsyncContext(req) {
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
- // uncaught exception popping up in devtools
- return Promise.resolve().then(${runtimeTemplate.basicFunction("", [
- `${runtimeTemplate.renderConst()} e = new Error("Cannot find module '" + req + "'");`,
- "e.code = 'MODULE_NOT_FOUND';",
- "throw e;"
- ])});
- }
- webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")};
- webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
- webpackEmptyAsyncContext.id = ${JSON.stringify(id)};
- module.exports = webpackEmptyAsyncContext;`;
- }
- /**
- * @returns {string | undefined} import property access
- */
- getImportPropertyAccess() {
- const importName = this.options.importName;
- if (!importName || importName === "*") return;
- return propertyAccess([importName]);
- }
- /**
- * @param {number} index index
- * @param {string} userRequest user request
- * @param {string} value value expression
- * @param {string[]} entries entries
- * @returns {void}
- */
- appendGlobMapEntry(index, userRequest, value, entries) {
- entries.push(`\n ${JSON.stringify(userRequest)}: ${value}`);
- }
- /**
- * @param {string} entries entries
- * @returns {string} object export source
- */
- getGlobObjectExportSource(entries) {
- return `\nmodule.exports = {${entries}\n};\n`;
- }
- /**
- * @returns {string} empty object export source
- */
- getEmptyObjectExportSource() {
- return "\nmodule.exports = {};\n";
- }
- /**
- * @param {AsyncDependenciesBlock[]} blocks blocks
- * @param {ImportPhaseType} phase import phase
- * @param {object} context context
- * @param {RuntimeTemplate} context.runtimeTemplate runtime template
- * @param {ChunkGraph} context.chunkGraph chunk graph
- * @param {RuntimeRequirements=} context.runtimeRequirements runtime requirements
- * @returns {string} glob lazy source
- */
- getGlobLazySource(
- blocks,
- phase,
- { runtimeTemplate, chunkGraph, runtimeRequirements }
- ) {
- if (!blocks || blocks.length === 0) {
- return this.getEmptyObjectExportSource();
- }
- const moduleGraph = chunkGraph.moduleGraph;
- const globImportAccess = this.getImportPropertyAccess();
- /** @type {RuntimeRequirements} */
- const localRuntimeRequirements = runtimeRequirements || new Set();
- /** @type {{ userRequest: string, block: AsyncDependenciesBlock, dependency: ContextElementDependency }[]} */
- const blockInfo = blocks
- .map((block) => {
- const dependency =
- /** @type {ContextElementDependency} */
- (block.dependencies[0]);
- return {
- userRequest: dependency.userRequest,
- block,
- dependency
- };
- })
- .sort((a, b) =>
- a.userRequest < b.userRequest
- ? -1
- : a.userRequest > b.userRequest
- ? 1
- : 0
- );
- /** @type {string[]} */
- const entries = [];
- for (let i = 0; i < blockInfo.length; i++) {
- const info = blockInfo[i];
- let importPromise = runtimeTemplate.moduleNamespacePromise({
- chunkGraph,
- block: info.block,
- module: /** @type {Module} */ (moduleGraph.getModule(info.dependency)),
- request: info.userRequest,
- message: "import.meta.glob",
- strict: this.options.namespaceObject === "strict",
- dependency: info.dependency,
- runtimeRequirements: localRuntimeRequirements,
- originModule: this
- });
- if (globImportAccess) {
- importPromise = `${importPromise}.then(function(m) { return m${globImportAccess}; })`;
- }
- this.appendGlobMapEntry(
- i,
- info.userRequest,
- `function() { return ${importPromise}; }`,
- entries
- );
- }
- return this.getGlobObjectExportSource(entries.join(","));
- }
- /**
- * @param {Dependency[]} dependencies dependencies
- * @param {ChunkGraph} chunkGraph chunk graph
- * @param {RuntimeTemplate} runtimeTemplate runtime template
- * @returns {string} glob sync source
- */
- getGlobSyncSource(dependencies, chunkGraph, runtimeTemplate) {
- if (!dependencies || dependencies.length === 0) {
- return this.getEmptyObjectExportSource();
- }
- const moduleGraph = chunkGraph.moduleGraph;
- const fakeMap = this.getFakeMap(dependencies, chunkGraph);
- const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
- const globImportAccess = this.getImportPropertyAccess();
- const sortedDependencies =
- /** @type {import("./dependencies/ContextElementDependency")[]} */
- (dependencies).sort((a, b) =>
- a.userRequest < b.userRequest
- ? -1
- : a.userRequest > b.userRequest
- ? 1
- : 0
- );
- /** @type {string[]} */
- const entries = [];
- let index = 0;
- for (const dep of sortedDependencies) {
- const module = moduleGraph.getModule(dep);
- let moduleExpr;
- if (module) {
- const moduleId = chunkGraph.getModuleId(module);
- moduleExpr = `(function() { var id = ${JSON.stringify(moduleId)}; return ${returnModuleObject}; })()`;
- if (globImportAccess) {
- moduleExpr += globImportAccess;
- }
- } else {
- moduleExpr = `undefined /* ${JSON.stringify(dep.userRequest)} */`;
- }
- this.appendGlobMapEntry(index++, dep.userRequest, moduleExpr, entries);
- }
- const fakeMapInit = this.getFakeMapInitStatement(fakeMap, runtimeTemplate);
- return `${fakeMapInit}\n${this.getGlobObjectExportSource(entries.join(","))}`;
- }
- /**
- * @param {string} asyncMode module mode
- * @param {ImportPhaseType} phase import phase
- * @param {CodeGenerationContext} context context info
- * @returns {string} the source code
- */
- getGlobSourceString(asyncMode, phase, context) {
- if (asyncMode === "lazy") {
- if (this.blocks && this.blocks.length > 0) {
- return this.getGlobLazySource(this.blocks, phase, context);
- }
- return this.getEmptyObjectExportSource();
- }
- if (this.dependencies && this.dependencies.length > 0) {
- return this.getGlobSyncSource(
- this.dependencies,
- context.chunkGraph,
- context.runtimeTemplate
- );
- }
- return this.getEmptyObjectExportSource();
- }
- /**
- * @param {string} asyncMode module mode
- * @param {ImportPhaseType} phase import phase
- * @param {CodeGenerationContext & { runtimeRequirements: RuntimeRequirements }} context context info
- * @returns {string} the source code
- */
- getSourceString(asyncMode, phase, context) {
- if (this.options.patterns) {
- return this.getGlobSourceString(asyncMode, phase, context);
- }
- return this.getContextSourceString(asyncMode, phase, context);
- }
- /**
- * @param {string} asyncMode module mode
- * @param {ImportPhaseType} phase import phase
- * @param {CodeGenerationContext & { runtimeRequirements: RuntimeRequirements }} context context info
- * @returns {string} the source code
- */
- getContextSourceString(asyncMode, phase, context) {
- const { runtimeTemplate, chunkGraph, runtimeRequirements } = context;
- const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this));
- if (asyncMode === "lazy") {
- if (this.blocks && this.blocks.length > 0) {
- return this.getLazySource(this.blocks, id, phase, {
- runtimeTemplate,
- chunkGraph,
- runtimeRequirements
- });
- }
- return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
- }
- if (asyncMode === "eager") {
- if (this.dependencies && this.dependencies.length > 0) {
- return this.getEagerSource(this.dependencies, id, phase, {
- chunkGraph,
- runtimeTemplate
- });
- }
- return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
- }
- if (asyncMode === "lazy-once") {
- const block = this.blocks[0];
- if (block) {
- return this.getLazyOnceSource(block, block.dependencies, id, phase, {
- runtimeTemplate,
- chunkGraph,
- runtimeRequirements
- });
- }
- return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
- }
- if (asyncMode === "async-weak") {
- if (this.dependencies && this.dependencies.length > 0) {
- return this.getAsyncWeakSource(this.dependencies, id, phase, {
- chunkGraph,
- runtimeTemplate
- });
- }
- return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
- }
- if (
- asyncMode === "weak" &&
- this.dependencies &&
- this.dependencies.length > 0
- ) {
- return this.getWeakSyncSource(
- this.dependencies,
- id,
- chunkGraph,
- runtimeTemplate
- );
- }
- if (this.dependencies && this.dependencies.length > 0) {
- return this.getSyncSource(
- this.dependencies,
- id,
- chunkGraph,
- runtimeTemplate
- );
- }
- return this.getSourceForEmptyContext(id, runtimeTemplate);
- }
- /**
- * @param {string} sourceString source content
- * @param {Compilation=} compilation the compilation
- * @returns {Source} generated source
- */
- getSource(sourceString, compilation) {
- if (this.useSourceMap || this.useSimpleSourceMap) {
- return new OriginalSource(
- sourceString,
- `webpack://${makePathsRelative(
- (compilation && compilation.compiler.context) || "",
- this.identifier(),
- compilation && compilation.compiler.root
- )}`
- );
- }
- return new RawSource(sourceString);
- }
- /**
- * Generates code and runtime requirements for this module.
- * @param {CodeGenerationContext} context context for code generation
- * @returns {CodeGenerationResult} result
- */
- codeGeneration(context) {
- const { chunkGraph, compilation } = context;
- /** @type {RuntimeRequirements} */
- const set = new Set();
- /** @type {Sources} */
- const sources = new Map();
- sources.set(
- JAVASCRIPT_TYPE,
- this.getSource(
- this.getSourceString(
- this.options.mode,
- this.options.phase || ImportPhase.Evaluation,
- { ...context, runtimeRequirements: set }
- ),
- compilation
- )
- );
- const allDeps =
- this.dependencies.length > 0
- ? /** @type {ContextElementDependency[]} */ [...this.dependencies]
- : [];
- for (const block of this.blocks) {
- for (const dep of block.dependencies) {
- allDeps.push(/** @type {ContextElementDependency} */ (dep));
- }
- }
- set.add(RuntimeGlobals.module);
- set.add(RuntimeGlobals.hasOwnProperty);
- if (allDeps.length > 0) {
- const asyncMode = this.options.mode;
- set.add(RuntimeGlobals.require);
- // `ensureChunk` is not listed per mode: the source generators above add it
- // where they emit a call, so a baked context or one with no chunk drops it.
- if (asyncMode === "weak" || asyncMode === "async-weak") {
- set.add(RuntimeGlobals.moduleFactories);
- }
- if (this.getFakeMap(allDeps, chunkGraph) !== 9) {
- set.add(RuntimeGlobals.createFakeNamespaceObject);
- }
- if (
- ImportPhaseUtils.isDefer(this.options.phase || ImportPhase.Evaluation)
- ) {
- set.add(RuntimeGlobals.makeDeferredNamespaceObject);
- }
- }
- return {
- sources,
- runtimeRequirements: set
- };
- }
- /**
- * 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) {
- // base penalty
- let size = 160;
- // if we don't have dependencies we stop here.
- for (const dependency of this.dependencies) {
- const element = /** @type {ContextElementDependency} */ (dependency);
- size += 5 + element.userRequest.length;
- }
- return size;
- }
- /**
- * Serializes this instance into the provided serializer context.
- * @param {ObjectSerializerContext} context context
- */
- serialize(context) {
- context.write(this._identifier).write(this._forceBuild);
- super.serialize(context);
- }
- /**
- * Restores this instance from the provided deserializer context.
- * @param {ObjectDeserializerContext} context context
- */
- deserialize(context) {
- this._identifier = context.read();
- const c1 = context.rest;
- this._forceBuild = c1.read();
- super.deserialize(c1.rest);
- }
- }
- makeSerializable(ContextModule, "webpack/lib/ContextModule");
- module.exports = ContextModule;
|