ConcatenatedModule.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { SyncBailHook } = require("tapable");
  7. const {
  8. CachedSource,
  9. ConcatSource,
  10. ReplaceSource
  11. } = require("webpack-sources");
  12. const ConcatenationScope = require("../ConcatenationScope");
  13. const Dependency = require("../Dependency");
  14. const { UsageState } = require("../ExportsInfo");
  15. const ExternalModule = require("../ExternalModule");
  16. const Module = require("../Module");
  17. const {
  18. JAVASCRIPT_TYPE,
  19. JAVASCRIPT_TYPES
  20. } = require("../ModuleSourceTypeConstants");
  21. const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants");
  22. const NormalModule = require("../NormalModule");
  23. const RuntimeGlobals = require("../RuntimeGlobals");
  24. const Template = require("../Template");
  25. const { DEFAULTS } = require("../config/defaults");
  26. const CommonJsExportRequireDependency = require("../dependencies/CommonJsExportRequireDependency");
  27. const CommonJsFullRequireDependency = require("../dependencies/CommonJsFullRequireDependency");
  28. const CommonJsRequireDependency = require("../dependencies/CommonJsRequireDependency");
  29. const { ImportPhaseUtils } = require("../dependencies/ImportPhase");
  30. const JavascriptParser = require("../javascript/JavascriptParser");
  31. const analyzeScope = require("../javascript/ScopeAnalyzer");
  32. const {
  33. getDeferredCycleModuleIds,
  34. getDeferredCycleModules,
  35. getMakeDeferredNamespaceModeFromExportsType,
  36. getOptimizedDeferredModule
  37. } = require("../runtime/MakeDeferredNamespaceObjectRuntime");
  38. const { equals } = require("../util/ArrayHelpers");
  39. const LazySet = require("../util/LazySet");
  40. const {
  41. compareModulesByFullName,
  42. concatComparators
  43. } = require("../util/comparators");
  44. const {
  45. RESERVED_NAMES,
  46. addScopeSymbols,
  47. findNewName,
  48. getAllReferences,
  49. getPathInAst,
  50. getUsedNamesInScopeInfo,
  51. isCommonJsConcatenationEnabled
  52. } = require("../util/concatenate");
  53. const createHash = require("../util/createHash");
  54. const createHooksRegistry = require("../util/createHooksRegistry");
  55. const { makePathsRelative } = require("../util/identifier");
  56. const makeSerializable = require("../util/makeSerializable");
  57. const { propertyAccess, propertyName } = require("../util/property");
  58. const {
  59. filterRuntime,
  60. intersectRuntime,
  61. mergeRuntimeCondition,
  62. mergeRuntimeConditionNonFalse,
  63. runtimeConditionToString,
  64. subtractRuntimeCondition
  65. } = require("../util/runtime");
  66. const { InlinedUsedName } = require("./InlineExports");
  67. /** @import { Source } from "webpack-sources" */
  68. /**
  69. * @import {
  70. * WebpackOptionsNormalizedWithDefaults as WebpackOptions
  71. * } from "../config/defaults"
  72. */
  73. /** @import ChunkGraph from "../ChunkGraph" */
  74. /** @import CodeGenerationResults from "../CodeGenerationResults" */
  75. /** @import Compilation, { FileSystemDependencies } from "../Compilation" */
  76. /** @import { UpdateHashContext } from "../Dependency" */
  77. /** @import HarmonyImportDependency from "../dependencies/HarmonyImportDependency" */
  78. /** @import DependencyTemplates from "../DependencyTemplates" */
  79. /** @import { ExportInfo } from "../ExportsInfo" */
  80. /**
  81. * @import {
  82. * BuildCallback,
  83. * BuildInfo,
  84. * BuildMeta,
  85. * ExportsType,
  86. * CodeGenerationContext,
  87. * CodeGenerationResultData,
  88. * CodeGenerationResult,
  89. * LibIdentOptions,
  90. * LibIdent,
  91. * NameForCondition,
  92. * ReadOnlyRuntimeRequirements,
  93. * RuntimeRequirements,
  94. * SourceTypes
  95. * } from "../Module"
  96. */
  97. /** @import ModuleGraph from "../ModuleGraph" */
  98. /**
  99. * @import ModuleGraphConnection, {
  100. * ConnectionState
  101. * } from "../ModuleGraphConnection"
  102. */
  103. /** @import RequestShortener from "../RequestShortener" */
  104. /** @import { ResolverWithOptions } from "../ResolverFactory" */
  105. /** @import RuntimeTemplate from "../RuntimeTemplate" */
  106. /**
  107. * @import {
  108. * JavascriptModuleBuildInfo,
  109. * JavascriptModuleBuildMeta
  110. * } from "../javascript/JavascriptModule"
  111. */
  112. /**
  113. * @import {
  114. * ChunkRenderContext,
  115. * Scope,
  116. * Reference,
  117. * Variable
  118. * } from "../javascript/JavascriptModulesPlugin"
  119. */
  120. /** @import { Range } from "../javascript/JavascriptParser" */
  121. /** @import { Identifier, Program } from "estree" */
  122. /**
  123. * @import {
  124. * ObjectDeserializerContext
  125. * } from "../serialization/ObjectMiddleware"
  126. */
  127. /** @import Hash, { HashFunction } from "../util/Hash" */
  128. /** @import { UsedNames, UsedNamesInScopeInfo } from "../util/concatenate" */
  129. /** @import { InputFileSystem } from "../util/fs" */
  130. /** @import { AssociatedObjectForCache } from "../util/identifier" */
  131. /** @import { RuntimeSpec } from "../util/runtime" */
  132. /**
  133. * @template T
  134. * @typedef {import("../InitFragment")<T>} InitFragment
  135. */
  136. /**
  137. * @template T
  138. * @typedef {import("../util/comparators").Comparator<T>} Comparator
  139. */
  140. const IDENTIFIER_SCAN_REGEXP = /[$A-Za-z_][\w$]*/g;
  141. const IDENTIFIER_SCAN_WHITESPACE = new Set([" ", "\t", "\n", "\r"]);
  142. /**
  143. * Finds every identifier a generated source could resolve against the enclosing
  144. * concatenation scope. Property names are skipped; string and comment contents
  145. * are not, which only over-reserves.
  146. * @param {Source} source generated source
  147. * @returns {ReadonlySet<string>} identifier names
  148. */
  149. const findIdentifiers = (source) => {
  150. const code = source.source().toString();
  151. /** @type {Set<string>} */
  152. const result = new Set();
  153. IDENTIFIER_SCAN_REGEXP.lastIndex = 0;
  154. let match = IDENTIFIER_SCAN_REGEXP.exec(code);
  155. while (match !== null) {
  156. let i = match.index - 1;
  157. while (i >= 0 && IDENTIFIER_SCAN_WHITESPACE.has(code[i])) i--;
  158. // `a.b` can't bind to the outer scope, but the `b` of `...b` can
  159. if (!(i >= 0 && code[i] === "." && code[i - 1] !== ".")) {
  160. result.add(match[0]);
  161. }
  162. match = IDENTIFIER_SCAN_REGEXP.exec(code);
  163. }
  164. return result;
  165. };
  166. /** @typedef {RawBinding | SymbolBinding} Binding */
  167. /** @typedef {string[]} ExportName */
  168. /**
  169. * @typedef {object} RawBinding
  170. * @property {ModuleInfo} info
  171. * @property {string} rawName
  172. * @property {string=} comment
  173. * @property {ExportName} ids
  174. * @property {ExportName} exportName
  175. */
  176. /**
  177. * @typedef {object} SymbolBinding
  178. * @property {ConcatenatedModuleInfo} info
  179. * @property {string} name
  180. * @property {string=} comment
  181. * @property {ExportName} ids
  182. * @property {ExportName} exportName
  183. */
  184. /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */
  185. /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo} ModuleInfoOrReference */
  186. /** @typedef {Map<string, string>} ExportMap */
  187. /**
  188. * @typedef {object} ConcatenatedModuleInfo
  189. * @property {"concatenated"} type
  190. * @property {boolean} wrapped the body renders inside the lazy CJS wrapper with real module/exports instead of being scope-hoisted into the shared scope
  191. * @property {boolean} eager a wrapped body reached by an eager import edge, so its accessor is called at its own slot in evaluation order
  192. * @property {Module} module
  193. * @property {number} index
  194. * @property {Program | undefined} ast
  195. * @property {Source | undefined} internalSource
  196. * @property {ReplaceSource | undefined} source
  197. * @property {InitFragment<ChunkRenderContext>[]=} chunkInitFragments
  198. * @property {ReadOnlyRuntimeRequirements | undefined} runtimeRequirements
  199. * @property {Scope | undefined} globalScope
  200. * @property {Reference[] | undefined} unresolvedReferences the module's free references
  201. * @property {Scope | undefined} moduleScope
  202. * @property {Map<string, string>} internalNames
  203. * @property {ExportMap | undefined} exportMap
  204. * @property {ExportMap | undefined} rawExportMap
  205. * @property {string=} namespaceExportSymbol
  206. * @property {string | undefined} namespaceFnName name of the lazy wrapper accessor function (calling it evaluates the module and returns its exports)
  207. * @property {string | undefined} namespaceObjectName
  208. * @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
  209. * @property {ConcatenationScope | undefined} concatenationScope
  210. * @property {boolean} interopNamespaceObjectUsed "default-with-named" namespace
  211. * @property {string | undefined} interopNamespaceObjectName "default-with-named" namespace
  212. * @property {boolean} interopNamespaceObject2Used "default-only" namespace
  213. * @property {string | undefined} interopNamespaceObject2Name "default-only" namespace
  214. * @property {boolean} interopDefaultAccessUsed runtime namespace object that detects "__esModule"
  215. * @property {string | undefined} interopDefaultAccessName runtime namespace object that detects "__esModule"
  216. * @property {ExportsType=} exportsTypeStrict memoized getExportsType(strict=true)
  217. * @property {ExportsType=} exportsTypeNonStrict memoized getExportsType(strict=false)
  218. */
  219. /**
  220. * @typedef {object} ExternalModuleInfo
  221. * @property {"external"} type
  222. * @property {boolean} wrapped the module's `require()` call is deferred behind an accessor instead of running at its own slot; unlike a wrapped concatenated member there is no body and no CJS wrapper, so any external may be wrapped
  223. * @property {boolean} eager a wrapped module reached by an eager import edge, so its accessor is called at its own slot in evaluation order
  224. * @property {Module} module
  225. * @property {RuntimeSpec | boolean} runtimeCondition
  226. * @property {NonDeferAccess} nonDeferAccess
  227. * @property {number} index
  228. * @property {string | undefined} name module.exports / harmony namespace object
  229. * @property {string | undefined} namespaceFnName lazy module accessor
  230. * @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
  231. * @property {string | undefined} deferredName deferred module.exports / harmony namespace object
  232. * @property {boolean} deferred the module is deferred at least once
  233. * @property {boolean} deferredNamespaceObjectUsed deferred namespace object that being used in a not-analyzable way so it must be materialized
  234. * @property {string | undefined} deferredNamespaceObjectName deferred namespace object that being used in a not-analyzable way so it must be materialized
  235. * @property {boolean} interopNamespaceObjectUsed "default-with-named" namespace
  236. * @property {string | undefined} interopNamespaceObjectName "default-with-named" namespace
  237. * @property {boolean} interopNamespaceObject2Used "default-only" namespace
  238. * @property {string | undefined} interopNamespaceObject2Name "default-only" namespace
  239. * @property {boolean} interopDefaultAccessUsed runtime namespace object that detects "__esModule"
  240. * @property {string | undefined} interopDefaultAccessName runtime namespace object that detects "__esModule"
  241. * @property {ExportsType=} exportsTypeStrict memoized getExportsType(strict=true)
  242. * @property {ExportsType=} exportsTypeNonStrict memoized getExportsType(strict=false)
  243. */
  244. /**
  245. * @typedef {object} ReferenceToModuleInfo
  246. * @property {"reference"} type
  247. * @property {RuntimeSpec | boolean} runtimeCondition
  248. * @property {NonDeferAccess} nonDeferAccess
  249. * @property {ModuleInfo} target
  250. */
  251. /**
  252. * @template T
  253. * @param {string} property property
  254. * @param {(a: T[keyof T], b: T[keyof T]) => 0 | 1 | -1} comparator comparator
  255. * @returns {Comparator<T>} comparator
  256. */
  257. const createComparator = (property, comparator) => (a, b) =>
  258. comparator(
  259. a[/** @type {keyof T} */ (property)],
  260. b[/** @type {keyof T} */ (property)]
  261. );
  262. /**
  263. * @param {number} a a
  264. * @param {number} b b
  265. * @returns {0 | 1 | -1} result
  266. */
  267. const compareNumbers = (a, b) => {
  268. if (Number.isNaN(a)) {
  269. if (!Number.isNaN(b)) {
  270. return 1;
  271. }
  272. } else {
  273. if (Number.isNaN(b)) {
  274. return -1;
  275. }
  276. if (a !== b) {
  277. return a < b ? -1 : 1;
  278. }
  279. }
  280. return 0;
  281. };
  282. const bySourceOrder = createComparator("sourceOrder", compareNumbers);
  283. const byRangeStart = createComparator("rangeStart", compareNumbers);
  284. /**
  285. * @param {Iterable<string>} iterable iterable object
  286. * @returns {string} joined iterable object
  287. */
  288. const joinIterableWithComma = (iterable) => {
  289. // This is more performant than Array.from().join(", ")
  290. // as it doesn't create an array
  291. let str = "";
  292. let first = true;
  293. for (const item of iterable) {
  294. if (first) {
  295. first = false;
  296. } else {
  297. str += ", ";
  298. }
  299. str += item;
  300. }
  301. return str;
  302. };
  303. /** @typedef {boolean} NonDeferAccess */
  304. /**
  305. * @param {NonDeferAccess} a a
  306. * @param {NonDeferAccess} b b
  307. * @returns {NonDeferAccess} merged
  308. */
  309. const mergeNonDeferAccess = (a, b) => a || b;
  310. /**
  311. * @param {NonDeferAccess} a first
  312. * @param {NonDeferAccess} b second
  313. * @returns {NonDeferAccess} first - second
  314. */
  315. const subtractNonDeferAccess = (a, b) => a && !b;
  316. /**
  317. * @typedef {object} ConcatenationEntry
  318. * @property {"concatenated" | "external"} type
  319. * @property {boolean} wrapped evaluation is deferred behind an accessor: a "concatenated" entry renders its body inside the lazy CJS wrapper instead of being scope-hoisted, an "external" entry only defers its `require()` call
  320. * @property {Module} module
  321. * @property {RuntimeSpec | boolean} runtimeCondition
  322. * @property {NonDeferAccess} nonDeferAccess
  323. */
  324. /**
  325. * Whether a member runs inside the lazy CJS wrapper or is scope-hoisted. Only a
  326. * NormalModule can carry a CJS body; an ESM member starts out hoisted and is
  327. * downgraded by {@link ConcatenatedModule._createConcatenationList}.
  328. * @param {Module} module a module taking part in the concatenation
  329. * @returns {boolean} true, when the module renders wrapped
  330. */
  331. const needWrapped = (module) =>
  332. module instanceof NormalModule &&
  333. module.type.startsWith("javascript/") &&
  334. module.buildMeta !== undefined &&
  335. module.buildMeta.exportsType !== "namespace";
  336. /**
  337. * Whether a hoisted member can move into the lazy wrapper instead.
  338. * @param {ConcatenationEntry} entry a member of the concatenation
  339. * @returns {boolean} true, when it may be wrapped
  340. */
  341. const entryCanBeWrapped = (entry) =>
  342. (entry.module instanceof NormalModule &&
  343. !entry.module.type.startsWith("css/")) ||
  344. (entry.module instanceof ExternalModule &&
  345. entry.module.canBeWrappedInConcatenation());
  346. /** @typedef {Set<ConcatenatedModuleInfo>} NeededNamespaceObjects */
  347. /** @typedef {Map<Module, ModuleInfo>} ModuleToInfoMap */
  348. /**
  349. * getExportsType memoized on the info, which lives for one codeGeneration.
  350. * The "dynamic" case walks the module graph, and is queried once per reference.
  351. * @param {ModuleGraph} moduleGraph the module graph
  352. * @param {ModuleInfo} info module info
  353. * @param {boolean | undefined} strict strict harmony module (undefined is treated as non-strict)
  354. * @returns {ExportsType} the exports type
  355. */
  356. const getExportsType = (moduleGraph, info, strict) => {
  357. if (strict) {
  358. if (info.exportsTypeStrict === undefined) {
  359. info.exportsTypeStrict = info.module.getExportsType(moduleGraph, true);
  360. }
  361. return info.exportsTypeStrict;
  362. }
  363. if (info.exportsTypeNonStrict === undefined) {
  364. info.exportsTypeNonStrict = info.module.getExportsType(moduleGraph, false);
  365. }
  366. return info.exportsTypeNonStrict;
  367. };
  368. /**
  369. * @param {ExternalModuleInfo} info module info
  370. * @returns {string} module exports expression
  371. */
  372. const getExternalModuleExpr = (info) =>
  373. info.wrapped
  374. ? `${
  375. /** @type {NonNullable<ExternalModuleInfo["namespaceFnName"]>} */
  376. (info.namespaceFnName)
  377. }()`
  378. : /** @type {NonNullable<ExternalModuleInfo["name"]>} */ (info.name);
  379. /**
  380. * A wrapped module's interop object is declared as a lazy accessor, so reading
  381. * it is a call. See `declareInterop`.
  382. * @param {ModuleInfo} info module info
  383. * @param {string | undefined} interopName interop variable name
  384. * @returns {string} interop object expression
  385. */
  386. const getInteropExpr = (info, interopName) =>
  387. info.wrapped ? `${interopName}()` : /** @type {string} */ (interopName);
  388. /**
  389. * Expression for an export that is not used. A hoisted body runs at its own
  390. * slot, but a wrapped one only runs when its accessor is called, so dropping
  391. * the reference would drop the module's side effects with it.
  392. * @param {ConcatenatedModuleInfo} info module info
  393. * @returns {string} expression evaluating to undefined
  394. */
  395. const getUnusedExportExpr = (info) =>
  396. info.wrapped
  397. ? `/* unused export */ (${info.namespaceObjectName}, undefined)`
  398. : "/* unused export */ undefined";
  399. /**
  400. * @param {ModuleGraph} moduleGraph the module graph
  401. * @param {ModuleInfo} info module info
  402. * @param {ExportName} exportName exportName
  403. * @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap
  404. * @param {RuntimeSpec} runtime for which runtime
  405. * @param {RequestShortener} requestShortener the request shortener
  406. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  407. * @param {NeededNamespaceObjects} neededNamespaceObjects modules for which a namespace object should be generated
  408. * @param {boolean} asCall asCall
  409. * @param {boolean} depDeferred the dependency is deferred
  410. * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
  411. * @param {boolean | undefined} asiSafe asiSafe
  412. * @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
  413. * @param {Set<InstanceType<ExportInfo>>=} alreadyVisited alreadyVisited
  414. * @returns {Binding} the final variable
  415. */
  416. const getFinalBinding = (
  417. moduleGraph,
  418. info,
  419. exportName,
  420. moduleToInfoMap,
  421. runtime,
  422. requestShortener,
  423. runtimeTemplate,
  424. neededNamespaceObjects,
  425. asCall,
  426. depDeferred,
  427. strictHarmonyModule,
  428. asiSafe,
  429. moduleExportsAccess,
  430. alreadyVisited
  431. ) => {
  432. const exportsType = getExportsType(moduleGraph, info, strictHarmonyModule);
  433. const moduleDeferred =
  434. info.type === "external" &&
  435. info.deferred &&
  436. !(/** @type {BuildMeta} */ (info.module.buildMeta).async);
  437. const deferred = depDeferred && moduleDeferred;
  438. if (moduleExportsAccess && info.type === "concatenated") {
  439. neededNamespaceObjects.add(info);
  440. // ids arrive as declared names and the rendered exports object is keyed by
  441. // used ones, so resolve here — the same way `case "external"` does below.
  442. // Resolving in the caller instead would mangle twice.
  443. const usedName =
  444. exportName.length === 0
  445. ? exportName
  446. : moduleGraph
  447. .getExportsInfo(info.module)
  448. .getUsedName(exportName, runtime);
  449. if (!usedName) {
  450. return {
  451. info,
  452. rawName: getUnusedExportExpr(info),
  453. ids: [],
  454. exportName
  455. };
  456. }
  457. return {
  458. info,
  459. rawName:
  460. /** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
  461. (info.namespaceObjectName),
  462. ids: /** @type {ExportName} */ (usedName),
  463. exportName
  464. };
  465. }
  466. if (exportName.length === 0) {
  467. switch (exportsType) {
  468. case "default-only":
  469. if (deferred) info.deferredNamespaceObjectUsed = true;
  470. else info.interopNamespaceObject2Used = true;
  471. return {
  472. info,
  473. rawName: deferred
  474. ? /** @type {string} */ (info.deferredNamespaceObjectName)
  475. : getInteropExpr(info, info.interopNamespaceObject2Name),
  476. ids: exportName,
  477. exportName
  478. };
  479. case "default-with-named":
  480. if (deferred) info.deferredNamespaceObjectUsed = true;
  481. else info.interopNamespaceObjectUsed = true;
  482. return {
  483. info,
  484. rawName: deferred
  485. ? /** @type {string} */ (info.deferredNamespaceObjectName)
  486. : getInteropExpr(info, info.interopNamespaceObjectName),
  487. ids: exportName,
  488. exportName
  489. };
  490. case "namespace":
  491. case "dynamic":
  492. break;
  493. default:
  494. throw new Error(`Unexpected exportsType ${exportsType}`);
  495. }
  496. } else {
  497. switch (exportsType) {
  498. case "namespace":
  499. break;
  500. case "default-with-named":
  501. switch (exportName[0]) {
  502. case "default":
  503. exportName = exportName.slice(1);
  504. if (deferred) {
  505. // `ns.default` for a deferred default-with-named external
  506. // module must read through the optimized `.a` getter
  507. // (which lazily evaluates the module and returns its
  508. // exports), not the proxy namespace itself — otherwise
  509. // `typeof ns.default` / `ns.default instanceof X`
  510. // observe the proxy instead of the actual default.
  511. return {
  512. info,
  513. rawName: `${info.deferredName}.a`,
  514. ids: exportName,
  515. exportName
  516. };
  517. }
  518. break;
  519. case "__esModule":
  520. return {
  521. info,
  522. rawName: "/* __esModule */true",
  523. ids: exportName.slice(1),
  524. exportName
  525. };
  526. }
  527. break;
  528. case "default-only": {
  529. const exportId = exportName[0];
  530. if (exportId === "__esModule") {
  531. return {
  532. info,
  533. rawName: "/* __esModule */true",
  534. ids: exportName.slice(1),
  535. exportName
  536. };
  537. }
  538. exportName = exportName.slice(1);
  539. if (exportId !== "default") {
  540. return {
  541. info,
  542. rawName:
  543. "/* non-default import from default-exporting module */undefined",
  544. ids: exportName,
  545. exportName
  546. };
  547. }
  548. if (deferred) {
  549. // As with default-with-named above, `ns.default` for a
  550. // deferred default-only external must read through the
  551. // optimized `.a` getter so that `typeof` / `instanceof`
  552. // observe the actual default value rather than the proxy.
  553. return {
  554. info,
  555. rawName: `${info.deferredName}.a`,
  556. ids: exportName,
  557. exportName
  558. };
  559. }
  560. break;
  561. }
  562. case "dynamic":
  563. switch (exportName[0]) {
  564. case "default": {
  565. exportName = exportName.slice(1);
  566. if (deferred) {
  567. return {
  568. info,
  569. rawName: `${info.deferredName}.a`,
  570. ids: exportName,
  571. exportName
  572. };
  573. }
  574. if (moduleDeferred) {
  575. return {
  576. info,
  577. rawName: getExternalModuleExpr(info),
  578. ids: exportName,
  579. exportName
  580. };
  581. }
  582. info.interopDefaultAccessUsed = true;
  583. const accessor = getInteropExpr(
  584. info,
  585. info.interopDefaultAccessName
  586. );
  587. const defaultExport = asCall
  588. ? `${accessor}()`
  589. : asiSafe
  590. ? `(${accessor}())`
  591. : asiSafe === false
  592. ? `;(${accessor}())`
  593. : `${accessor}.a`;
  594. return {
  595. info,
  596. rawName: defaultExport,
  597. ids: exportName,
  598. exportName
  599. };
  600. }
  601. case "__esModule":
  602. return {
  603. info,
  604. rawName: "/* __esModule */true",
  605. ids: exportName.slice(1),
  606. exportName
  607. };
  608. }
  609. break;
  610. default:
  611. throw new Error(`Unexpected exportsType ${exportsType}`);
  612. }
  613. }
  614. if (exportName.length === 0) {
  615. switch (info.type) {
  616. case "concatenated":
  617. neededNamespaceObjects.add(info);
  618. return {
  619. info,
  620. rawName:
  621. /** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
  622. (info.namespaceObjectName),
  623. ids: exportName,
  624. exportName
  625. };
  626. case "external":
  627. if (deferred) {
  628. info.deferredNamespaceObjectUsed = true;
  629. return {
  630. info,
  631. rawName: /** @type {string} */ (info.deferredNamespaceObjectName),
  632. ids: exportName,
  633. exportName
  634. };
  635. }
  636. return {
  637. info,
  638. rawName: getExternalModuleExpr(info),
  639. ids: exportName,
  640. exportName
  641. };
  642. }
  643. }
  644. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  645. const exportInfo = exportsInfo.getExportInfo(exportName[0]);
  646. // Lazily allocate: only the reexport-following recursion below needs it,
  647. // most calls return before reaching this point.
  648. if (alreadyVisited === undefined) alreadyVisited = new Set();
  649. if (alreadyVisited.has(exportInfo)) {
  650. return {
  651. info,
  652. rawName: "/* circular reexport */ Object(function x() { x() }())",
  653. ids: [],
  654. exportName
  655. };
  656. }
  657. alreadyVisited.add(exportInfo);
  658. switch (info.type) {
  659. case "concatenated": {
  660. const exportId = exportName[0];
  661. if (exportInfo.provided === false) {
  662. // It's not provided, but it could be on the prototype
  663. neededNamespaceObjects.add(info);
  664. return {
  665. info,
  666. rawName: /** @type {string} */ (info.namespaceObjectName),
  667. ids: exportName,
  668. exportName
  669. };
  670. }
  671. const directExport = info.exportMap && info.exportMap.get(exportId);
  672. if (directExport) {
  673. const usedName = exportsInfo.getUsedName(exportName, runtime);
  674. if (!usedName) {
  675. return {
  676. info,
  677. rawName: "/* unused export */ undefined",
  678. ids: exportName.slice(1),
  679. exportName
  680. };
  681. }
  682. if (usedName instanceof InlinedUsedName) {
  683. return {
  684. info,
  685. // Render the inlined literal only (e.g. `"str"`), not its property
  686. // suffix: that suffix is returned in `ids` and appended once by
  687. // getFinalName. Using `usedName.render()` would emit it here too,
  688. // duplicating the access (e.g. `"str".a.a`).
  689. rawName: usedName.render(
  690. Template.toNormalComment(
  691. `inlined export ${propertyAccess(exportName)}`
  692. )
  693. ),
  694. ids: usedName.suffix,
  695. exportName
  696. };
  697. }
  698. return {
  699. info,
  700. name: directExport,
  701. ids: /** @type {ExportName} */ (usedName).slice(1),
  702. exportName
  703. };
  704. }
  705. const rawExport = info.rawExportMap && info.rawExportMap.get(exportId);
  706. if (rawExport) {
  707. return {
  708. info,
  709. rawName: rawExport,
  710. ids: exportName.slice(1),
  711. exportName
  712. };
  713. }
  714. const reexport = exportInfo.findTarget(moduleGraph, (module) =>
  715. moduleToInfoMap.has(module)
  716. );
  717. if (reexport === false) {
  718. // Source module was removed because all its exports were inlined;
  719. // we render the inlined value here instead of binding to the now-absent module.
  720. const target = exportInfo.getTarget(moduleGraph);
  721. if (target && target.export) {
  722. const usedName = moduleGraph
  723. .getExportsInfo(target.module)
  724. .getUsedName([...target.export, ...exportName.slice(1)], runtime);
  725. if (usedName instanceof InlinedUsedName) {
  726. return {
  727. info,
  728. // Literal only; suffix is appended once via `ids` (see directExport branch).
  729. rawName: usedName.render(
  730. Template.toNormalComment(
  731. `inlined export ${propertyAccess(exportName)}`
  732. )
  733. ),
  734. ids: usedName.suffix,
  735. exportName
  736. };
  737. }
  738. }
  739. throw new Error(
  740. `Target module of reexport from '${info.module.readableIdentifier(
  741. requestShortener
  742. )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from(
  743. moduleToInfoMap,
  744. ([m, info]) =>
  745. ` * ${info.type} ${m.readableIdentifier(requestShortener)}`
  746. ).join("\n")}`
  747. );
  748. }
  749. if (reexport) {
  750. const refInfo = moduleToInfoMap.get(reexport.module);
  751. return getFinalBinding(
  752. moduleGraph,
  753. /** @type {ModuleInfo} */ (refInfo),
  754. reexport.export
  755. ? [...reexport.export, ...exportName.slice(1)]
  756. : exportName.slice(1),
  757. moduleToInfoMap,
  758. runtime,
  759. requestShortener,
  760. runtimeTemplate,
  761. neededNamespaceObjects,
  762. asCall,
  763. reexport.deferred,
  764. /** @type {BuildMeta} */
  765. (info.module.buildMeta).strictHarmonyModule,
  766. asiSafe,
  767. false,
  768. alreadyVisited
  769. );
  770. }
  771. // A wrapped module resolves every export through its live exports
  772. // alias (namespaceObjectName), same as namespaceExportSymbol modules.
  773. if (info.namespaceExportSymbol || info.wrapped) {
  774. const usedName = exportsInfo.getUsedName(exportName, runtime);
  775. if (!usedName) {
  776. return {
  777. info,
  778. rawName: "/* unused export */ undefined",
  779. ids: exportName.slice(1),
  780. exportName
  781. };
  782. }
  783. // an inlined export never reaches the exports object, so render the
  784. // literal instead of reading the namespace
  785. if (usedName instanceof InlinedUsedName) {
  786. return {
  787. info,
  788. // Literal only; suffix is appended once via `ids` (see directExport branch).
  789. rawName: usedName.render(
  790. Template.toNormalComment(
  791. `inlined export ${propertyAccess(exportName)}`
  792. )
  793. ),
  794. ids: usedName.suffix,
  795. exportName
  796. };
  797. }
  798. return {
  799. info,
  800. rawName: /** @type {string} */ (info.namespaceObjectName),
  801. ids: /** @type {ExportName} */ (usedName),
  802. exportName
  803. };
  804. }
  805. throw new Error(
  806. `Cannot get final name for export '${exportName.join(
  807. "."
  808. )}' of ${info.module.readableIdentifier(requestShortener)}`
  809. );
  810. }
  811. case "external": {
  812. const used = exportsInfo.getUsedName(exportName, runtime);
  813. if (!used) {
  814. return {
  815. info,
  816. rawName: "/* unused export */ undefined",
  817. ids: exportName.slice(1),
  818. exportName
  819. };
  820. }
  821. if (used instanceof InlinedUsedName) {
  822. return {
  823. info,
  824. // Literal only; suffix is appended once via `ids` (see directExport branch).
  825. rawName: used.render(
  826. Template.toNormalComment(
  827. `inlined export ${propertyAccess(exportName)}`
  828. )
  829. ),
  830. ids: used.suffix,
  831. exportName
  832. };
  833. }
  834. const usedName = /** @type {ExportName} */ (used);
  835. const comment = equals(usedName, exportName)
  836. ? ""
  837. : Template.toNormalComment(`${exportName.join(".")}`);
  838. return {
  839. info,
  840. rawName:
  841. (deferred ? `${info.deferredName}.a` : getExternalModuleExpr(info)) +
  842. comment,
  843. ids: usedName,
  844. exportName
  845. };
  846. }
  847. }
  848. };
  849. /**
  850. * @param {ModuleGraph} moduleGraph the module graph
  851. * @param {ModuleInfo} info module info
  852. * @param {ExportName} exportName exportName
  853. * @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap
  854. * @param {RuntimeSpec} runtime for which runtime
  855. * @param {RequestShortener} requestShortener the request shortener
  856. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  857. * @param {NeededNamespaceObjects} neededNamespaceObjects modules for which a namespace object should be generated
  858. * @param {boolean} asCall asCall
  859. * @param {boolean} depDeferred the dependency is deferred
  860. * @param {boolean | undefined} callContext callContext
  861. * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
  862. * @param {boolean | undefined} asiSafe asiSafe
  863. * @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
  864. * @returns {string} the final name
  865. */
  866. const getFinalName = (
  867. moduleGraph,
  868. info,
  869. exportName,
  870. moduleToInfoMap,
  871. runtime,
  872. requestShortener,
  873. runtimeTemplate,
  874. neededNamespaceObjects,
  875. asCall,
  876. depDeferred,
  877. callContext,
  878. strictHarmonyModule,
  879. asiSafe,
  880. moduleExportsAccess
  881. ) => {
  882. const binding = getFinalBinding(
  883. moduleGraph,
  884. info,
  885. exportName,
  886. moduleToInfoMap,
  887. runtime,
  888. requestShortener,
  889. runtimeTemplate,
  890. neededNamespaceObjects,
  891. asCall,
  892. depDeferred,
  893. strictHarmonyModule,
  894. asiSafe,
  895. moduleExportsAccess
  896. );
  897. {
  898. const { ids, comment } = binding;
  899. /** @type {string} */
  900. let reference;
  901. /** @type {boolean} */
  902. let isPropertyAccess;
  903. if ("rawName" in binding) {
  904. reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`;
  905. isPropertyAccess = ids.length > 0;
  906. } else {
  907. const { info, name: exportId } = binding;
  908. const name = info.internalNames.get(exportId);
  909. if (!name) {
  910. throw new Error(
  911. `The export "${exportId}" in "${info.module.readableIdentifier(
  912. requestShortener
  913. )}" has no internal name (existing names: ${
  914. Array.from(
  915. info.internalNames,
  916. ([name, symbol]) => `${name}: ${symbol}`
  917. ).join(", ") || "none"
  918. })`
  919. );
  920. }
  921. reference = `${name}${comment || ""}${propertyAccess(ids)}`;
  922. isPropertyAccess = ids.length > 1;
  923. }
  924. if (isPropertyAccess) {
  925. if (asCall && callContext === false) {
  926. return asiSafe
  927. ? `(0,${reference})`
  928. : asiSafe === false
  929. ? `;(0,${reference})`
  930. : `/*#__PURE__*/Object(${reference})`;
  931. } else if (binding.info.wrapped) {
  932. return asiSafe === false ? `;(${reference})` : `(${reference})`;
  933. }
  934. }
  935. return reference;
  936. }
  937. };
  938. /**
  939. * @typedef {object} ConcatenateModuleHooks
  940. * @property {SyncBailHook<[ConcatenatedModule, RuntimeSpec[], string, Record<string, string>], boolean>} onDemandExportsGeneration
  941. * @property {SyncBailHook<[Partial<ConcatenatedModuleInfo>, ConcatenatedModuleInfo], boolean | void>} concatenatedModuleInfo
  942. */
  943. /** @typedef {BuildInfo["topLevelDeclarations"]} TopLevelDeclarations */
  944. /**
  945. * Defines the build info properties specific to concatenated modules.
  946. * @typedef {object} KnownConcatenatedModuleBuildInfo
  947. * @property {FileSystemDependencies=} fileDependencies
  948. * @property {FileSystemDependencies=} contextDependencies
  949. * @property {FileSystemDependencies=} missingDependencies
  950. * @property {boolean=} needCreateRequire collected from the inner modules
  951. * @property {boolean=} inlineExports taken over from the root module
  952. */
  953. /** @typedef {BuildInfo & KnownConcatenatedModuleBuildInfo} ConcatenatedModuleBuildInfo */
  954. class ConcatenatedModule extends Module {
  955. /**
  956. * @param {Module} rootModule the root module of the concatenation
  957. * @param {Set<Module>} modules all modules in the concatenation (including the root module)
  958. * @param {RuntimeSpec} runtime the runtime
  959. * @param {Compilation} compilation the compilation
  960. * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching
  961. * @param {HashFunction=} hashFunction hash function to use
  962. * @returns {ConcatenatedModule} the module
  963. */
  964. static create(
  965. rootModule,
  966. modules,
  967. runtime,
  968. compilation,
  969. associatedObjectForCache,
  970. hashFunction = DEFAULTS.HASH_FUNCTION
  971. ) {
  972. const identifier = ConcatenatedModule._createIdentifier(
  973. rootModule,
  974. modules,
  975. associatedObjectForCache,
  976. hashFunction
  977. );
  978. return new ConcatenatedModule({
  979. identifier,
  980. rootModule,
  981. modules,
  982. runtime,
  983. compilation
  984. });
  985. }
  986. /**
  987. * @param {object} options options
  988. * @param {string} options.identifier the identifier of the module
  989. * @param {Module} options.rootModule the root module of the concatenation
  990. * @param {RuntimeSpec} options.runtime the selected runtime
  991. * @param {Set<Module>} options.modules all concatenated modules
  992. * @param {Compilation} options.compilation the compilation
  993. */
  994. constructor({ identifier, rootModule, modules, runtime, compilation }) {
  995. super(JAVASCRIPT_MODULE_TYPE_ESM, null, rootModule && rootModule.layer);
  996. // Redeclared with the concatenated module specific shape
  997. /** @type {ConcatenatedModuleBuildInfo | undefined} */
  998. this.buildInfo = undefined;
  999. /** @type {JavascriptModuleBuildMeta | undefined} */
  1000. this.buildMeta = undefined;
  1001. // Info from Factory
  1002. /** @type {string} */
  1003. this._identifier = identifier;
  1004. /** @type {Module} */
  1005. this.rootModule = rootModule;
  1006. /** @type {Set<Module>} */
  1007. this._modules = modules;
  1008. /** @type {RuntimeSpec} */
  1009. this._runtime = runtime;
  1010. this.factoryMeta = rootModule && rootModule.factoryMeta;
  1011. /** @type {Compilation} */
  1012. this.compilation = compilation;
  1013. }
  1014. /**
  1015. * Assuming this module is in the cache. Update the (cached) module with
  1016. * the fresh module from the factory. Usually updates internal references
  1017. * and properties.
  1018. * @param {Module} module fresh module
  1019. * @returns {void}
  1020. */
  1021. updateCacheModule(module) {
  1022. throw new Error("Must not be called");
  1023. }
  1024. /**
  1025. * Returns the source types this module can generate.
  1026. * @returns {SourceTypes} types available (do not mutate)
  1027. */
  1028. getSourceTypes() {
  1029. return JAVASCRIPT_TYPES;
  1030. }
  1031. get modules() {
  1032. return [...this._modules];
  1033. }
  1034. /**
  1035. * Returns the unique identifier used to reference this module.
  1036. * @returns {string} a unique identifier of the module
  1037. */
  1038. identifier() {
  1039. return this._identifier;
  1040. }
  1041. /**
  1042. * Returns a human-readable identifier for this module.
  1043. * @param {RequestShortener} requestShortener the request shortener
  1044. * @returns {string} a user readable identifier of the module
  1045. */
  1046. readableIdentifier(requestShortener) {
  1047. return `${this.rootModule.readableIdentifier(requestShortener)} + ${
  1048. this._modules.size - 1
  1049. } modules`;
  1050. }
  1051. /**
  1052. * Gets the library identifier.
  1053. * @param {LibIdentOptions} options options
  1054. * @returns {LibIdent | null} an identifier for library inclusion
  1055. */
  1056. libIdent(options) {
  1057. return this.rootModule.libIdent(options);
  1058. }
  1059. /**
  1060. * Returns the path used when matching this module against rule conditions.
  1061. * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
  1062. */
  1063. nameForCondition() {
  1064. return this.rootModule.nameForCondition();
  1065. }
  1066. /**
  1067. * Gets side effects connection state.
  1068. * @param {ModuleGraph} moduleGraph the module graph
  1069. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  1070. */
  1071. getSideEffectsConnectionState(moduleGraph) {
  1072. return this.rootModule.getSideEffectsConnectionState(moduleGraph);
  1073. }
  1074. /**
  1075. * Builds the module using the provided compilation context.
  1076. * @param {WebpackOptions} options webpack options
  1077. * @param {Compilation} compilation the compilation
  1078. * @param {ResolverWithOptions} resolver the resolver
  1079. * @param {InputFileSystem} fs the file system
  1080. * @param {BuildCallback} callback callback function
  1081. * @returns {void}
  1082. */
  1083. build(options, compilation, resolver, fs, callback) {
  1084. const { rootModule } = this;
  1085. const concatenateCommonJsModules = isCommonJsConcatenationEnabled(
  1086. options.optimization.concatenateModules
  1087. );
  1088. const { moduleArgument, exportsArgument } =
  1089. /** @type {BuildInfo} */
  1090. (rootModule.buildInfo);
  1091. /** @type {ConcatenatedModuleBuildInfo} */
  1092. this.buildInfo = {
  1093. strict: true,
  1094. cacheable: true,
  1095. moduleArgument,
  1096. exportsArgument,
  1097. fileDependencies: new LazySet(),
  1098. contextDependencies: new LazySet(),
  1099. missingDependencies: new LazySet(),
  1100. topLevelDeclarations: new Set(),
  1101. assets: undefined,
  1102. inlineExports: /** @type {JavascriptModuleBuildInfo} */ (
  1103. rootModule.buildInfo
  1104. ).inlineExports
  1105. };
  1106. this.buildMeta = rootModule.buildMeta;
  1107. this.clearDependenciesAndBlocks();
  1108. this.clearWarningsAndErrors();
  1109. for (const m of this._modules) {
  1110. // populate cacheable
  1111. const { cacheable, notCacheableReasons } = /** @type {BuildInfo} */ (
  1112. m.buildInfo
  1113. );
  1114. if (!cacheable) {
  1115. this.buildInfo.cacheable = false;
  1116. if (notCacheableReasons) {
  1117. const reasons =
  1118. this.buildInfo.notCacheableReasons ||
  1119. (this.buildInfo.notCacheableReasons = []);
  1120. for (const reason of notCacheableReasons) {
  1121. if (!reasons.includes(reason)) reasons.push(reason);
  1122. }
  1123. }
  1124. }
  1125. // populate dependencies — keep only deps that leave the concat set
  1126. for (const d of m.dependencies) {
  1127. if (
  1128. !Dependency.canConcatenate(d, concatenateCommonJsModules) ||
  1129. !this._modules.has(
  1130. /** @type {Module} */
  1131. (compilation.moduleGraph.getModule(d))
  1132. )
  1133. ) {
  1134. this.dependencies.push(d);
  1135. }
  1136. }
  1137. // populate codeGenerationDependencies — the inner modules'
  1138. // templates are applied during ConcatenatedModule.codeGeneration,
  1139. // so the referenced modules must have been code-generated by then.
  1140. // Skip references that point back into the concat set itself.
  1141. if (m.codeGenerationDependencies !== undefined) {
  1142. for (const d of m.codeGenerationDependencies) {
  1143. const referenced =
  1144. /** @type {Module} */
  1145. (compilation.moduleGraph.getModule(d));
  1146. if (!this._modules.has(referenced)) {
  1147. this.addCodeGenerationDependency(d);
  1148. }
  1149. }
  1150. }
  1151. // populate blocks
  1152. for (const d of m.blocks) {
  1153. this.blocks.push(d);
  1154. }
  1155. // populate warnings
  1156. const warnings = m.getWarnings();
  1157. if (warnings !== undefined) {
  1158. for (const warning of warnings) {
  1159. this.addWarning(warning);
  1160. }
  1161. }
  1162. // populate errors
  1163. const errors = m.getErrors();
  1164. if (errors !== undefined) {
  1165. for (const error of errors) {
  1166. this.addError(error);
  1167. }
  1168. }
  1169. const { assets, assetsInfo, topLevelDeclarations, needCreateRequire } =
  1170. /** @type {JavascriptModuleBuildInfo} */ (m.buildInfo);
  1171. const buildInfo = this.buildInfo;
  1172. // populate topLevelDeclarations
  1173. if (topLevelDeclarations) {
  1174. const mergedTopLevelDeclarations = buildInfo.topLevelDeclarations;
  1175. if (mergedTopLevelDeclarations !== undefined) {
  1176. for (const decl of topLevelDeclarations) {
  1177. mergedTopLevelDeclarations.add(decl);
  1178. }
  1179. }
  1180. } else {
  1181. buildInfo.topLevelDeclarations = undefined;
  1182. }
  1183. // populate needCreateRequire
  1184. if (needCreateRequire) {
  1185. this.buildInfo.needCreateRequire = true;
  1186. }
  1187. // populate assets
  1188. if (assets) {
  1189. if (buildInfo.assets === undefined) {
  1190. buildInfo.assets = Object.create(null);
  1191. }
  1192. Object.assign(
  1193. /** @type {NonNullable<BuildInfo["assets"]>} */
  1194. (buildInfo.assets),
  1195. assets
  1196. );
  1197. }
  1198. if (assetsInfo) {
  1199. if (buildInfo.assetsInfo === undefined) {
  1200. buildInfo.assetsInfo = new Map();
  1201. }
  1202. for (const [key, value] of assetsInfo) {
  1203. buildInfo.assetsInfo.set(key, value);
  1204. }
  1205. }
  1206. }
  1207. callback();
  1208. }
  1209. /**
  1210. * Returns the estimated size for the requested source type.
  1211. * @param {string=} type the source type for which the size should be estimated
  1212. * @returns {number} the estimated size of the module (must be non-zero)
  1213. */
  1214. size(type) {
  1215. // Guess size from embedded modules
  1216. let size = 0;
  1217. for (const module of this._modules) {
  1218. size += module.size(type);
  1219. }
  1220. return size;
  1221. }
  1222. /**
  1223. * @private
  1224. * @param {Module} rootModule the root of the concatenation
  1225. * @param {Set<Module>} modulesSet a set of modules which should be concatenated
  1226. * @param {RuntimeSpec} runtime for this runtime
  1227. * @param {ModuleGraph} moduleGraph the module graph
  1228. * @returns {ConcatenationEntry[]} concatenation list
  1229. */
  1230. _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) {
  1231. const concatenateCommonJsModules = isCommonJsConcatenationEnabled(
  1232. this.compilation.options.optimization.concatenateModules
  1233. );
  1234. /** @type {ConcatenationEntry[]} */
  1235. const list = [];
  1236. /** @type {Map<Module, { runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} */
  1237. const existingEntries = new Map();
  1238. /** @type {Map<Module, Module[]>} */
  1239. const importConnections = new Map();
  1240. /** @type {Set<Module>} */
  1241. const wrappedModules = new Set();
  1242. /**
  1243. * @param {Module} module a module
  1244. * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} imported modules in order
  1245. */
  1246. const getConcatenatedImports = (module) => {
  1247. const connections = [...moduleGraph.getOutgoingConnections(module)];
  1248. if (module === rootModule) {
  1249. for (const c of moduleGraph.getOutgoingConnections(this)) {
  1250. connections.push(c);
  1251. }
  1252. }
  1253. /**
  1254. * @type {{ connection: ModuleGraphConnection, sourceOrder: number, rangeStart: number | undefined, defer?: boolean }[]}
  1255. */
  1256. const references = connections
  1257. .filter((connection) => {
  1258. if (
  1259. !connection.dependency ||
  1260. !Dependency.canConcatenate(
  1261. connection.dependency,
  1262. concatenateCommonJsModules
  1263. )
  1264. ) {
  1265. return false;
  1266. }
  1267. if (
  1268. !Module.getSourceBasicTypes(connection.module).has(JAVASCRIPT_TYPE)
  1269. ) {
  1270. return false;
  1271. }
  1272. return (
  1273. connection &&
  1274. connection.resolvedOriginModule === module &&
  1275. connection.module &&
  1276. connection.isTargetActive(runtime)
  1277. );
  1278. })
  1279. .map((connection) => {
  1280. const dep =
  1281. /** @type {HarmonyImportDependency} */
  1282. (connection.dependency);
  1283. return {
  1284. connection,
  1285. // A require() edge carries no sourceOrder; Infinity sorts it last,
  1286. // matching the low-priority sentinel. NaN must not be used here:
  1287. // compareNumbers returns 0 against every number, which makes the
  1288. // comparator non-transitive and the order depend on insertion order.
  1289. sourceOrder:
  1290. typeof dep.sourceOrder === "number" ? dep.sourceOrder : Infinity,
  1291. rangeStart: dep.range && dep.range[0],
  1292. defer: ImportPhaseUtils.isDefer(dep.phase)
  1293. };
  1294. });
  1295. /**
  1296. * bySourceOrder
  1297. * @example
  1298. * import a from "a"; // sourceOrder=1
  1299. * import b from "b"; // sourceOrder=2
  1300. *
  1301. * byRangeStart
  1302. * @example
  1303. * import {a, b} from "a"; // sourceOrder=1
  1304. * a.a(); // first range
  1305. * b.b(); // second range
  1306. *
  1307. * If there is no reexport, we have the same source.
  1308. * If there is reexport, but module has side effects, this will lead to reexport module only.
  1309. * If there is side-effects-free reexport, we can get simple deterministic result with range start comparison.
  1310. */
  1311. references.sort(concatComparators(bySourceOrder, byRangeStart));
  1312. /** @type {Map<Module, { connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} */
  1313. const referencesMap = new Map();
  1314. /** @type {Module[] | undefined} */
  1315. let targets;
  1316. for (const { connection, defer } of references) {
  1317. const runtimeCondition = filterRuntime(runtime, (r) =>
  1318. connection.isTargetActive(r)
  1319. );
  1320. if (runtimeCondition === false) continue;
  1321. const nonDeferAccess = !defer;
  1322. const module = connection.module;
  1323. if (targets === undefined) targets = [module];
  1324. else if (!targets.includes(module)) targets.push(module);
  1325. if (
  1326. [
  1327. CommonJsRequireDependency,
  1328. CommonJsFullRequireDependency,
  1329. CommonJsExportRequireDependency
  1330. ].some((Dep) => connection.dependency instanceof Dep)
  1331. ) {
  1332. wrappedModules.add(module);
  1333. }
  1334. const entry = referencesMap.get(module);
  1335. if (entry === undefined) {
  1336. referencesMap.set(module, {
  1337. connection,
  1338. runtimeCondition,
  1339. nonDeferAccess
  1340. });
  1341. continue;
  1342. }
  1343. entry.runtimeCondition = mergeRuntimeConditionNonFalse(
  1344. entry.runtimeCondition,
  1345. runtimeCondition,
  1346. runtime
  1347. );
  1348. entry.nonDeferAccess = mergeNonDeferAccess(
  1349. entry.nonDeferAccess,
  1350. nonDeferAccess
  1351. );
  1352. }
  1353. if (targets !== undefined) importConnections.set(module, targets);
  1354. return referencesMap.values();
  1355. };
  1356. /**
  1357. * @param {ModuleGraphConnection} connection graph connection
  1358. * @param {RuntimeSpec | true} runtimeCondition runtime condition
  1359. * @param {NonDeferAccess} nonDeferAccess non-defer access
  1360. * @returns {void}
  1361. */
  1362. const enterModule = (connection, runtimeCondition, nonDeferAccess) => {
  1363. const module = connection.module;
  1364. if (!module) return;
  1365. const existingEntry = existingEntries.get(module);
  1366. if (
  1367. existingEntry &&
  1368. existingEntry.runtimeCondition === true &&
  1369. existingEntry.nonDeferAccess === true
  1370. ) {
  1371. return;
  1372. }
  1373. if (modulesSet.has(module)) {
  1374. existingEntries.set(module, {
  1375. runtimeCondition: true,
  1376. nonDeferAccess: true
  1377. });
  1378. if (runtimeCondition !== true) {
  1379. throw new Error(
  1380. `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString(
  1381. runtimeCondition
  1382. )}). This should not happen.`
  1383. );
  1384. }
  1385. if (nonDeferAccess !== true) {
  1386. throw new Error(
  1387. `Cannot deferred concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}. This should not happen.`
  1388. );
  1389. }
  1390. const imports = getConcatenatedImports(module);
  1391. for (const {
  1392. connection,
  1393. runtimeCondition,
  1394. nonDeferAccess
  1395. } of imports) {
  1396. enterModule(connection, runtimeCondition, nonDeferAccess);
  1397. }
  1398. list.push({
  1399. type: "concatenated",
  1400. wrapped: needWrapped(module),
  1401. module: connection.module,
  1402. runtimeCondition,
  1403. nonDeferAccess
  1404. });
  1405. } else {
  1406. /** @type {RuntimeSpec | boolean} */
  1407. let reducedRuntimeCondition;
  1408. /** @type {NonDeferAccess} */
  1409. let reducedNonDeferAccess;
  1410. if (existingEntry !== undefined) {
  1411. reducedRuntimeCondition = subtractRuntimeCondition(
  1412. runtimeCondition,
  1413. existingEntry.runtimeCondition,
  1414. runtime
  1415. );
  1416. reducedNonDeferAccess = subtractNonDeferAccess(
  1417. nonDeferAccess,
  1418. existingEntry.nonDeferAccess
  1419. );
  1420. if (
  1421. reducedRuntimeCondition === false &&
  1422. reducedNonDeferAccess === false
  1423. ) {
  1424. return;
  1425. }
  1426. if (reducedRuntimeCondition !== false) {
  1427. existingEntry.runtimeCondition = mergeRuntimeConditionNonFalse(
  1428. existingEntry.runtimeCondition,
  1429. reducedRuntimeCondition,
  1430. runtime
  1431. );
  1432. }
  1433. if (reducedNonDeferAccess !== false) {
  1434. existingEntry.nonDeferAccess = mergeNonDeferAccess(
  1435. existingEntry.nonDeferAccess,
  1436. reducedNonDeferAccess
  1437. );
  1438. }
  1439. } else {
  1440. reducedRuntimeCondition = runtimeCondition;
  1441. reducedNonDeferAccess = nonDeferAccess;
  1442. existingEntries.set(connection.module, {
  1443. runtimeCondition,
  1444. nonDeferAccess
  1445. });
  1446. }
  1447. if (list.length > 0) {
  1448. const lastItem = list[list.length - 1];
  1449. if (
  1450. lastItem.type === "external" &&
  1451. lastItem.module === connection.module
  1452. ) {
  1453. lastItem.runtimeCondition = mergeRuntimeCondition(
  1454. lastItem.runtimeCondition,
  1455. reducedRuntimeCondition,
  1456. runtime
  1457. );
  1458. lastItem.nonDeferAccess = mergeNonDeferAccess(
  1459. lastItem.nonDeferAccess,
  1460. reducedNonDeferAccess
  1461. );
  1462. return;
  1463. }
  1464. }
  1465. list.push({
  1466. type: "external",
  1467. wrapped: wrappedModules.has(connection.module),
  1468. get module() {
  1469. // We need to use a getter here, because the module in the dependency
  1470. // could be replaced by some other process (i. e. also replaced with a
  1471. // concatenated module)
  1472. return connection.module;
  1473. },
  1474. runtimeCondition: reducedRuntimeCondition,
  1475. nonDeferAccess: reducedNonDeferAccess
  1476. });
  1477. }
  1478. };
  1479. existingEntries.set(rootModule, {
  1480. runtimeCondition: true,
  1481. nonDeferAccess: true
  1482. });
  1483. const imports = getConcatenatedImports(rootModule);
  1484. for (const { connection, runtimeCondition, nonDeferAccess } of imports) {
  1485. enterModule(connection, runtimeCondition, nonDeferAccess);
  1486. }
  1487. list.push({
  1488. type: "concatenated",
  1489. wrapped: needWrapped(rootModule),
  1490. module: rootModule,
  1491. runtimeCondition: true,
  1492. nonDeferAccess: true
  1493. });
  1494. // A lazily evaluated member may only depend on lazily evaluated members,
  1495. // so wrapping propagates forward from every `require()` target along all
  1496. // import edges, ESM included.
  1497. /** @type {Set<Module>} */
  1498. const modules = new Set(wrappedModules);
  1499. for (const entry of list) {
  1500. if (entry.wrapped) modules.add(entry.module);
  1501. }
  1502. const queue = [...modules];
  1503. for (let i = 0; i < queue.length; i++) {
  1504. const targets = importConnections.get(queue[i]);
  1505. if (targets === undefined) continue;
  1506. for (const target of targets) {
  1507. if (modules.has(target)) continue;
  1508. modules.add(target);
  1509. queue.push(target);
  1510. }
  1511. }
  1512. for (const entry of list) {
  1513. if (
  1514. !entry.wrapped &&
  1515. modules.has(entry.module) &&
  1516. entryCanBeWrapped(entry)
  1517. ) {
  1518. entry.wrapped = true;
  1519. }
  1520. }
  1521. return list;
  1522. }
  1523. /**
  1524. * @param {Module} rootModule the root module of the concatenation
  1525. * @param {Set<Module>} modules all modules in the concatenation (including the root module)
  1526. * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching
  1527. * @param {HashFunction=} hashFunction hash function to use
  1528. * @returns {string} the identifier
  1529. */
  1530. static _createIdentifier(
  1531. rootModule,
  1532. modules,
  1533. associatedObjectForCache,
  1534. hashFunction = DEFAULTS.HASH_FUNCTION
  1535. ) {
  1536. const cachedMakePathsRelative = makePathsRelative.bindContextCache(
  1537. /** @type {string} */ (rootModule.context),
  1538. associatedObjectForCache
  1539. );
  1540. /** @type {string[]} */
  1541. const identifiers = [];
  1542. for (const module of modules) {
  1543. identifiers.push(cachedMakePathsRelative(module.identifier()));
  1544. }
  1545. identifiers.sort();
  1546. const hash = createHash(hashFunction);
  1547. hash.update(identifiers.join(" "));
  1548. return `${rootModule.identifier()}|${hash.digest("hex")}`;
  1549. }
  1550. /**
  1551. * Adds the provided file dependencies to the module.
  1552. * @param {FileSystemDependencies} fileDependencies set where file dependencies are added to
  1553. * @param {FileSystemDependencies} contextDependencies set where context dependencies are added to
  1554. * @param {FileSystemDependencies} missingDependencies set where missing dependencies are added to
  1555. * @param {FileSystemDependencies} buildDependencies set where build dependencies are added to
  1556. */
  1557. addCacheDependencies(
  1558. fileDependencies,
  1559. contextDependencies,
  1560. missingDependencies,
  1561. buildDependencies
  1562. ) {
  1563. for (const module of this._modules) {
  1564. module.addCacheDependencies(
  1565. fileDependencies,
  1566. contextDependencies,
  1567. missingDependencies,
  1568. buildDependencies
  1569. );
  1570. }
  1571. }
  1572. /*
  1573. * How the inner modules become one flat source. Stages [1]-[5] only mutate the
  1574. * per-module info records (names, ReplaceSource patches); stages [6]-[9] append
  1575. * to the single output ConcatSource, in exactly the order shown.
  1576. *
  1577. * _getModulesWithInfo() — ordered concatenation list + one info per module
  1578. * | (concatenated [+wrapped] | external | reference)
  1579. * v
  1580. * [1] ANALYSE — inner codeGeneration() per module, into a ConcatenationScope
  1581. * | plain -> ReplaceSource + ast + scope analysis
  1582. * | wrapped -> ReplaceSource only, body kept verbatim
  1583. * | external -> nothing yet, rendered as a require() below
  1584. * [2] RESERVE — free globals of the analysed bodies enter allUsedNames, so
  1585. * | renaming in [3] can't shadow them (a wrapped body is not analysed;
  1586. * | the reserved `__webpack_` prefix protects it)
  1587. * [3] RENAME — module-scope variables renamed inside the ReplaceSource, then
  1588. * | the generated names allocated: wrapper accessor, namespace object,
  1589. * | interop helpers, external import variable
  1590. * [4] LINK — __WEBPACK_MODULE_REFERENCE__ tokens replaced by their final
  1591. * | binding; through the ast for analysed bodies, textually for wrapped
  1592. * [5] COLLECT EXPORTS — root exports split into used / unused / inlined
  1593. * v
  1594. * ---- from here on everything is appended to the result ConcatSource ----
  1595. * |
  1596. * [6] EMIT EXPORTS — __esModule flag + exports getters, UNUSED/INLINED lists
  1597. * [7] BUILD NS — namespace object sources built as strings (not emitted yet)
  1598. * [8] DEFINE — everything that must exist before any body runs: namespace
  1599. * | objects, wrapper accessors (wrapped modules and wrapped externals),
  1600. * | deferred external loaders
  1601. * [9] EVALUATE — bodies in concatenation order: plain bodies inline, externals
  1602. * | as require(); a wrapped body stays behind its accessor
  1603. * v
  1604. * [10] RESULT — CodeGenerationResult { sources, data, runtimeRequirements }
  1605. */
  1606. /**
  1607. * Generates code and runtime requirements for this module.
  1608. * @param {CodeGenerationContext} context context for code generation
  1609. * @returns {CodeGenerationResult} result
  1610. */
  1611. codeGeneration({
  1612. dependencyTemplates,
  1613. runtimeTemplate,
  1614. moduleGraph,
  1615. chunkGraph,
  1616. runtime: generationRuntime,
  1617. runtimes,
  1618. codeGenerationResults
  1619. }) {
  1620. const { concatenatedModuleInfo } = ConcatenatedModule.getCompilationHooks(
  1621. this.compilation
  1622. );
  1623. /** @type {RuntimeRequirements} */
  1624. const runtimeRequirements = new Set();
  1625. const runtime = intersectRuntime(generationRuntime, this._runtime);
  1626. const requestShortener = runtimeTemplate.requestShortener;
  1627. // Meta info for each module, in evaluation order (repeats become references)
  1628. const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo(
  1629. moduleGraph,
  1630. runtime
  1631. );
  1632. // This module's body is the root's body, so a wrapped root still evaluates
  1633. // at its slot. No import edge inside the concatenation expresses that.
  1634. const rootModuleInfo = moduleToInfoMap.get(this.rootModule);
  1635. if (rootModuleInfo !== undefined) rootModuleInfo.eager = true;
  1636. // State shared by all stages below, in the order they are filled
  1637. // List of all used names to avoid conflicts
  1638. const allUsedNames = new Set(RESERVED_NAMES);
  1639. // Updated Top level declarations are created by renaming
  1640. /** @type {TopLevelDeclarations} */
  1641. const topLevelDeclarations = new Set();
  1642. // Free names remaining in the rendered source (runtime globals are
  1643. // tracked by runtimeRequirements instead)
  1644. /** @type {Set<string>} */
  1645. const freeNames = new Set();
  1646. // List of additional names in scope for module references
  1647. /** @type {UsedNamesInScopeInfo} */
  1648. const usedNamesInScopeInfo = new Map();
  1649. // Set of already checked scopes
  1650. /** @type {Set<Scope>} */
  1651. const ignoredScopes = new Set();
  1652. // Set with modules that need a generated namespace object
  1653. /** @type {NeededNamespaceObjects} */
  1654. const neededNamespaceObjects = new Set();
  1655. // Set with modules whose mangled namespace escapes as a whole value and
  1656. // therefore needs a decoupled namespace object keyed by the original names
  1657. /** @type {Set<ConcatenatedModuleInfo | ExternalModuleInfo>} */
  1658. const neededEscapeNamespaceObjects = new Set();
  1659. // #region [1] ANALYSE: run each inner module's own codeGeneration; a
  1660. // non-wrapped body is parsed and scope-analysed so [3] can rename its locals
  1661. for (const info of moduleToInfoMap.values()) {
  1662. this._analyseModule(
  1663. moduleToInfoMap,
  1664. info,
  1665. dependencyTemplates,
  1666. runtimeTemplate,
  1667. moduleGraph,
  1668. chunkGraph,
  1669. runtime,
  1670. runtimes,
  1671. /** @type {CodeGenerationResults} */
  1672. (codeGenerationResults),
  1673. allUsedNames
  1674. );
  1675. }
  1676. // #endregion
  1677. /**
  1678. * Lazily allocates a decoupled namespace object for a concatenated module
  1679. * whose exports are mangled, so an escaping whole-namespace value still
  1680. * exposes the original export names. Returns undefined when no export is
  1681. * mangled (the regular namespace object can be used as-is).
  1682. * @param {ConcatenatedModuleInfo | ExternalModuleInfo} info module info
  1683. * @returns {string | undefined} the escape namespace object name
  1684. */
  1685. const getEscapeNamespaceObjectName = (info) => {
  1686. // Only a hoisted member's namespaceExportSymbol is a real variable
  1687. // holding the original names; a wrapped one reuses the field for its
  1688. // `X_namespaceFn()` call, which exposes the mangled keys
  1689. if (
  1690. info.type === "concatenated" &&
  1691. !info.wrapped &&
  1692. info.namespaceExportSymbol
  1693. ) {
  1694. return undefined;
  1695. }
  1696. // Deferred external modules keep their special deferred namespace object
  1697. // and are rendered through a different path that wouldn't emit ours.
  1698. if (info.type === "external" && info.deferred) {
  1699. return undefined;
  1700. }
  1701. // Only real ES module namespaces are decoupled; non-harmony modules use
  1702. // their interop/fake namespace object as before.
  1703. const buildMeta = /** @type {BuildMeta} */ (info.module.buildMeta);
  1704. if (!buildMeta || buildMeta.exportsType !== "namespace") return undefined;
  1705. if (info.escapeNamespaceObjectName !== undefined) {
  1706. return info.escapeNamespaceObjectName;
  1707. }
  1708. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  1709. let mangled = false;
  1710. for (const exportInfo of exportsInfo.orderedExports) {
  1711. if (exportInfo.provided === false) continue;
  1712. const usedName = exportInfo.getUsedName(undefined, runtime);
  1713. if (!usedName || usedName instanceof InlinedUsedName) continue;
  1714. if (usedName[usedName.length - 1] !== exportInfo.name) {
  1715. mangled = true;
  1716. break;
  1717. }
  1718. }
  1719. if (!mangled) return undefined;
  1720. const name = findNewName(
  1721. "namespaceObject",
  1722. allUsedNames,
  1723. /** @type {UsedNames} */ (new Set()),
  1724. info.module.readableIdentifier(requestShortener)
  1725. );
  1726. allUsedNames.add(name);
  1727. topLevelDeclarations.add(name);
  1728. info.escapeNamespaceObjectName = name;
  1729. neededEscapeNamespaceObjects.add(info);
  1730. return name;
  1731. };
  1732. // #region [2] RESERVE: the free globals of every analysed body. Claiming
  1733. // them up front is what lets [3] rename without shadowing any of them
  1734. for (const info of modulesWithInfo) {
  1735. if (info.type === "concatenated") {
  1736. if (info.wrapped) {
  1737. // The body is emitted verbatim and never renamed, so every identifier
  1738. // in it is claimed: its declarations must not shadow a name [3]
  1739. // generates, and its free globals must not be captured by one.
  1740. for (const name of findIdentifiers(
  1741. /** @type {Source} */ (info.internalSource)
  1742. )) {
  1743. allUsedNames.add(name);
  1744. }
  1745. // A wrapped body has no scope analysis, so its references are found
  1746. // textually. They still have to be resolved here: binding one is what
  1747. // flags the interop objects it needs, and [3] allocates their names.
  1748. /** @type {Set<string>} */
  1749. const visitedReferences = new Set();
  1750. for (const reference of ConcatenationScope.findModuleReferences(
  1751. /** @type {Source} */ (info.internalSource)
  1752. )) {
  1753. if (visitedReferences.has(reference.name)) continue;
  1754. visitedReferences.add(reference.name);
  1755. const match = ConcatenationScope.matchModuleReference(
  1756. reference.name
  1757. );
  1758. if (!match) continue;
  1759. const referencedInfo = modulesWithInfo[match.index];
  1760. if (referencedInfo.type === "reference") {
  1761. throw new Error("Module reference can't point to a reference");
  1762. }
  1763. if (
  1764. match.mangleableNamespace &&
  1765. match.ids.length === 0 &&
  1766. getEscapeNamespaceObjectName(referencedInfo) !== undefined
  1767. ) {
  1768. continue;
  1769. }
  1770. getFinalBinding(
  1771. moduleGraph,
  1772. referencedInfo,
  1773. match.ids,
  1774. moduleToInfoMap,
  1775. runtime,
  1776. requestShortener,
  1777. runtimeTemplate,
  1778. neededNamespaceObjects,
  1779. match.call,
  1780. match.deferredImport,
  1781. /** @type {BuildMeta} */
  1782. (info.module.buildMeta).strictHarmonyModule,
  1783. match.asiSafe,
  1784. match.moduleExportsAccess
  1785. );
  1786. }
  1787. } else {
  1788. // ignore symbols from moduleScope
  1789. if (info.moduleScope) {
  1790. ignoredScopes.add(info.moduleScope);
  1791. }
  1792. // add global symbols
  1793. if (info.unresolvedReferences) {
  1794. for (const reference of info.unresolvedReferences) {
  1795. const name = reference.identifier.name;
  1796. if (ConcatenationScope.isModuleReference(name)) {
  1797. const match = ConcatenationScope.matchModuleReference(name);
  1798. if (!match) continue;
  1799. const referencedInfo = modulesWithInfo[match.index];
  1800. if (referencedInfo.type === "reference") {
  1801. throw new Error(
  1802. "Module reference can't point to a reference"
  1803. );
  1804. }
  1805. // An escaping mangled namespace resolves to its own decoupled
  1806. // namespace object (a unique top-level name), so it neither needs
  1807. // the regular namespace object nor super-class scope handling.
  1808. if (
  1809. match.mangleableNamespace &&
  1810. match.ids.length === 0 &&
  1811. getEscapeNamespaceObjectName(referencedInfo) !== undefined
  1812. ) {
  1813. continue;
  1814. }
  1815. const binding = getFinalBinding(
  1816. moduleGraph,
  1817. referencedInfo,
  1818. match.ids,
  1819. moduleToInfoMap,
  1820. runtime,
  1821. requestShortener,
  1822. runtimeTemplate,
  1823. neededNamespaceObjects,
  1824. false,
  1825. match.deferredImport,
  1826. /** @type {BuildMeta} */
  1827. (info.module.buildMeta).strictHarmonyModule,
  1828. true,
  1829. match.moduleExportsAccess
  1830. );
  1831. if (!binding.ids) continue;
  1832. const { usedNames, alreadyCheckedScopes } =
  1833. getUsedNamesInScopeInfo(
  1834. usedNamesInScopeInfo,
  1835. binding.info.module.identifier(),
  1836. "name" in binding ? binding.name : ""
  1837. );
  1838. addScopeSymbols(
  1839. reference.from,
  1840. usedNames,
  1841. alreadyCheckedScopes,
  1842. ignoredScopes
  1843. );
  1844. } else {
  1845. allUsedNames.add(name);
  1846. freeNames.add(name);
  1847. }
  1848. }
  1849. }
  1850. }
  1851. }
  1852. }
  1853. // #endregion
  1854. /**
  1855. * @param {string} name the name to find a new name for
  1856. * @param {ConcatenatedModuleInfo} info the info of the module
  1857. * @param {Reference[]} references the references to the name
  1858. * @returns {string | undefined} the new name or undefined if the name is not found
  1859. */
  1860. const _findNewName = (name, info, references) => {
  1861. const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo(
  1862. usedNamesInScopeInfo,
  1863. info.module.identifier(),
  1864. name
  1865. );
  1866. if (allUsedNames.has(name) || usedNames.has(name)) {
  1867. for (const ref of references) {
  1868. addScopeSymbols(
  1869. ref.from,
  1870. usedNames,
  1871. alreadyCheckedScopes,
  1872. ignoredScopes
  1873. );
  1874. }
  1875. const newName = findNewName(
  1876. name,
  1877. allUsedNames,
  1878. usedNames,
  1879. info.module.readableIdentifier(requestShortener)
  1880. );
  1881. allUsedNames.add(newName);
  1882. info.internalNames.set(name, newName);
  1883. topLevelDeclarations.add(newName);
  1884. return newName;
  1885. }
  1886. };
  1887. /**
  1888. * @param {string} name the name to find a new name for
  1889. * @param {ConcatenatedModuleInfo} info the info of the module
  1890. * @param {Reference[]} references the references to the name
  1891. * @returns {string | undefined} the new name or undefined if the name is not found
  1892. */
  1893. const _findNewNameForSpecifier = (name, info, references) => {
  1894. const { usedNames: moduleUsedNames, alreadyCheckedScopes } =
  1895. getUsedNamesInScopeInfo(
  1896. usedNamesInScopeInfo,
  1897. info.module.identifier(),
  1898. name
  1899. );
  1900. /** @type {UsedNames} */
  1901. const referencesUsedNames = new Set();
  1902. for (const ref of references) {
  1903. addScopeSymbols(
  1904. ref.from,
  1905. referencesUsedNames,
  1906. alreadyCheckedScopes,
  1907. ignoredScopes
  1908. );
  1909. }
  1910. if (moduleUsedNames.has(name) || referencesUsedNames.has(name)) {
  1911. const newName = findNewName(
  1912. name,
  1913. allUsedNames,
  1914. new Set([...moduleUsedNames, ...referencesUsedNames]),
  1915. info.module.readableIdentifier(requestShortener)
  1916. );
  1917. allUsedNames.add(newName);
  1918. topLevelDeclarations.add(newName);
  1919. return newName;
  1920. }
  1921. };
  1922. // #region [3] RENAME: rename every module-scope variable inside its
  1923. // ReplaceSource, then allocate the generated names (wrapper accessor,
  1924. // namespace object, interop helpers, external import variable)
  1925. for (const info of moduleToInfoMap.values()) {
  1926. const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo(
  1927. usedNamesInScopeInfo,
  1928. info.module.identifier(),
  1929. ""
  1930. );
  1931. switch (info.type) {
  1932. case "concatenated": {
  1933. if (info.wrapped) {
  1934. // A wrapped module declares exactly one shared-scope name: the
  1935. // lazy wrapper accessor holding its body. [2] claimed every
  1936. // identifier of that body, so findNewName avoids the ones that
  1937. // would shadow the accessor from inside it.
  1938. const namespaceFnName = findNewName(
  1939. "namespaceFn",
  1940. allUsedNames,
  1941. namespaceObjectUsedNames,
  1942. info.module.readableIdentifier(requestShortener)
  1943. );
  1944. allUsedNames.add(namespaceFnName);
  1945. topLevelDeclarations.add(namespaceFnName);
  1946. info.namespaceFnName = namespaceFnName;
  1947. // Every reference — `require()` and ESM import alike — reads the
  1948. // live exports object through the accessor, so the namespace is
  1949. // the call itself, not a variable. Not a declared name.
  1950. info.namespaceObjectName = `${namespaceFnName}()`;
  1951. } else {
  1952. const variables = /** @type {Scope} */ (info.moduleScope).variables;
  1953. for (const variable of variables) {
  1954. const name = variable.name;
  1955. const references = getAllReferences(variable);
  1956. const newName = _findNewName(name, info, references);
  1957. if (newName) {
  1958. const source = /** @type {ReplaceSource} */ (info.source);
  1959. /** @type {Set<Identifier>} */
  1960. const allIdentifiers = new Set();
  1961. for (const r of references) allIdentifiers.add(r.identifier);
  1962. for (const identifier of variable.identifiers) {
  1963. allIdentifiers.add(identifier);
  1964. }
  1965. for (const identifier of allIdentifiers) {
  1966. const r = /** @type {Range} */ (identifier.range);
  1967. const path = getPathInAst(
  1968. /** @type {NonNullable<ConcatenatedModuleInfo["ast"]>} */
  1969. (info.ast),
  1970. identifier
  1971. );
  1972. if (path && path.length > 1) {
  1973. const maybeProperty =
  1974. path[1].type === "AssignmentPattern" &&
  1975. path[1].left === path[0]
  1976. ? path[2]
  1977. : path[1];
  1978. if (
  1979. maybeProperty.type === "Property" &&
  1980. maybeProperty.shorthand
  1981. ) {
  1982. source.insert(r[1], `: ${newName}`);
  1983. continue;
  1984. }
  1985. }
  1986. source.replace(r[0], r[1] - 1, newName);
  1987. }
  1988. } else {
  1989. allUsedNames.add(name);
  1990. info.internalNames.set(name, name);
  1991. topLevelDeclarations.add(name);
  1992. }
  1993. }
  1994. /** @type {string} */
  1995. let namespaceObjectName;
  1996. if (info.namespaceExportSymbol) {
  1997. namespaceObjectName =
  1998. /** @type {string} */
  1999. (info.internalNames.get(info.namespaceExportSymbol));
  2000. } else {
  2001. namespaceObjectName = findNewName(
  2002. "namespaceObject",
  2003. allUsedNames,
  2004. namespaceObjectUsedNames,
  2005. info.module.readableIdentifier(requestShortener)
  2006. );
  2007. allUsedNames.add(namespaceObjectName);
  2008. }
  2009. info.namespaceObjectName = namespaceObjectName;
  2010. topLevelDeclarations.add(namespaceObjectName);
  2011. }
  2012. break;
  2013. }
  2014. case "external": {
  2015. const externalName = findNewName(
  2016. "",
  2017. allUsedNames,
  2018. namespaceObjectUsedNames,
  2019. info.module.readableIdentifier(requestShortener)
  2020. );
  2021. allUsedNames.add(externalName);
  2022. info.name = externalName;
  2023. topLevelDeclarations.add(externalName);
  2024. if (info.wrapped) {
  2025. const namespaceFnName = findNewName(
  2026. "namespaceFn",
  2027. allUsedNames,
  2028. namespaceObjectUsedNames,
  2029. info.module.readableIdentifier(requestShortener)
  2030. );
  2031. allUsedNames.add(namespaceFnName);
  2032. info.namespaceFnName = namespaceFnName;
  2033. topLevelDeclarations.add(namespaceFnName);
  2034. }
  2035. if (info.deferred) {
  2036. const externalName = findNewName(
  2037. "deferred",
  2038. allUsedNames,
  2039. namespaceObjectUsedNames,
  2040. info.module.readableIdentifier(requestShortener)
  2041. );
  2042. allUsedNames.add(externalName);
  2043. info.deferredName = externalName;
  2044. topLevelDeclarations.add(externalName);
  2045. const externalNameInterop = findNewName(
  2046. "deferredNamespaceObject",
  2047. allUsedNames,
  2048. namespaceObjectUsedNames,
  2049. info.module.readableIdentifier(requestShortener)
  2050. );
  2051. allUsedNames.add(externalNameInterop);
  2052. info.deferredNamespaceObjectName = externalNameInterop;
  2053. topLevelDeclarations.add(externalNameInterop);
  2054. }
  2055. break;
  2056. }
  2057. }
  2058. const buildMeta = /** @type {BuildMeta} */ (info.module.buildMeta);
  2059. if (buildMeta.exportsType !== "namespace") {
  2060. const externalNameInterop = findNewName(
  2061. "namespaceObject",
  2062. allUsedNames,
  2063. namespaceObjectUsedNames,
  2064. info.module.readableIdentifier(requestShortener)
  2065. );
  2066. allUsedNames.add(externalNameInterop);
  2067. info.interopNamespaceObjectName = externalNameInterop;
  2068. topLevelDeclarations.add(externalNameInterop);
  2069. }
  2070. if (
  2071. buildMeta.exportsType === "default" &&
  2072. buildMeta.defaultObject !== "redirect" &&
  2073. info.interopNamespaceObject2Used
  2074. ) {
  2075. const externalNameInterop = findNewName(
  2076. "namespaceObject2",
  2077. allUsedNames,
  2078. namespaceObjectUsedNames,
  2079. info.module.readableIdentifier(requestShortener)
  2080. );
  2081. allUsedNames.add(externalNameInterop);
  2082. info.interopNamespaceObject2Name = externalNameInterop;
  2083. topLevelDeclarations.add(externalNameInterop);
  2084. }
  2085. if (buildMeta.exportsType === "dynamic" || !buildMeta.exportsType) {
  2086. const externalNameInterop = findNewName(
  2087. "default",
  2088. allUsedNames,
  2089. namespaceObjectUsedNames,
  2090. info.module.readableIdentifier(requestShortener)
  2091. );
  2092. allUsedNames.add(externalNameInterop);
  2093. info.interopDefaultAccessName = externalNameInterop;
  2094. topLevelDeclarations.add(externalNameInterop);
  2095. }
  2096. }
  2097. // #endregion
  2098. // #region [4] LINK: resolve each cross-module reference token to the final
  2099. // name picked in [3] and patch it in. Must run after [3] — a reference can
  2100. // only be resolved once its target has been named
  2101. for (const info of moduleToInfoMap.values()) {
  2102. if (info.type !== "concatenated") continue;
  2103. if (!info.wrapped) {
  2104. // group references by name
  2105. /** @type {Map<string, Reference[]>} */
  2106. const referencesByName = new Map();
  2107. for (const reference of /** @type {Reference[]} */ (
  2108. info.unresolvedReferences
  2109. )) {
  2110. const name = reference.identifier.name;
  2111. let references = referencesByName.get(name);
  2112. if (references === undefined) {
  2113. referencesByName.set(name, (references = []));
  2114. }
  2115. references.push(reference);
  2116. }
  2117. for (const [name, references] of referencesByName) {
  2118. const match = ConcatenationScope.matchModuleReference(name);
  2119. if (match) {
  2120. const referencedInfo = modulesWithInfo[match.index];
  2121. if (referencedInfo.type === "reference") {
  2122. throw new Error("Module reference can't point to a reference");
  2123. }
  2124. const concatenationScope = /** @type {ConcatenatedModuleInfo} */ (
  2125. referencedInfo
  2126. ).concatenationScope;
  2127. const exportId = match.ids[0];
  2128. const specifier =
  2129. concatenationScope && concatenationScope.getRawExport(exportId);
  2130. if (specifier) {
  2131. const newName = _findNewNameForSpecifier(
  2132. specifier,
  2133. info,
  2134. references
  2135. );
  2136. const initFragmentChanged =
  2137. newName &&
  2138. concatenatedModuleInfo.call(
  2139. {
  2140. rawExportMap: new Map([
  2141. [exportId, /** @type {string} */ (newName)]
  2142. ])
  2143. },
  2144. /** @type {ConcatenatedModuleInfo} */ (referencedInfo)
  2145. );
  2146. if (initFragmentChanged) {
  2147. concatenationScope.setRawExportMap(exportId, newName);
  2148. }
  2149. }
  2150. // A whole-namespace value that escapes: when the module's exports
  2151. // are mangled, point it at a decoupled namespace object that keeps
  2152. // the original names so untracked access keeps working.
  2153. const escapeName =
  2154. match.mangleableNamespace && match.ids.length === 0
  2155. ? getEscapeNamespaceObjectName(referencedInfo)
  2156. : undefined;
  2157. const finalName =
  2158. escapeName !== undefined
  2159. ? escapeName
  2160. : getFinalName(
  2161. moduleGraph,
  2162. referencedInfo,
  2163. match.ids,
  2164. moduleToInfoMap,
  2165. runtime,
  2166. requestShortener,
  2167. runtimeTemplate,
  2168. neededNamespaceObjects,
  2169. match.call,
  2170. match.deferredImport,
  2171. !match.directImport,
  2172. /** @type {BuildMeta} */
  2173. (info.module.buildMeta).strictHarmonyModule,
  2174. match.asiSafe,
  2175. match.moduleExportsAccess
  2176. );
  2177. for (const reference of references) {
  2178. const r = /** @type {Range} */ (reference.identifier.range);
  2179. const source = /** @type {ReplaceSource} */ (info.source);
  2180. // range is extended by 2 chars to cover the appended "._"
  2181. source.replace(r[0], r[1] + 1, finalName);
  2182. }
  2183. }
  2184. }
  2185. } else {
  2186. // Wrapped bodies are not re-parsed: find their reference tokens
  2187. // textually. [2] scanned the same source, so this reuses its result.
  2188. /** @type {Map<string, string>} */
  2189. const finalNames = new Map();
  2190. const source = /** @type {ReplaceSource} */ (info.source);
  2191. for (const reference of ConcatenationScope.findModuleReferences(
  2192. /** @type {Source} */ (info.internalSource)
  2193. )) {
  2194. let finalName = finalNames.get(reference.name);
  2195. if (finalName === undefined) {
  2196. const match = ConcatenationScope.matchModuleReference(
  2197. reference.name
  2198. );
  2199. if (!match) continue;
  2200. const referencedInfo = modulesWithInfo[match.index];
  2201. if (referencedInfo.type === "reference") {
  2202. throw new Error("Module reference can't point to a reference");
  2203. }
  2204. // Same escaping whole-namespace rule as the hoisted branch above: a
  2205. // wrapped target resolves to its `X_namespaceFn()` exports object,
  2206. // whose keys are the mangled ones.
  2207. const escapeName =
  2208. match.mangleableNamespace && match.ids.length === 0
  2209. ? getEscapeNamespaceObjectName(referencedInfo)
  2210. : undefined;
  2211. finalName =
  2212. escapeName !== undefined
  2213. ? escapeName
  2214. : getFinalName(
  2215. moduleGraph,
  2216. referencedInfo,
  2217. match.ids,
  2218. moduleToInfoMap,
  2219. runtime,
  2220. requestShortener,
  2221. runtimeTemplate,
  2222. neededNamespaceObjects,
  2223. match.call,
  2224. match.deferredImport,
  2225. !match.directImport,
  2226. /** @type {BuildMeta} */
  2227. (info.module.buildMeta).strictHarmonyModule,
  2228. match.asiSafe,
  2229. match.moduleExportsAccess
  2230. );
  2231. finalNames.set(reference.name, finalName);
  2232. }
  2233. // token end is extended by 2 chars to cover the appended "._"
  2234. source.replace(reference.start, reference.end + 1, finalName);
  2235. }
  2236. }
  2237. }
  2238. // #endregion
  2239. // #region [5] COLLECT EXPORTS: split the root module's exports into used /
  2240. // unused / inlined. Used ones stay thunks — resolving one can still
  2241. // register a namespace object, which [7] must see
  2242. // Map with all root exposed used exports
  2243. /** @type {Map<string, (requestShortener: RequestShortener) => string>} */
  2244. const exportsMap = new Map();
  2245. // Set with all root exposed unused exports
  2246. /** @type {Set<string>} */
  2247. const unusedExports = new Set();
  2248. // Set with all root exposed exports that were substituted with inlined literals
  2249. /** @type {Set<string>} */
  2250. const inlinedExports = new Set();
  2251. const rootInfo =
  2252. /** @type {ConcatenatedModuleInfo} */
  2253. (moduleToInfoMap.get(this.rootModule));
  2254. const strictHarmonyModule =
  2255. /** @type {BuildMeta} */
  2256. (rootInfo.module.buildMeta).strictHarmonyModule;
  2257. const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module);
  2258. /** @type {Record<string, string>} */
  2259. const exportsFinalName = {};
  2260. for (const exportInfo of exportsInfo.orderedExports) {
  2261. const name = exportInfo.name;
  2262. if (exportInfo.provided === false) continue;
  2263. const used = exportInfo.getUsedName(undefined, runtime);
  2264. if (!used) {
  2265. unusedExports.add(name);
  2266. continue;
  2267. }
  2268. if (used instanceof InlinedUsedName) {
  2269. inlinedExports.add(name);
  2270. continue;
  2271. }
  2272. exportsMap.set(used, (requestShortener) => {
  2273. try {
  2274. const finalName = getFinalName(
  2275. moduleGraph,
  2276. rootInfo,
  2277. [name],
  2278. moduleToInfoMap,
  2279. runtime,
  2280. requestShortener,
  2281. runtimeTemplate,
  2282. neededNamespaceObjects,
  2283. false,
  2284. false,
  2285. false,
  2286. strictHarmonyModule,
  2287. true
  2288. );
  2289. exportsFinalName[used] = finalName;
  2290. return `/* ${
  2291. exportInfo.isReexport() ? "reexport" : "binding"
  2292. } */ ${finalName}`;
  2293. } catch (err) {
  2294. /** @type {Error} */
  2295. (err).message +=
  2296. `\nwhile generating the root export '${name}' (used name: '${used}')`;
  2297. throw err;
  2298. }
  2299. });
  2300. }
  2301. // #endregion
  2302. // #region [6] EMIT EXPORTS: first thing in the output — the exports getters
  2303. // must exist before any body runs, so circular importers see them
  2304. const result = new ConcatSource();
  2305. // add harmony compatibility flag (must be first because of possible circular dependencies)
  2306. let shouldAddHarmonyFlag = false;
  2307. const rootExportsInfo = moduleGraph.getExportsInfo(this);
  2308. if (
  2309. rootExportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused ||
  2310. rootExportsInfo.getReadOnlyExportInfo("__esModule").getUsed(runtime) !==
  2311. UsageState.Unused
  2312. ) {
  2313. shouldAddHarmonyFlag = true;
  2314. }
  2315. // define exports
  2316. if (exportsMap.size > 0) {
  2317. /** @type {string[]} */
  2318. const definitions = [];
  2319. for (const [key, value] of exportsMap) {
  2320. definitions.push(
  2321. `\n ${propertyName(key)}: ${runtimeTemplate.returningFunction(
  2322. value(requestShortener)
  2323. )}`
  2324. );
  2325. }
  2326. runtimeRequirements.add(RuntimeGlobals.exports);
  2327. runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
  2328. // Goes with the definitions below: whoever takes those over emits both,
  2329. // and the marker has to stay in front of them.
  2330. const harmonyFlagSource = shouldAddHarmonyFlag
  2331. ? `// ESM COMPAT FLAG\n${runtimeTemplate.defineEsModuleFlagStatement({
  2332. exportsArgument: this.exportsArgument,
  2333. runtimeRequirements
  2334. })}`
  2335. : "";
  2336. const exportsSource =
  2337. "\n// EXPORTS\n" +
  2338. `${RuntimeGlobals.definePropertyGetters}(${
  2339. this.exportsArgument
  2340. }, {${definitions.join(",")}\n});\n`;
  2341. const { onDemandExportsGeneration } =
  2342. ConcatenatedModule.getCompilationHooks(this.compilation);
  2343. if (
  2344. !onDemandExportsGeneration.call(
  2345. this,
  2346. runtimes,
  2347. `${harmonyFlagSource}${exportsSource}`,
  2348. exportsFinalName
  2349. )
  2350. ) {
  2351. result.add(harmonyFlagSource);
  2352. result.add(exportsSource);
  2353. }
  2354. }
  2355. // list unused exports
  2356. if (unusedExports.size > 0) {
  2357. result.add(
  2358. `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n`
  2359. );
  2360. }
  2361. // list inlined exports
  2362. if (inlinedExports.size > 0) {
  2363. result.add(
  2364. `\n// INLINED EXPORTS: ${joinIterableWithComma(inlinedExports)}\n`
  2365. );
  2366. }
  2367. // #endregion
  2368. // #region [7] BUILD NS: namespace object sources are built as strings here
  2369. // and emitted by [8]; an external's is emitted next to its import variable
  2370. // or accessor instead, which is defined later.
  2371. //
  2372. // generate decoupled namespace objects for escaping mangled namespaces:
  2373. // same getters as the regular namespace object, but keyed by the original
  2374. // export names so untracked access by name keeps working. Done before the
  2375. // regular namespace objects so any nested namespace they pull in is built.
  2376. /** @type {Map<ConcatenatedModuleInfo | ExternalModuleInfo, string>} */
  2377. const escapeNamespaceObjectSources = new Map();
  2378. for (const info of neededEscapeNamespaceObjects) {
  2379. /** @type {string[]} */
  2380. const nsObj = [];
  2381. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  2382. for (const exportInfo of exportsInfo.orderedExports) {
  2383. if (exportInfo.provided === false) continue;
  2384. const usedName = exportInfo.getUsedName(undefined, runtime);
  2385. if (!usedName) continue;
  2386. if (usedName instanceof InlinedUsedName) {
  2387. nsObj.push(
  2388. `\n ${propertyName(
  2389. exportInfo.name
  2390. )}: ${runtimeTemplate.returningFunction(
  2391. usedName.render(
  2392. Template.toNormalComment(
  2393. `inlined export ${propertyAccess([exportInfo.name])}`
  2394. )
  2395. )
  2396. )}`
  2397. );
  2398. } else {
  2399. // External (non-concatenated) modules are accessed through their
  2400. // import variable; concatenated ones resolve to an internal binding.
  2401. const finalName =
  2402. info.type === "external"
  2403. ? `${getExternalModuleExpr(info)}${propertyAccess([usedName])}`
  2404. : getFinalName(
  2405. moduleGraph,
  2406. info,
  2407. [exportInfo.name],
  2408. moduleToInfoMap,
  2409. runtime,
  2410. requestShortener,
  2411. runtimeTemplate,
  2412. neededNamespaceObjects,
  2413. false,
  2414. false,
  2415. undefined,
  2416. /** @type {BuildMeta} */
  2417. (info.module.buildMeta).strictHarmonyModule,
  2418. true
  2419. );
  2420. nsObj.push(
  2421. `\n ${propertyName(
  2422. exportInfo.name
  2423. )}: ${runtimeTemplate.returningFunction(finalName)}`
  2424. );
  2425. }
  2426. }
  2427. const name = /** @type {string} */ (info.escapeNamespaceObjectName);
  2428. const defineGetters =
  2429. nsObj.length > 0
  2430. ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join(
  2431. ","
  2432. )}\n});\n`
  2433. : "";
  2434. if (nsObj.length > 0) {
  2435. runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
  2436. }
  2437. escapeNamespaceObjectSources.set(
  2438. info,
  2439. `
  2440. // NAMESPACE OBJECT (decoupled): ${info.module.readableIdentifier(
  2441. requestShortener
  2442. )}
  2443. var ${name} = {};
  2444. ${RuntimeGlobals.makeNamespaceObject}(${name});
  2445. ${defineGetters}`
  2446. );
  2447. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  2448. }
  2449. // generate namespace objects
  2450. /** @type {Map<ConcatenatedModuleInfo, string>} */
  2451. const namespaceObjectSources = new Map();
  2452. for (const info of neededNamespaceObjects) {
  2453. if (
  2454. info.namespaceExportSymbol ||
  2455. // Skip constructing namespace object generated for wrapped module
  2456. info.wrapped
  2457. ) {
  2458. continue;
  2459. }
  2460. /** @type {string[]} */
  2461. const nsObj = [];
  2462. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  2463. for (const exportInfo of exportsInfo.orderedExports) {
  2464. if (exportInfo.provided === false) continue;
  2465. const usedName = exportInfo.getUsedName(undefined, runtime);
  2466. if (usedName && !(usedName instanceof InlinedUsedName)) {
  2467. const finalName = getFinalName(
  2468. moduleGraph,
  2469. info,
  2470. [exportInfo.name],
  2471. moduleToInfoMap,
  2472. runtime,
  2473. requestShortener,
  2474. runtimeTemplate,
  2475. neededNamespaceObjects,
  2476. false,
  2477. false,
  2478. undefined,
  2479. /** @type {BuildMeta} */
  2480. (info.module.buildMeta).strictHarmonyModule,
  2481. true
  2482. );
  2483. nsObj.push(
  2484. `\n ${propertyName(
  2485. usedName
  2486. )}: ${runtimeTemplate.returningFunction(finalName)}`
  2487. );
  2488. }
  2489. }
  2490. const name = info.namespaceObjectName;
  2491. const defineGetters =
  2492. nsObj.length > 0
  2493. ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join(
  2494. ","
  2495. )}\n});\n`
  2496. : "";
  2497. if (nsObj.length > 0) {
  2498. runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
  2499. }
  2500. namespaceObjectSources.set(
  2501. info,
  2502. `
  2503. // NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)}
  2504. var ${name} = {};
  2505. ${RuntimeGlobals.makeNamespaceObject}(${name});
  2506. ${defineGetters}`
  2507. );
  2508. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  2509. }
  2510. // #endregion
  2511. // #region [8] DEFINE: define required namespace objects and wrapper
  2512. // (must be before evaluation modules — a cycle member calls another's
  2513. // accessor before that module's own position in the order)
  2514. // wrapper accessors are only called later, so their definitions may be
  2515. // emitted in a stable order of their own instead of concatenation order
  2516. /** @type {(ConcatenatedModuleInfo | ExternalModuleInfo)[]} */
  2517. const wrappedInfos = [];
  2518. for (const info of modulesWithInfo) {
  2519. if (
  2520. (info.type === "concatenated" || info.type === "external") &&
  2521. info.wrapped
  2522. ) {
  2523. wrappedInfos.push(info);
  2524. }
  2525. }
  2526. const compareWrappedModules = compareModulesByFullName(
  2527. runtimeTemplate.compilation.compiler
  2528. );
  2529. wrappedInfos.sort((a, b) => compareWrappedModules(a.module, b.module));
  2530. for (const info of wrappedInfos) {
  2531. if (info.type === "concatenated") {
  2532. runtimeRequirements.add(RuntimeGlobals.concatenationWrap);
  2533. result.add(
  2534. `\n// MODULE: ${info.module.readableIdentifier(
  2535. requestShortener
  2536. )}\nvar ${info.namespaceFnName} = /*#__PURE__*/${
  2537. RuntimeGlobals.concatenationWrap
  2538. }(function(${info.module.moduleArgument}, ${
  2539. info.module.exportsArgument
  2540. }) {\n`
  2541. );
  2542. result.add(/** @type {ReplaceSource} */ (info.source));
  2543. // A generated body (json, asset, html) binds its value to a local
  2544. // instead of writing exports; hand that local to the accessor. The
  2545. // name is verbatim: a wrapped body is not scope-analysed, so it keeps
  2546. // the reserved symbol the generator registered.
  2547. result.add(
  2548. info.namespaceExportSymbol
  2549. ? `\n${info.module.moduleArgument}.exports = ${info.namespaceExportSymbol};\n});\n`
  2550. : "\n});\n"
  2551. );
  2552. // its getters call the accessor lazily, so this may sit right after it
  2553. const escapeSource = escapeNamespaceObjectSources.get(info);
  2554. if (escapeSource) result.add(escapeSource);
  2555. } else if (info.type === "external") {
  2556. runtimeRequirements.add(RuntimeGlobals.require);
  2557. const { runtimeCondition } = info;
  2558. const condition = runtimeTemplate.runtimeConditionExpression({
  2559. chunkGraph,
  2560. runtimeCondition,
  2561. runtime,
  2562. runtimeRequirements
  2563. });
  2564. const moduleId = JSON.stringify(chunkGraph.getModuleId(info.module));
  2565. const body =
  2566. condition === "true"
  2567. ? `return ${RuntimeGlobals.require}(${moduleId});`
  2568. : `if (${condition}) return ${RuntimeGlobals.require}(${moduleId});`;
  2569. result.add(
  2570. `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
  2571. requestShortener
  2572. )}\nvar ${info.namespaceFnName} = ${runtimeTemplate.basicFunction(
  2573. "",
  2574. body
  2575. )};\n`
  2576. );
  2577. const escapeSource = escapeNamespaceObjectSources.get(info);
  2578. if (escapeSource) result.add(escapeSource);
  2579. }
  2580. }
  2581. for (const info of modulesWithInfo) {
  2582. if (info.type === "concatenated") {
  2583. if (!info.wrapped) {
  2584. const source = namespaceObjectSources.get(info);
  2585. if (source) result.add(source);
  2586. const escapeSource = escapeNamespaceObjectSources.get(
  2587. /** @type {ConcatenatedModuleInfo} */ (info)
  2588. );
  2589. if (escapeSource) result.add(escapeSource);
  2590. }
  2591. } else if (info.type === "external" && info.deferred) {
  2592. const moduleId = JSON.stringify(chunkGraph.getModuleId(info.module));
  2593. const loader = getOptimizedDeferredModule(
  2594. moduleId,
  2595. getExportsType(
  2596. moduleGraph,
  2597. info,
  2598. /** @type {BuildMeta} */
  2599. (this.rootModule.buildMeta).strictHarmonyModule
  2600. ),
  2601. // an async module will opt-out of the concat module optimization.
  2602. [],
  2603. // A closure member absorbed into this concatenation shares this
  2604. // module's runtime id (and thus its `evaluating` flag); resolve it
  2605. // to that id instead of the member's now-absent standalone id.
  2606. getDeferredCycleModuleIds(
  2607. getDeferredCycleModules(moduleGraph, info.module),
  2608. (mod) =>
  2609. moduleToInfoMap.has(mod)
  2610. ? chunkGraph.getModuleId(this)
  2611. : chunkGraph.getModuleId(mod)
  2612. ),
  2613. runtimeRequirements
  2614. );
  2615. runtimeRequirements.add(RuntimeGlobals.require);
  2616. result.add(
  2617. `\n// DEFERRED EXTERNAL MODULE: ${info.module.readableIdentifier(
  2618. requestShortener
  2619. )}\nvar ${info.deferredName} = ${loader};`
  2620. );
  2621. if (info.deferredNamespaceObjectUsed) {
  2622. runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject);
  2623. result.add(
  2624. `\nvar ${info.deferredNamespaceObjectName} = /*#__PURE__*/${
  2625. RuntimeGlobals.makeDeferredNamespaceObject
  2626. }(${JSON.stringify(
  2627. chunkGraph.getModuleId(info.module)
  2628. )}, ${getMakeDeferredNamespaceModeFromExportsType(
  2629. getExportsType(moduleGraph, info, strictHarmonyModule)
  2630. )});`
  2631. );
  2632. }
  2633. }
  2634. }
  2635. // #endregion
  2636. // #region [9] EVALUATE: emit the bodies in concatenation order and collect
  2637. // what they need — runtime requirements, chunk init fragments, interop
  2638. /** @type {InitFragment<ChunkRenderContext>[]} */
  2639. const chunkInitFragments = [];
  2640. for (const rawInfo of modulesWithInfo) {
  2641. /** @type {undefined | string} */
  2642. let name;
  2643. let isConditional = false;
  2644. const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo;
  2645. switch (info.type) {
  2646. case "concatenated": {
  2647. name = info.namespaceObjectName;
  2648. // wrapped bodies are emitted above, evaluated at their call sites
  2649. if (info.wrapped && info.eager) {
  2650. // This slot is the module's place in evaluation order; calling from
  2651. // the importing body would run it too late.
  2652. result.add(
  2653. `\n;// ${info.module.readableIdentifier(
  2654. requestShortener
  2655. )}\n${info.namespaceFnName}();\n`
  2656. );
  2657. } else if (!info.wrapped) {
  2658. result.add(
  2659. `\n;// ${info.module.readableIdentifier(requestShortener)}\n`
  2660. );
  2661. result.add(/** @type {ReplaceSource} */ (info.source));
  2662. }
  2663. if (info.chunkInitFragments) {
  2664. for (const f of info.chunkInitFragments) chunkInitFragments.push(f);
  2665. }
  2666. if (info.runtimeRequirements) {
  2667. for (const r of info.runtimeRequirements) {
  2668. // Wrapped module supplies module/exports/this itself
  2669. if (
  2670. info.wrapped &&
  2671. (r === RuntimeGlobals.module ||
  2672. r === RuntimeGlobals.exports ||
  2673. r === RuntimeGlobals.thisAsExports)
  2674. ) {
  2675. continue;
  2676. }
  2677. runtimeRequirements.add(r);
  2678. }
  2679. }
  2680. break;
  2681. }
  2682. case "external": {
  2683. name = getExternalModuleExpr(info);
  2684. // deferred and wrapped cases are handled in the "const info of modulesWithInfo" loop above
  2685. if (!info.deferred && !info.wrapped) {
  2686. result.add(
  2687. `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
  2688. requestShortener
  2689. )}\n`
  2690. );
  2691. runtimeRequirements.add(RuntimeGlobals.require);
  2692. const { runtimeCondition } =
  2693. /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */
  2694. (rawInfo);
  2695. const condition = runtimeTemplate.runtimeConditionExpression({
  2696. chunkGraph,
  2697. runtimeCondition,
  2698. runtime,
  2699. runtimeRequirements
  2700. });
  2701. if (condition !== "true") {
  2702. isConditional = true;
  2703. result.add(`if (${condition}) {\n`);
  2704. }
  2705. const moduleId = JSON.stringify(
  2706. chunkGraph.getModuleId(info.module)
  2707. );
  2708. // External module bindings may be wrapped in
  2709. // runtime-condition `if` blocks but referenced outside,
  2710. // so they must remain function-scoped (`var`).
  2711. result.add(`var ${info.name} = __webpack_require__(${moduleId});`);
  2712. // Decoupled namespace object for an escaping mangled external
  2713. // module must come after its import variable is defined.
  2714. const escapeSource = escapeNamespaceObjectSources.get(info);
  2715. if (escapeSource) result.add(escapeSource);
  2716. } else if (info.wrapped && info.eager) {
  2717. result.add(
  2718. `\n;// EXTERNAL MODULE: ${info.module.readableIdentifier(
  2719. requestShortener
  2720. )}\n${info.namespaceFnName}();\n`
  2721. );
  2722. }
  2723. // If a module is deferred in other places, but used as non-deferred here,
  2724. // the module itself will be emitted as mod_deferred (in the case "external"),
  2725. // we need to emit an extra import declaration to evaluate it in order.
  2726. const { nonDeferAccess } =
  2727. /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */
  2728. (rawInfo);
  2729. if (info.deferred && nonDeferAccess && !info.wrapped) {
  2730. result.add(
  2731. `\n// non-deferred import to a deferred module (${info.module.readableIdentifier(
  2732. requestShortener
  2733. )})\nvar ${info.name} = ${info.deferredName}.a;`
  2734. );
  2735. }
  2736. break;
  2737. }
  2738. default:
  2739. // @ts-expect-error never is expected here
  2740. throw new Error(`Unsupported concatenation entry type ${info.type}`);
  2741. }
  2742. // Building a wrapped module's interop object here would evaluate its body
  2743. // at the top level and break require() cycles, so defer it behind a
  2744. // hoisted function. The memo lives on the function object: it keeps the
  2745. // identity stable without claiming a second top-level name.
  2746. /**
  2747. * @param {string} interopName interop variable name
  2748. * @param {string} expr interop object expression
  2749. * @returns {string} the declaration
  2750. */
  2751. const declareInterop = (interopName, expr) =>
  2752. info.wrapped
  2753. ? `\nfunction ${interopName}() { return ${interopName}.c || (${interopName}.c = ${expr}); }`
  2754. : `\nvar ${interopName} = /*#__PURE__*/${expr};`;
  2755. if (info.interopNamespaceObjectUsed) {
  2756. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  2757. result.add(
  2758. declareInterop(
  2759. /** @type {string} */ (info.interopNamespaceObjectName),
  2760. `${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2)`
  2761. )
  2762. );
  2763. }
  2764. if (info.interopNamespaceObject2Used) {
  2765. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  2766. result.add(
  2767. declareInterop(
  2768. /** @type {string} */ (info.interopNamespaceObject2Name),
  2769. `${RuntimeGlobals.createFakeNamespaceObject}(${name})`
  2770. )
  2771. );
  2772. }
  2773. if (info.interopDefaultAccessUsed) {
  2774. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  2775. result.add(
  2776. declareInterop(
  2777. /** @type {string} */ (info.interopDefaultAccessName),
  2778. `${RuntimeGlobals.compatGetDefaultExport}(${name})`
  2779. )
  2780. );
  2781. }
  2782. if (isConditional) {
  2783. result.add("\n}");
  2784. }
  2785. }
  2786. // #endregion
  2787. // #region [10] RESULT: topLevelDeclarations and freeNames let consumers
  2788. // (mangling, an outer concatenation) reason about this source unparsed
  2789. /** @type {CodeGenerationResultData} */
  2790. const data = new Map();
  2791. if (chunkInitFragments.length > 0) {
  2792. data.set("chunkInitFragments", chunkInitFragments);
  2793. }
  2794. data.set("topLevelDeclarations", topLevelDeclarations);
  2795. data.set("freeNames", freeNames);
  2796. /** @type {CodeGenerationResult} */
  2797. const resultEntry = {
  2798. sources: new Map([[JAVASCRIPT_TYPE, new CachedSource(result)]]),
  2799. data,
  2800. runtimeRequirements
  2801. };
  2802. // #endregion
  2803. return resultEntry;
  2804. }
  2805. /**
  2806. * @param {ModuleToInfoMap} modulesMap modulesMap
  2807. * @param {ModuleInfo} info info
  2808. * @param {DependencyTemplates} dependencyTemplates dependencyTemplates
  2809. * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate
  2810. * @param {ModuleGraph} moduleGraph moduleGraph
  2811. * @param {ChunkGraph} chunkGraph chunkGraph
  2812. * @param {RuntimeSpec} runtime runtime
  2813. * @param {RuntimeSpec[]} runtimes runtimes
  2814. * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults
  2815. * @param {UsedNames} usedNames used names
  2816. */
  2817. _analyseModule(
  2818. modulesMap,
  2819. info,
  2820. dependencyTemplates,
  2821. runtimeTemplate,
  2822. moduleGraph,
  2823. chunkGraph,
  2824. runtime,
  2825. runtimes,
  2826. codeGenerationResults,
  2827. usedNames
  2828. ) {
  2829. if (info.type === "concatenated") {
  2830. const m = info.module;
  2831. if (info.wrapped) {
  2832. // the wrapper isolates the body's top-level declarations, so no
  2833. // renaming is needed -- only a concatenation scope, to rewrite in-scope
  2834. // `require()` targets to accessor references. [2] claims its identifiers
  2835. // textually in place of the scope analysis skipped here.
  2836. const concatenationScope = new ConcatenationScope(
  2837. modulesMap,
  2838. info,
  2839. usedNames
  2840. );
  2841. info.concatenationScope = concatenationScope;
  2842. const codeGenResult = m.codeGeneration({
  2843. dependencyTemplates,
  2844. runtimeTemplate,
  2845. moduleGraph,
  2846. chunkGraph,
  2847. runtime,
  2848. runtimes,
  2849. concatenationScope,
  2850. codeGenerationResults,
  2851. sourceTypes: JAVASCRIPT_TYPES
  2852. });
  2853. const source =
  2854. /** @type {Source} */
  2855. (codeGenResult.sources.get(JAVASCRIPT_TYPE));
  2856. const data = codeGenResult.data;
  2857. info.runtimeRequirements =
  2858. /** @type {ReadOnlyRuntimeRequirements} */
  2859. (codeGenResult.runtimeRequirements);
  2860. info.internalSource = source;
  2861. info.source = new ReplaceSource(source);
  2862. info.chunkInitFragments = data && data.get("chunkInitFragments");
  2863. } else {
  2864. try {
  2865. // Create a concatenation scope to track and capture information
  2866. const concatenationScope = new ConcatenationScope(
  2867. modulesMap,
  2868. info,
  2869. usedNames
  2870. );
  2871. // Not cached: Compilation memoizes the outer codeGeneration per
  2872. // (module, runtime), so inner generation never recomputes usefully.
  2873. const codeGenResult = m.codeGeneration({
  2874. dependencyTemplates,
  2875. runtimeTemplate,
  2876. moduleGraph,
  2877. chunkGraph,
  2878. runtime,
  2879. runtimes,
  2880. concatenationScope,
  2881. codeGenerationResults,
  2882. sourceTypes: JAVASCRIPT_TYPES
  2883. });
  2884. const source =
  2885. /** @type {Source} */
  2886. (codeGenResult.sources.get(JAVASCRIPT_TYPE));
  2887. const data = codeGenResult.data;
  2888. const chunkInitFragments = data && data.get("chunkInitFragments");
  2889. const code = source.source().toString();
  2890. /** @type {Program} */
  2891. let ast;
  2892. try {
  2893. const { experiments } = this.compilation.options;
  2894. ({ ast } = JavascriptParser._parse(
  2895. code,
  2896. {
  2897. sourceType: "module",
  2898. ranges: true,
  2899. // generated code contains phase imports when the experiments are on
  2900. importPhases: Boolean(
  2901. experiments.deferImport || experiments.sourceImport
  2902. )
  2903. },
  2904. JavascriptParser._getModuleParseFunction(this.compilation, m)
  2905. ));
  2906. } catch (_err) {
  2907. const err =
  2908. /** @type {Error & { loc?: { line: number, column: number } }} */
  2909. (_err);
  2910. if (
  2911. err.loc &&
  2912. typeof err.loc === "object" &&
  2913. typeof err.loc.line === "number"
  2914. ) {
  2915. const lineNumber = err.loc.line;
  2916. const lines = code.split("\n");
  2917. err.message += `\n| ${lines
  2918. .slice(Math.max(0, lineNumber - 3), lineNumber + 2)
  2919. .join("\n| ")}`;
  2920. }
  2921. throw err;
  2922. }
  2923. const analysis = analyzeScope(ast);
  2924. const resultSource = new ReplaceSource(source);
  2925. info.runtimeRequirements =
  2926. /** @type {ReadOnlyRuntimeRequirements} */
  2927. (codeGenResult.runtimeRequirements);
  2928. info.ast = ast;
  2929. info.internalSource = source;
  2930. info.source = resultSource;
  2931. info.chunkInitFragments = chunkInitFragments;
  2932. info.globalScope = analysis.globalScope;
  2933. info.moduleScope = analysis.moduleScope;
  2934. info.unresolvedReferences = analysis.unresolvedReferences;
  2935. info.concatenationScope = concatenationScope;
  2936. } catch (err) {
  2937. /** @type {Error} */
  2938. (err).message +=
  2939. `\nwhile analyzing module ${m.identifier()} for concatenation`;
  2940. throw err;
  2941. }
  2942. }
  2943. }
  2944. }
  2945. /**
  2946. * @param {ModuleGraph} moduleGraph the module graph
  2947. * @param {RuntimeSpec} runtime the runtime
  2948. * @returns {[ModuleInfoOrReference[], ModuleToInfoMap]} module info items
  2949. */
  2950. _getModulesWithInfo(moduleGraph, runtime) {
  2951. const orderedConcatenationList = this._createConcatenationList(
  2952. this.rootModule,
  2953. this._modules,
  2954. runtime,
  2955. moduleGraph
  2956. );
  2957. /** @type {ModuleToInfoMap} */
  2958. const map = new Map();
  2959. const list = orderedConcatenationList.map((info, index) => {
  2960. let item = map.get(info.module);
  2961. if (item === undefined) {
  2962. switch (info.type) {
  2963. case "concatenated":
  2964. item = {
  2965. type: "concatenated",
  2966. wrapped: info.wrapped,
  2967. eager: false,
  2968. module: info.module,
  2969. index,
  2970. namespaceFnName: undefined,
  2971. ast: undefined,
  2972. chunkInitFragments: undefined,
  2973. internalSource: undefined,
  2974. runtimeRequirements: undefined,
  2975. source: undefined,
  2976. globalScope: undefined,
  2977. unresolvedReferences: undefined,
  2978. moduleScope: undefined,
  2979. internalNames: new Map(),
  2980. exportMap: undefined,
  2981. rawExportMap: undefined,
  2982. namespaceExportSymbol: undefined,
  2983. namespaceObjectName: undefined,
  2984. escapeNamespaceObjectName: undefined,
  2985. interopNamespaceObjectUsed: false,
  2986. interopNamespaceObjectName: undefined,
  2987. interopNamespaceObject2Used: false,
  2988. interopNamespaceObject2Name: undefined,
  2989. interopDefaultAccessUsed: false,
  2990. interopDefaultAccessName: undefined,
  2991. concatenationScope: undefined,
  2992. exportsTypeStrict: undefined,
  2993. exportsTypeNonStrict: undefined
  2994. };
  2995. break;
  2996. case "external":
  2997. item = {
  2998. type: "external",
  2999. wrapped: info.wrapped,
  3000. eager: false,
  3001. module: info.module,
  3002. runtimeCondition: info.runtimeCondition,
  3003. nonDeferAccess: info.nonDeferAccess,
  3004. index,
  3005. name: undefined,
  3006. namespaceFnName: undefined,
  3007. escapeNamespaceObjectName: undefined,
  3008. deferredName: undefined,
  3009. interopNamespaceObjectUsed: false,
  3010. interopNamespaceObjectName: undefined,
  3011. interopNamespaceObject2Used: false,
  3012. interopNamespaceObject2Name: undefined,
  3013. interopDefaultAccessUsed: false,
  3014. interopDefaultAccessName: undefined,
  3015. deferred: this.compilation.options.experiments.deferImport
  3016. ? moduleGraph.isDeferred(info.module)
  3017. : false,
  3018. deferredNamespaceObjectName: undefined,
  3019. deferredNamespaceObjectUsed: false,
  3020. exportsTypeStrict: undefined,
  3021. exportsTypeNonStrict: undefined
  3022. };
  3023. break;
  3024. default:
  3025. throw new Error(
  3026. `Unsupported concatenation entry type ${info.type}`
  3027. );
  3028. }
  3029. map.set(
  3030. /** @type {ModuleInfo} */ (item).module,
  3031. /** @type {ModuleInfo} */ (item)
  3032. );
  3033. return /** @type {ModuleInfo} */ (item);
  3034. }
  3035. /** @type {ReferenceToModuleInfo} */
  3036. const ref = {
  3037. type: "reference",
  3038. runtimeCondition: info.runtimeCondition,
  3039. nonDeferAccess: info.nonDeferAccess,
  3040. target: item
  3041. };
  3042. return ref;
  3043. });
  3044. return [list, map];
  3045. }
  3046. /**
  3047. * Updates the hash with the data contributed by this instance.
  3048. * @param {Hash} hash the hash used to track dependencies
  3049. * @param {UpdateHashContext} context context
  3050. * @returns {void}
  3051. */
  3052. updateHash(hash, context) {
  3053. const { chunkGraph, runtime } = context;
  3054. for (const info of this._createConcatenationList(
  3055. this.rootModule,
  3056. this._modules,
  3057. intersectRuntime(runtime, this._runtime),
  3058. chunkGraph.moduleGraph
  3059. )) {
  3060. switch (info.type) {
  3061. case "concatenated":
  3062. info.module.updateHash(hash, context);
  3063. break;
  3064. case "external":
  3065. hash.update(
  3066. `${chunkGraph.getModuleId(info.module)}|${runtimeConditionToString(
  3067. info.runtimeCondition
  3068. )}|${info.nonDeferAccess ? "1" : "0"}|${
  3069. this.compilation.options.experiments.deferImport &&
  3070. chunkGraph.moduleGraph.isDeferred(info.module)
  3071. ? "1"
  3072. : "0"
  3073. }`
  3074. );
  3075. break;
  3076. }
  3077. }
  3078. super.updateHash(hash, context);
  3079. }
  3080. /**
  3081. * @param {ObjectDeserializerContext} context context
  3082. * @returns {ConcatenatedModule} ConcatenatedModule
  3083. */
  3084. static deserialize(context) {
  3085. const obj = new ConcatenatedModule({
  3086. identifier: /** @type {EXPECTED_ANY} */ (undefined),
  3087. rootModule: /** @type {EXPECTED_ANY} */ (undefined),
  3088. modules: /** @type {EXPECTED_ANY} */ (undefined),
  3089. runtime: undefined,
  3090. compilation: /** @type {EXPECTED_ANY} */ (undefined)
  3091. });
  3092. obj.deserialize(context);
  3093. return obj;
  3094. }
  3095. }
  3096. ConcatenatedModule.getCompilationHooks = createHooksRegistry(
  3097. () =>
  3098. /** @type {ConcatenateModuleHooks} */ ({
  3099. onDemandExportsGeneration: new SyncBailHook([
  3100. "module",
  3101. "runtimes",
  3102. "exportsFinalName",
  3103. "exportsSource"
  3104. ]),
  3105. concatenatedModuleInfo: new SyncBailHook([
  3106. "updatedInfo",
  3107. "concatenatedModuleInfo"
  3108. ])
  3109. })
  3110. );
  3111. makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule");
  3112. /** @type {WeakMap<Compilation, WeakMap<Module, ConcatenatedModule>>} */
  3113. const absorbedBy = new WeakMap();
  3114. /**
  3115. * The module the chunk graph holds for `module`: concatenation replaces every module
  3116. * it absorbs with one `ConcatenatedModule`, so an absorbed module is itself in no
  3117. * chunk and no runtime, and asking the chunk graph about it answers about nothing.
  3118. * @param {Compilation} compilation the compilation
  3119. * @param {Module} module a module, possibly absorbed by concatenation
  3120. * @returns {Module} the module the chunk graph holds, or `module` itself
  3121. */
  3122. ConcatenatedModule.getChunkGraphModule = (compilation, module) => {
  3123. let map = absorbedBy.get(compilation);
  3124. if (map === undefined) {
  3125. map = new WeakMap();
  3126. for (const candidate of compilation.modules) {
  3127. if (candidate instanceof ConcatenatedModule) {
  3128. for (const inner of candidate._modules) {
  3129. map.set(inner, candidate);
  3130. }
  3131. }
  3132. }
  3133. absorbedBy.set(compilation, map);
  3134. }
  3135. const outer = map.get(module);
  3136. return outer === undefined ? module : outer;
  3137. };
  3138. module.exports = ConcatenatedModule;