ConcatenatedModule.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const eslintScope = require("eslint-scope");
  7. const Referencer = require("eslint-scope/lib/referencer");
  8. const {
  9. CachedSource,
  10. ConcatSource,
  11. ReplaceSource
  12. } = require("webpack-sources");
  13. const ConcatenationScope = require("../ConcatenationScope");
  14. const { UsageState } = require("../ExportsInfo");
  15. const Module = require("../Module");
  16. const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants");
  17. const RuntimeGlobals = require("../RuntimeGlobals");
  18. const Template = require("../Template");
  19. const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
  20. const JavascriptParser = require("../javascript/JavascriptParser");
  21. const { equals } = require("../util/ArrayHelpers");
  22. const LazySet = require("../util/LazySet");
  23. const { concatComparators } = require("../util/comparators");
  24. const createHash = require("../util/createHash");
  25. const { makePathsRelative } = require("../util/identifier");
  26. const makeSerializable = require("../util/makeSerializable");
  27. const propertyAccess = require("../util/propertyAccess");
  28. const {
  29. filterRuntime,
  30. intersectRuntime,
  31. mergeRuntimeCondition,
  32. mergeRuntimeConditionNonFalse,
  33. runtimeConditionToString,
  34. subtractRuntimeCondition
  35. } = require("../util/runtime");
  36. /** @typedef {import("eslint-scope").Scope} Scope */
  37. /** @typedef {import("webpack-sources").Source} Source */
  38. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  39. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  40. /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
  41. /** @typedef {import("../Compilation")} Compilation */
  42. /** @typedef {import("../Dependency")} Dependency */
  43. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  44. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  45. /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
  46. /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
  47. /** @template T @typedef {import("../InitFragment")<T>} InitFragment */
  48. /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
  49. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  50. /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
  51. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  52. /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
  53. /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */
  54. /** @typedef {import("../RequestShortener")} RequestShortener */
  55. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  56. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  57. /** @typedef {import("../WebpackError")} WebpackError */
  58. /** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
  59. /** @typedef {import("../util/Hash")} Hash */
  60. /** @typedef {typeof import("../util/Hash")} HashConstructor */
  61. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  62. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  63. // fix eslint-scope to support class properties correctly
  64. // cspell:word Referencer
  65. const ReferencerClass = Referencer;
  66. if (!ReferencerClass.prototype.PropertyDefinition) {
  67. ReferencerClass.prototype.PropertyDefinition =
  68. ReferencerClass.prototype.Property;
  69. }
  70. /**
  71. * @typedef {Object} ReexportInfo
  72. * @property {Module} module
  73. * @property {string[]} export
  74. */
  75. /** @typedef {RawBinding | SymbolBinding} Binding */
  76. /**
  77. * @typedef {Object} RawBinding
  78. * @property {ModuleInfo} info
  79. * @property {string} rawName
  80. * @property {string=} comment
  81. * @property {string[]} ids
  82. * @property {string[]} exportName
  83. */
  84. /**
  85. * @typedef {Object} SymbolBinding
  86. * @property {ConcatenatedModuleInfo} info
  87. * @property {string} name
  88. * @property {string=} comment
  89. * @property {string[]} ids
  90. * @property {string[]} exportName
  91. */
  92. /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */
  93. /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo } ModuleInfoOrReference */
  94. /**
  95. * @typedef {Object} ConcatenatedModuleInfo
  96. * @property {"concatenated"} type
  97. * @property {Module} module
  98. * @property {number} index
  99. * @property {Object} ast
  100. * @property {Source} internalSource
  101. * @property {ReplaceSource} source
  102. * @property {InitFragment<ChunkRenderContext>[]=} chunkInitFragments
  103. * @property {Iterable<string>} runtimeRequirements
  104. * @property {Scope} globalScope
  105. * @property {Scope} moduleScope
  106. * @property {Map<string, string>} internalNames
  107. * @property {Map<string, string>} exportMap
  108. * @property {Map<string, string>} rawExportMap
  109. * @property {string=} namespaceExportSymbol
  110. * @property {string} namespaceObjectName
  111. * @property {boolean} interopNamespaceObjectUsed
  112. * @property {string} interopNamespaceObjectName
  113. * @property {boolean} interopNamespaceObject2Used
  114. * @property {string} interopNamespaceObject2Name
  115. * @property {boolean} interopDefaultAccessUsed
  116. * @property {string} interopDefaultAccessName
  117. */
  118. /**
  119. * @typedef {Object} ExternalModuleInfo
  120. * @property {"external"} type
  121. * @property {Module} module
  122. * @property {RuntimeSpec | boolean} runtimeCondition
  123. * @property {number} index
  124. * @property {string} name
  125. * @property {boolean} interopNamespaceObjectUsed
  126. * @property {string} interopNamespaceObjectName
  127. * @property {boolean} interopNamespaceObject2Used
  128. * @property {string} interopNamespaceObject2Name
  129. * @property {boolean} interopDefaultAccessUsed
  130. * @property {string} interopDefaultAccessName
  131. */
  132. /**
  133. * @typedef {Object} ReferenceToModuleInfo
  134. * @property {"reference"} type
  135. * @property {RuntimeSpec | boolean} runtimeCondition
  136. * @property {ConcatenatedModuleInfo | ExternalModuleInfo} target
  137. */
  138. const RESERVED_NAMES = new Set(
  139. [
  140. // internal names (should always be renamed)
  141. ConcatenationScope.DEFAULT_EXPORT,
  142. ConcatenationScope.NAMESPACE_OBJECT_EXPORT,
  143. // keywords
  144. "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue",
  145. "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float",
  146. "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null",
  147. "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw",
  148. "throws,transient,true,try,typeof,var,void,volatile,while,with,yield",
  149. // commonjs/amd
  150. "module,__dirname,__filename,exports,require,define",
  151. // js globals
  152. "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math",
  153. "NaN,name,Number,Object,prototype,String,toString,undefined,valueOf",
  154. // browser globals
  155. "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout",
  156. "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent",
  157. "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape",
  158. "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location",
  159. "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering",
  160. "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat",
  161. "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll",
  162. "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape",
  163. "untaint,window",
  164. // window events
  165. "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit"
  166. ]
  167. .join(",")
  168. .split(",")
  169. );
  170. const createComparator = (property, comparator) => (a, b) =>
  171. comparator(a[property], b[property]);
  172. const compareNumbers = (a, b) => {
  173. if (isNaN(a)) {
  174. if (!isNaN(b)) {
  175. return 1;
  176. }
  177. } else {
  178. if (isNaN(b)) {
  179. return -1;
  180. }
  181. if (a !== b) {
  182. return a < b ? -1 : 1;
  183. }
  184. }
  185. return 0;
  186. };
  187. const bySourceOrder = createComparator("sourceOrder", compareNumbers);
  188. const byRangeStart = createComparator("rangeStart", compareNumbers);
  189. const joinIterableWithComma = iterable => {
  190. // This is more performant than Array.from().join(", ")
  191. // as it doesn't create an array
  192. let str = "";
  193. let first = true;
  194. for (const item of iterable) {
  195. if (first) {
  196. first = false;
  197. } else {
  198. str += ", ";
  199. }
  200. str += item;
  201. }
  202. return str;
  203. };
  204. /**
  205. * @typedef {Object} ConcatenationEntry
  206. * @property {"concatenated" | "external"} type
  207. * @property {Module} module
  208. * @property {RuntimeSpec | boolean} runtimeCondition
  209. */
  210. /**
  211. * @param {ModuleGraph} moduleGraph the module graph
  212. * @param {ModuleInfo} info module info
  213. * @param {string[]} exportName exportName
  214. * @param {Map<Module, ModuleInfo>} moduleToInfoMap moduleToInfoMap
  215. * @param {RuntimeSpec} runtime for which runtime
  216. * @param {RequestShortener} requestShortener the request shortener
  217. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  218. * @param {Set<ConcatenatedModuleInfo>} neededNamespaceObjects modules for which a namespace object should be generated
  219. * @param {boolean} asCall asCall
  220. * @param {boolean} strictHarmonyModule strictHarmonyModule
  221. * @param {boolean | undefined} asiSafe asiSafe
  222. * @param {Set<ExportInfo>} alreadyVisited alreadyVisited
  223. * @returns {Binding} the final variable
  224. */
  225. const getFinalBinding = (
  226. moduleGraph,
  227. info,
  228. exportName,
  229. moduleToInfoMap,
  230. runtime,
  231. requestShortener,
  232. runtimeTemplate,
  233. neededNamespaceObjects,
  234. asCall,
  235. strictHarmonyModule,
  236. asiSafe,
  237. alreadyVisited = new Set()
  238. ) => {
  239. const exportsType = info.module.getExportsType(
  240. moduleGraph,
  241. strictHarmonyModule
  242. );
  243. if (exportName.length === 0) {
  244. switch (exportsType) {
  245. case "default-only":
  246. info.interopNamespaceObject2Used = true;
  247. return {
  248. info,
  249. rawName: info.interopNamespaceObject2Name,
  250. ids: exportName,
  251. exportName
  252. };
  253. case "default-with-named":
  254. info.interopNamespaceObjectUsed = true;
  255. return {
  256. info,
  257. rawName: info.interopNamespaceObjectName,
  258. ids: exportName,
  259. exportName
  260. };
  261. case "namespace":
  262. case "dynamic":
  263. break;
  264. default:
  265. throw new Error(`Unexpected exportsType ${exportsType}`);
  266. }
  267. } else {
  268. switch (exportsType) {
  269. case "namespace":
  270. break;
  271. case "default-with-named":
  272. switch (exportName[0]) {
  273. case "default":
  274. exportName = exportName.slice(1);
  275. break;
  276. case "__esModule":
  277. return {
  278. info,
  279. rawName: "/* __esModule */true",
  280. ids: exportName.slice(1),
  281. exportName
  282. };
  283. }
  284. break;
  285. case "default-only": {
  286. const exportId = exportName[0];
  287. if (exportId === "__esModule") {
  288. return {
  289. info,
  290. rawName: "/* __esModule */true",
  291. ids: exportName.slice(1),
  292. exportName
  293. };
  294. }
  295. exportName = exportName.slice(1);
  296. if (exportId !== "default") {
  297. return {
  298. info,
  299. rawName:
  300. "/* non-default import from default-exporting module */undefined",
  301. ids: exportName,
  302. exportName
  303. };
  304. }
  305. break;
  306. }
  307. case "dynamic":
  308. switch (exportName[0]) {
  309. case "default": {
  310. exportName = exportName.slice(1);
  311. info.interopDefaultAccessUsed = true;
  312. const defaultExport = asCall
  313. ? `${info.interopDefaultAccessName}()`
  314. : asiSafe
  315. ? `(${info.interopDefaultAccessName}())`
  316. : asiSafe === false
  317. ? `;(${info.interopDefaultAccessName}())`
  318. : `${info.interopDefaultAccessName}.a`;
  319. return {
  320. info,
  321. rawName: defaultExport,
  322. ids: exportName,
  323. exportName
  324. };
  325. }
  326. case "__esModule":
  327. return {
  328. info,
  329. rawName: "/* __esModule */true",
  330. ids: exportName.slice(1),
  331. exportName
  332. };
  333. }
  334. break;
  335. default:
  336. throw new Error(`Unexpected exportsType ${exportsType}`);
  337. }
  338. }
  339. if (exportName.length === 0) {
  340. switch (info.type) {
  341. case "concatenated":
  342. neededNamespaceObjects.add(info);
  343. return {
  344. info,
  345. rawName: info.namespaceObjectName,
  346. ids: exportName,
  347. exportName
  348. };
  349. case "external":
  350. return { info, rawName: info.name, ids: exportName, exportName };
  351. }
  352. }
  353. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  354. const exportInfo = exportsInfo.getExportInfo(exportName[0]);
  355. if (alreadyVisited.has(exportInfo)) {
  356. return {
  357. info,
  358. rawName: "/* circular reexport */ Object(function x() { x() }())",
  359. ids: [],
  360. exportName
  361. };
  362. }
  363. alreadyVisited.add(exportInfo);
  364. switch (info.type) {
  365. case "concatenated": {
  366. const exportId = exportName[0];
  367. if (exportInfo.provided === false) {
  368. // It's not provided, but it could be on the prototype
  369. neededNamespaceObjects.add(info);
  370. return {
  371. info,
  372. rawName: info.namespaceObjectName,
  373. ids: exportName,
  374. exportName
  375. };
  376. }
  377. const directExport = info.exportMap && info.exportMap.get(exportId);
  378. if (directExport) {
  379. const usedName = /** @type {string[]} */ (
  380. exportsInfo.getUsedName(exportName, runtime)
  381. );
  382. if (!usedName) {
  383. return {
  384. info,
  385. rawName: "/* unused export */ undefined",
  386. ids: exportName.slice(1),
  387. exportName
  388. };
  389. }
  390. return {
  391. info,
  392. name: directExport,
  393. ids: usedName.slice(1),
  394. exportName
  395. };
  396. }
  397. const rawExport = info.rawExportMap && info.rawExportMap.get(exportId);
  398. if (rawExport) {
  399. return {
  400. info,
  401. rawName: rawExport,
  402. ids: exportName.slice(1),
  403. exportName
  404. };
  405. }
  406. const reexport = exportInfo.findTarget(moduleGraph, module =>
  407. moduleToInfoMap.has(module)
  408. );
  409. if (reexport === false) {
  410. throw new Error(
  411. `Target module of reexport from '${info.module.readableIdentifier(
  412. requestShortener
  413. )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from(
  414. moduleToInfoMap,
  415. ([m, info]) =>
  416. ` * ${info.type} ${m.readableIdentifier(requestShortener)}`
  417. ).join("\n")}`
  418. );
  419. }
  420. if (reexport) {
  421. const refInfo = moduleToInfoMap.get(reexport.module);
  422. return getFinalBinding(
  423. moduleGraph,
  424. refInfo,
  425. reexport.export
  426. ? [...reexport.export, ...exportName.slice(1)]
  427. : exportName.slice(1),
  428. moduleToInfoMap,
  429. runtime,
  430. requestShortener,
  431. runtimeTemplate,
  432. neededNamespaceObjects,
  433. asCall,
  434. info.module.buildMeta.strictHarmonyModule,
  435. asiSafe,
  436. alreadyVisited
  437. );
  438. }
  439. if (info.namespaceExportSymbol) {
  440. const usedName = /** @type {string[]} */ (
  441. exportsInfo.getUsedName(exportName, runtime)
  442. );
  443. return {
  444. info,
  445. rawName: info.namespaceObjectName,
  446. ids: usedName,
  447. exportName
  448. };
  449. }
  450. throw new Error(
  451. `Cannot get final name for export '${exportName.join(
  452. "."
  453. )}' of ${info.module.readableIdentifier(requestShortener)}`
  454. );
  455. }
  456. case "external": {
  457. const used = /** @type {string[]} */ (
  458. exportsInfo.getUsedName(exportName, runtime)
  459. );
  460. if (!used) {
  461. return {
  462. info,
  463. rawName: "/* unused export */ undefined",
  464. ids: exportName.slice(1),
  465. exportName
  466. };
  467. }
  468. const comment = equals(used, exportName)
  469. ? ""
  470. : Template.toNormalComment(`${exportName.join(".")}`);
  471. return { info, rawName: info.name + comment, ids: used, exportName };
  472. }
  473. }
  474. };
  475. /**
  476. * @param {ModuleGraph} moduleGraph the module graph
  477. * @param {ModuleInfo} info module info
  478. * @param {string[]} exportName exportName
  479. * @param {Map<Module, ModuleInfo>} moduleToInfoMap moduleToInfoMap
  480. * @param {RuntimeSpec} runtime for which runtime
  481. * @param {RequestShortener} requestShortener the request shortener
  482. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  483. * @param {Set<ConcatenatedModuleInfo>} neededNamespaceObjects modules for which a namespace object should be generated
  484. * @param {boolean} asCall asCall
  485. * @param {boolean} callContext callContext
  486. * @param {boolean} strictHarmonyModule strictHarmonyModule
  487. * @param {boolean | undefined} asiSafe asiSafe
  488. * @returns {string} the final name
  489. */
  490. const getFinalName = (
  491. moduleGraph,
  492. info,
  493. exportName,
  494. moduleToInfoMap,
  495. runtime,
  496. requestShortener,
  497. runtimeTemplate,
  498. neededNamespaceObjects,
  499. asCall,
  500. callContext,
  501. strictHarmonyModule,
  502. asiSafe
  503. ) => {
  504. const binding = getFinalBinding(
  505. moduleGraph,
  506. info,
  507. exportName,
  508. moduleToInfoMap,
  509. runtime,
  510. requestShortener,
  511. runtimeTemplate,
  512. neededNamespaceObjects,
  513. asCall,
  514. strictHarmonyModule,
  515. asiSafe
  516. );
  517. {
  518. const { ids, comment } = binding;
  519. let reference;
  520. let isPropertyAccess;
  521. if ("rawName" in binding) {
  522. reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`;
  523. isPropertyAccess = ids.length > 0;
  524. } else {
  525. const { info, name: exportId } = binding;
  526. const name = info.internalNames.get(exportId);
  527. if (!name) {
  528. throw new Error(
  529. `The export "${exportId}" in "${info.module.readableIdentifier(
  530. requestShortener
  531. )}" has no internal name (existing names: ${
  532. Array.from(
  533. info.internalNames,
  534. ([name, symbol]) => `${name}: ${symbol}`
  535. ).join(", ") || "none"
  536. })`
  537. );
  538. }
  539. reference = `${name}${comment || ""}${propertyAccess(ids)}`;
  540. isPropertyAccess = ids.length > 1;
  541. }
  542. if (isPropertyAccess && asCall && callContext === false) {
  543. return asiSafe
  544. ? `(0,${reference})`
  545. : asiSafe === false
  546. ? `;(0,${reference})`
  547. : `/*#__PURE__*/Object(${reference})`;
  548. }
  549. return reference;
  550. }
  551. };
  552. const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => {
  553. let scope = s;
  554. while (scope) {
  555. if (scopeSet1.has(scope)) break;
  556. if (scopeSet2.has(scope)) break;
  557. scopeSet1.add(scope);
  558. for (const variable of scope.variables) {
  559. nameSet.add(variable.name);
  560. }
  561. scope = scope.upper;
  562. }
  563. };
  564. const getAllReferences = variable => {
  565. let set = variable.references;
  566. // Look for inner scope variables too (like in class Foo { t() { Foo } })
  567. const identifiers = new Set(variable.identifiers);
  568. for (const scope of variable.scope.childScopes) {
  569. for (const innerVar of scope.variables) {
  570. if (innerVar.identifiers.some(id => identifiers.has(id))) {
  571. set = set.concat(innerVar.references);
  572. break;
  573. }
  574. }
  575. }
  576. return set;
  577. };
  578. const getPathInAst = (ast, node) => {
  579. if (ast === node) {
  580. return [];
  581. }
  582. const nr = node.range;
  583. const enterNode = n => {
  584. if (!n) return undefined;
  585. const r = n.range;
  586. if (r) {
  587. if (r[0] <= nr[0] && r[1] >= nr[1]) {
  588. const path = getPathInAst(n, node);
  589. if (path) {
  590. path.push(n);
  591. return path;
  592. }
  593. }
  594. }
  595. return undefined;
  596. };
  597. if (Array.isArray(ast)) {
  598. for (let i = 0; i < ast.length; i++) {
  599. const enterResult = enterNode(ast[i]);
  600. if (enterResult !== undefined) return enterResult;
  601. }
  602. } else if (ast && typeof ast === "object") {
  603. const keys = Object.keys(ast);
  604. for (let i = 0; i < keys.length; i++) {
  605. const value = ast[keys[i]];
  606. if (Array.isArray(value)) {
  607. const pathResult = getPathInAst(value, node);
  608. if (pathResult !== undefined) return pathResult;
  609. } else if (value && typeof value === "object") {
  610. const enterResult = enterNode(value);
  611. if (enterResult !== undefined) return enterResult;
  612. }
  613. }
  614. }
  615. };
  616. const TYPES = new Set(["javascript"]);
  617. class ConcatenatedModule extends Module {
  618. /**
  619. * @param {Module} rootModule the root module of the concatenation
  620. * @param {Set<Module>} modules all modules in the concatenation (including the root module)
  621. * @param {RuntimeSpec} runtime the runtime
  622. * @param {Object=} associatedObjectForCache object for caching
  623. * @param {string | HashConstructor=} hashFunction hash function to use
  624. * @returns {ConcatenatedModule} the module
  625. */
  626. static create(
  627. rootModule,
  628. modules,
  629. runtime,
  630. associatedObjectForCache,
  631. hashFunction = "md4"
  632. ) {
  633. const identifier = ConcatenatedModule._createIdentifier(
  634. rootModule,
  635. modules,
  636. associatedObjectForCache,
  637. hashFunction
  638. );
  639. return new ConcatenatedModule({
  640. identifier,
  641. rootModule,
  642. modules,
  643. runtime
  644. });
  645. }
  646. /**
  647. * @param {Object} options options
  648. * @param {string} options.identifier the identifier of the module
  649. * @param {Module=} options.rootModule the root module of the concatenation
  650. * @param {RuntimeSpec} options.runtime the selected runtime
  651. * @param {Set<Module>=} options.modules all concatenated modules
  652. */
  653. constructor({ identifier, rootModule, modules, runtime }) {
  654. super(JAVASCRIPT_MODULE_TYPE_ESM, null, rootModule && rootModule.layer);
  655. // Info from Factory
  656. /** @type {string} */
  657. this._identifier = identifier;
  658. /** @type {Module} */
  659. this.rootModule = rootModule;
  660. /** @type {Set<Module>} */
  661. this._modules = modules;
  662. this._runtime = runtime;
  663. this.factoryMeta = rootModule && rootModule.factoryMeta;
  664. }
  665. /**
  666. * Assuming this module is in the cache. Update the (cached) module with
  667. * the fresh module from the factory. Usually updates internal references
  668. * and properties.
  669. * @param {Module} module fresh module
  670. * @returns {void}
  671. */
  672. updateCacheModule(module) {
  673. throw new Error("Must not be called");
  674. }
  675. /**
  676. * @returns {Set<string>} types available (do not mutate)
  677. */
  678. getSourceTypes() {
  679. return TYPES;
  680. }
  681. get modules() {
  682. return Array.from(this._modules);
  683. }
  684. /**
  685. * @returns {string} a unique identifier of the module
  686. */
  687. identifier() {
  688. return this._identifier;
  689. }
  690. /**
  691. * @param {RequestShortener} requestShortener the request shortener
  692. * @returns {string} a user readable identifier of the module
  693. */
  694. readableIdentifier(requestShortener) {
  695. return (
  696. this.rootModule.readableIdentifier(requestShortener) +
  697. ` + ${this._modules.size - 1} modules`
  698. );
  699. }
  700. /**
  701. * @param {LibIdentOptions} options options
  702. * @returns {string | null} an identifier for library inclusion
  703. */
  704. libIdent(options) {
  705. return this.rootModule.libIdent(options);
  706. }
  707. /**
  708. * @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
  709. */
  710. nameForCondition() {
  711. return this.rootModule.nameForCondition();
  712. }
  713. /**
  714. * @param {ModuleGraph} moduleGraph the module graph
  715. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  716. */
  717. getSideEffectsConnectionState(moduleGraph) {
  718. return this.rootModule.getSideEffectsConnectionState(moduleGraph);
  719. }
  720. /**
  721. * @param {WebpackOptions} options webpack options
  722. * @param {Compilation} compilation the compilation
  723. * @param {ResolverWithOptions} resolver the resolver
  724. * @param {InputFileSystem} fs the file system
  725. * @param {function(WebpackError=): void} callback callback function
  726. * @returns {void}
  727. */
  728. build(options, compilation, resolver, fs, callback) {
  729. const { rootModule } = this;
  730. this.buildInfo = {
  731. strict: true,
  732. cacheable: true,
  733. moduleArgument: rootModule.buildInfo.moduleArgument,
  734. exportsArgument: rootModule.buildInfo.exportsArgument,
  735. fileDependencies: new LazySet(),
  736. contextDependencies: new LazySet(),
  737. missingDependencies: new LazySet(),
  738. topLevelDeclarations: new Set(),
  739. assets: undefined
  740. };
  741. this.buildMeta = rootModule.buildMeta;
  742. this.clearDependenciesAndBlocks();
  743. this.clearWarningsAndErrors();
  744. for (const m of this._modules) {
  745. // populate cacheable
  746. if (!m.buildInfo.cacheable) {
  747. this.buildInfo.cacheable = false;
  748. }
  749. // populate dependencies
  750. for (const d of m.dependencies.filter(
  751. dep =>
  752. !(dep instanceof HarmonyImportDependency) ||
  753. !this._modules.has(compilation.moduleGraph.getModule(dep))
  754. )) {
  755. this.dependencies.push(d);
  756. }
  757. // populate blocks
  758. for (const d of m.blocks) {
  759. this.blocks.push(d);
  760. }
  761. // populate warnings
  762. const warnings = m.getWarnings();
  763. if (warnings !== undefined) {
  764. for (const warning of warnings) {
  765. this.addWarning(warning);
  766. }
  767. }
  768. // populate errors
  769. const errors = m.getErrors();
  770. if (errors !== undefined) {
  771. for (const error of errors) {
  772. this.addError(error);
  773. }
  774. }
  775. // populate topLevelDeclarations
  776. if (m.buildInfo.topLevelDeclarations) {
  777. const topLevelDeclarations = this.buildInfo.topLevelDeclarations;
  778. if (topLevelDeclarations !== undefined) {
  779. for (const decl of m.buildInfo.topLevelDeclarations) {
  780. topLevelDeclarations.add(decl);
  781. }
  782. }
  783. } else {
  784. this.buildInfo.topLevelDeclarations = undefined;
  785. }
  786. // populate assets
  787. if (m.buildInfo.assets) {
  788. if (this.buildInfo.assets === undefined) {
  789. this.buildInfo.assets = Object.create(null);
  790. }
  791. Object.assign(this.buildInfo.assets, m.buildInfo.assets);
  792. }
  793. if (m.buildInfo.assetsInfo) {
  794. if (this.buildInfo.assetsInfo === undefined) {
  795. this.buildInfo.assetsInfo = new Map();
  796. }
  797. for (const [key, value] of m.buildInfo.assetsInfo) {
  798. this.buildInfo.assetsInfo.set(key, value);
  799. }
  800. }
  801. }
  802. callback();
  803. }
  804. /**
  805. * @param {string=} type the source type for which the size should be estimated
  806. * @returns {number} the estimated size of the module (must be non-zero)
  807. */
  808. size(type) {
  809. // Guess size from embedded modules
  810. let size = 0;
  811. for (const module of this._modules) {
  812. size += module.size(type);
  813. }
  814. return size;
  815. }
  816. /**
  817. * @private
  818. * @param {Module} rootModule the root of the concatenation
  819. * @param {Set<Module>} modulesSet a set of modules which should be concatenated
  820. * @param {RuntimeSpec} runtime for this runtime
  821. * @param {ModuleGraph} moduleGraph the module graph
  822. * @returns {ConcatenationEntry[]} concatenation list
  823. */
  824. _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) {
  825. /** @type {ConcatenationEntry[]} */
  826. const list = [];
  827. /** @type {Map<Module, RuntimeSpec | true>} */
  828. const existingEntries = new Map();
  829. /**
  830. * @param {Module} module a module
  831. * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order
  832. */
  833. const getConcatenatedImports = module => {
  834. let connections = Array.from(moduleGraph.getOutgoingConnections(module));
  835. if (module === rootModule) {
  836. for (const c of moduleGraph.getOutgoingConnections(this))
  837. connections.push(c);
  838. }
  839. /**
  840. * @type {Array<{ connection: ModuleGraphConnection, sourceOrder: number, rangeStart: number }>}
  841. */
  842. const references = connections
  843. .filter(connection => {
  844. if (!(connection.dependency instanceof HarmonyImportDependency))
  845. return false;
  846. return (
  847. connection &&
  848. connection.resolvedOriginModule === module &&
  849. connection.module &&
  850. connection.isTargetActive(runtime)
  851. );
  852. })
  853. .map(connection => {
  854. const dep = /** @type {HarmonyImportDependency} */ (
  855. connection.dependency
  856. );
  857. return {
  858. connection,
  859. sourceOrder: dep.sourceOrder,
  860. rangeStart: dep.range && dep.range[0]
  861. };
  862. });
  863. /**
  864. * bySourceOrder
  865. * @example
  866. * import a from "a"; // sourceOrder=1
  867. * import b from "b"; // sourceOrder=2
  868. *
  869. * byRangeStart
  870. * @example
  871. * import {a, b} from "a"; // sourceOrder=1
  872. * a.a(); // first range
  873. * b.b(); // second range
  874. *
  875. * If there is no reexport, we have the same source.
  876. * If there is reexport, but module has side effects, this will lead to reexport module only.
  877. * If there is side-effects-free reexport, we can get simple deterministic result with range start comparison.
  878. */
  879. references.sort(concatComparators(bySourceOrder, byRangeStart));
  880. /** @type {Map<Module, { connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} */
  881. const referencesMap = new Map();
  882. for (const { connection } of references) {
  883. const runtimeCondition = filterRuntime(runtime, r =>
  884. connection.isTargetActive(r)
  885. );
  886. if (runtimeCondition === false) continue;
  887. const module = connection.module;
  888. const entry = referencesMap.get(module);
  889. if (entry === undefined) {
  890. referencesMap.set(module, { connection, runtimeCondition });
  891. continue;
  892. }
  893. entry.runtimeCondition = mergeRuntimeConditionNonFalse(
  894. entry.runtimeCondition,
  895. runtimeCondition,
  896. runtime
  897. );
  898. }
  899. return referencesMap.values();
  900. };
  901. /**
  902. * @param {ModuleGraphConnection} connection graph connection
  903. * @param {RuntimeSpec | true} runtimeCondition runtime condition
  904. * @returns {void}
  905. */
  906. const enterModule = (connection, runtimeCondition) => {
  907. const module = connection.module;
  908. if (!module) return;
  909. const existingEntry = existingEntries.get(module);
  910. if (existingEntry === true) {
  911. return;
  912. }
  913. if (modulesSet.has(module)) {
  914. existingEntries.set(module, true);
  915. if (runtimeCondition !== true) {
  916. throw new Error(
  917. `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString(
  918. runtimeCondition
  919. )}). This should not happen.`
  920. );
  921. }
  922. const imports = getConcatenatedImports(module);
  923. for (const { connection, runtimeCondition } of imports)
  924. enterModule(connection, runtimeCondition);
  925. list.push({
  926. type: "concatenated",
  927. module: connection.module,
  928. runtimeCondition
  929. });
  930. } else {
  931. if (existingEntry !== undefined) {
  932. const reducedRuntimeCondition = subtractRuntimeCondition(
  933. runtimeCondition,
  934. existingEntry,
  935. runtime
  936. );
  937. if (reducedRuntimeCondition === false) return;
  938. runtimeCondition = reducedRuntimeCondition;
  939. existingEntries.set(
  940. connection.module,
  941. mergeRuntimeConditionNonFalse(
  942. existingEntry,
  943. runtimeCondition,
  944. runtime
  945. )
  946. );
  947. } else {
  948. existingEntries.set(connection.module, runtimeCondition);
  949. }
  950. if (list.length > 0) {
  951. const lastItem = list[list.length - 1];
  952. if (
  953. lastItem.type === "external" &&
  954. lastItem.module === connection.module
  955. ) {
  956. lastItem.runtimeCondition = mergeRuntimeCondition(
  957. lastItem.runtimeCondition,
  958. runtimeCondition,
  959. runtime
  960. );
  961. return;
  962. }
  963. }
  964. list.push({
  965. type: "external",
  966. get module() {
  967. // We need to use a getter here, because the module in the dependency
  968. // could be replaced by some other process (i. e. also replaced with a
  969. // concatenated module)
  970. return connection.module;
  971. },
  972. runtimeCondition
  973. });
  974. }
  975. };
  976. existingEntries.set(rootModule, true);
  977. const imports = getConcatenatedImports(rootModule);
  978. for (const { connection, runtimeCondition } of imports)
  979. enterModule(connection, runtimeCondition);
  980. list.push({
  981. type: "concatenated",
  982. module: rootModule,
  983. runtimeCondition: true
  984. });
  985. return list;
  986. }
  987. /**
  988. * @param {Module} rootModule the root module of the concatenation
  989. * @param {Set<Module>} modules all modules in the concatenation (including the root module)
  990. * @param {Object=} associatedObjectForCache object for caching
  991. * @param {string | HashConstructor=} hashFunction hash function to use
  992. * @returns {string} the identifier
  993. */
  994. static _createIdentifier(
  995. rootModule,
  996. modules,
  997. associatedObjectForCache,
  998. hashFunction = "md4"
  999. ) {
  1000. const cachedMakePathsRelative = makePathsRelative.bindContextCache(
  1001. rootModule.context,
  1002. associatedObjectForCache
  1003. );
  1004. let identifiers = [];
  1005. for (const module of modules) {
  1006. identifiers.push(cachedMakePathsRelative(module.identifier()));
  1007. }
  1008. identifiers.sort();
  1009. const hash = createHash(hashFunction);
  1010. hash.update(identifiers.join(" "));
  1011. return rootModule.identifier() + "|" + hash.digest("hex");
  1012. }
  1013. /**
  1014. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  1015. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  1016. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  1017. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  1018. */
  1019. addCacheDependencies(
  1020. fileDependencies,
  1021. contextDependencies,
  1022. missingDependencies,
  1023. buildDependencies
  1024. ) {
  1025. for (const module of this._modules) {
  1026. module.addCacheDependencies(
  1027. fileDependencies,
  1028. contextDependencies,
  1029. missingDependencies,
  1030. buildDependencies
  1031. );
  1032. }
  1033. }
  1034. /**
  1035. * @param {CodeGenerationContext} context context for code generation
  1036. * @returns {CodeGenerationResult} result
  1037. */
  1038. codeGeneration({
  1039. dependencyTemplates,
  1040. runtimeTemplate,
  1041. moduleGraph,
  1042. chunkGraph,
  1043. runtime: generationRuntime,
  1044. codeGenerationResults
  1045. }) {
  1046. /** @type {Set<string>} */
  1047. const runtimeRequirements = new Set();
  1048. const runtime = intersectRuntime(generationRuntime, this._runtime);
  1049. const requestShortener = runtimeTemplate.requestShortener;
  1050. // Meta info for each module
  1051. const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo(
  1052. moduleGraph,
  1053. runtime
  1054. );
  1055. // Set with modules that need a generated namespace object
  1056. /** @type {Set<ConcatenatedModuleInfo>} */
  1057. const neededNamespaceObjects = new Set();
  1058. // Generate source code and analyse scopes
  1059. // Prepare a ReplaceSource for the final source
  1060. for (const info of moduleToInfoMap.values()) {
  1061. this._analyseModule(
  1062. moduleToInfoMap,
  1063. info,
  1064. dependencyTemplates,
  1065. runtimeTemplate,
  1066. moduleGraph,
  1067. chunkGraph,
  1068. runtime,
  1069. codeGenerationResults
  1070. );
  1071. }
  1072. // List of all used names to avoid conflicts
  1073. const allUsedNames = new Set(RESERVED_NAMES);
  1074. // Updated Top level declarations are created by renaming
  1075. const topLevelDeclarations = new Set();
  1076. // List of additional names in scope for module references
  1077. /** @type {Map<string, { usedNames: Set<string>, alreadyCheckedScopes: Set<TODO> }>} */
  1078. const usedNamesInScopeInfo = new Map();
  1079. /**
  1080. * @param {string} module module identifier
  1081. * @param {string} id export id
  1082. * @returns {{ usedNames: Set<string>, alreadyCheckedScopes: Set<TODO> }} info
  1083. */
  1084. const getUsedNamesInScopeInfo = (module, id) => {
  1085. const key = `${module}-${id}`;
  1086. let info = usedNamesInScopeInfo.get(key);
  1087. if (info === undefined) {
  1088. info = {
  1089. usedNames: new Set(),
  1090. alreadyCheckedScopes: new Set()
  1091. };
  1092. usedNamesInScopeInfo.set(key, info);
  1093. }
  1094. return info;
  1095. };
  1096. // Set of already checked scopes
  1097. const ignoredScopes = new Set();
  1098. // get all global names
  1099. for (const info of modulesWithInfo) {
  1100. if (info.type === "concatenated") {
  1101. // ignore symbols from moduleScope
  1102. if (info.moduleScope) {
  1103. ignoredScopes.add(info.moduleScope);
  1104. }
  1105. // The super class expression in class scopes behaves weird
  1106. // We get ranges of all super class expressions to make
  1107. // renaming to work correctly
  1108. const superClassCache = new WeakMap();
  1109. const getSuperClassExpressions = scope => {
  1110. const cacheEntry = superClassCache.get(scope);
  1111. if (cacheEntry !== undefined) return cacheEntry;
  1112. const superClassExpressions = [];
  1113. for (const childScope of scope.childScopes) {
  1114. if (childScope.type !== "class") continue;
  1115. const block = childScope.block;
  1116. if (
  1117. (block.type === "ClassDeclaration" ||
  1118. block.type === "ClassExpression") &&
  1119. block.superClass
  1120. ) {
  1121. superClassExpressions.push({
  1122. range: block.superClass.range,
  1123. variables: childScope.variables
  1124. });
  1125. }
  1126. }
  1127. superClassCache.set(scope, superClassExpressions);
  1128. return superClassExpressions;
  1129. };
  1130. // add global symbols
  1131. if (info.globalScope) {
  1132. for (const reference of info.globalScope.through) {
  1133. const name = reference.identifier.name;
  1134. if (ConcatenationScope.isModuleReference(name)) {
  1135. const match = ConcatenationScope.matchModuleReference(name);
  1136. if (!match) continue;
  1137. const referencedInfo = modulesWithInfo[match.index];
  1138. if (referencedInfo.type === "reference")
  1139. throw new Error("Module reference can't point to a reference");
  1140. const binding = getFinalBinding(
  1141. moduleGraph,
  1142. referencedInfo,
  1143. match.ids,
  1144. moduleToInfoMap,
  1145. runtime,
  1146. requestShortener,
  1147. runtimeTemplate,
  1148. neededNamespaceObjects,
  1149. false,
  1150. info.module.buildMeta.strictHarmonyModule,
  1151. true
  1152. );
  1153. if (!binding.ids) continue;
  1154. const { usedNames, alreadyCheckedScopes } =
  1155. getUsedNamesInScopeInfo(
  1156. binding.info.module.identifier(),
  1157. "name" in binding ? binding.name : ""
  1158. );
  1159. for (const expr of getSuperClassExpressions(reference.from)) {
  1160. if (
  1161. expr.range[0] <= reference.identifier.range[0] &&
  1162. expr.range[1] >= reference.identifier.range[1]
  1163. ) {
  1164. for (const variable of expr.variables) {
  1165. usedNames.add(variable.name);
  1166. }
  1167. }
  1168. }
  1169. addScopeSymbols(
  1170. reference.from,
  1171. usedNames,
  1172. alreadyCheckedScopes,
  1173. ignoredScopes
  1174. );
  1175. } else {
  1176. allUsedNames.add(name);
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // generate names for symbols
  1183. for (const info of moduleToInfoMap.values()) {
  1184. const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo(
  1185. info.module.identifier(),
  1186. ""
  1187. );
  1188. switch (info.type) {
  1189. case "concatenated": {
  1190. for (const variable of info.moduleScope.variables) {
  1191. const name = variable.name;
  1192. const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo(
  1193. info.module.identifier(),
  1194. name
  1195. );
  1196. if (allUsedNames.has(name) || usedNames.has(name)) {
  1197. const references = getAllReferences(variable);
  1198. for (const ref of references) {
  1199. addScopeSymbols(
  1200. ref.from,
  1201. usedNames,
  1202. alreadyCheckedScopes,
  1203. ignoredScopes
  1204. );
  1205. }
  1206. const newName = this.findNewName(
  1207. name,
  1208. allUsedNames,
  1209. usedNames,
  1210. info.module.readableIdentifier(requestShortener)
  1211. );
  1212. allUsedNames.add(newName);
  1213. info.internalNames.set(name, newName);
  1214. topLevelDeclarations.add(newName);
  1215. const source = info.source;
  1216. const allIdentifiers = new Set(
  1217. references.map(r => r.identifier).concat(variable.identifiers)
  1218. );
  1219. for (const identifier of allIdentifiers) {
  1220. const r = identifier.range;
  1221. const path = getPathInAst(info.ast, identifier);
  1222. if (path && path.length > 1) {
  1223. const maybeProperty =
  1224. path[1].type === "AssignmentPattern" &&
  1225. path[1].left === path[0]
  1226. ? path[2]
  1227. : path[1];
  1228. if (
  1229. maybeProperty.type === "Property" &&
  1230. maybeProperty.shorthand
  1231. ) {
  1232. source.insert(r[1], `: ${newName}`);
  1233. continue;
  1234. }
  1235. }
  1236. source.replace(r[0], r[1] - 1, newName);
  1237. }
  1238. } else {
  1239. allUsedNames.add(name);
  1240. info.internalNames.set(name, name);
  1241. topLevelDeclarations.add(name);
  1242. }
  1243. }
  1244. let namespaceObjectName;
  1245. if (info.namespaceExportSymbol) {
  1246. namespaceObjectName = info.internalNames.get(
  1247. info.namespaceExportSymbol
  1248. );
  1249. } else {
  1250. namespaceObjectName = this.findNewName(
  1251. "namespaceObject",
  1252. allUsedNames,
  1253. namespaceObjectUsedNames,
  1254. info.module.readableIdentifier(requestShortener)
  1255. );
  1256. allUsedNames.add(namespaceObjectName);
  1257. }
  1258. info.namespaceObjectName = namespaceObjectName;
  1259. topLevelDeclarations.add(namespaceObjectName);
  1260. break;
  1261. }
  1262. case "external": {
  1263. const externalName = this.findNewName(
  1264. "",
  1265. allUsedNames,
  1266. namespaceObjectUsedNames,
  1267. info.module.readableIdentifier(requestShortener)
  1268. );
  1269. allUsedNames.add(externalName);
  1270. info.name = externalName;
  1271. topLevelDeclarations.add(externalName);
  1272. break;
  1273. }
  1274. }
  1275. if (info.module.buildMeta.exportsType !== "namespace") {
  1276. const externalNameInterop = this.findNewName(
  1277. "namespaceObject",
  1278. allUsedNames,
  1279. namespaceObjectUsedNames,
  1280. info.module.readableIdentifier(requestShortener)
  1281. );
  1282. allUsedNames.add(externalNameInterop);
  1283. info.interopNamespaceObjectName = externalNameInterop;
  1284. topLevelDeclarations.add(externalNameInterop);
  1285. }
  1286. if (
  1287. info.module.buildMeta.exportsType === "default" &&
  1288. info.module.buildMeta.defaultObject !== "redirect"
  1289. ) {
  1290. const externalNameInterop = this.findNewName(
  1291. "namespaceObject2",
  1292. allUsedNames,
  1293. namespaceObjectUsedNames,
  1294. info.module.readableIdentifier(requestShortener)
  1295. );
  1296. allUsedNames.add(externalNameInterop);
  1297. info.interopNamespaceObject2Name = externalNameInterop;
  1298. topLevelDeclarations.add(externalNameInterop);
  1299. }
  1300. if (
  1301. info.module.buildMeta.exportsType === "dynamic" ||
  1302. !info.module.buildMeta.exportsType
  1303. ) {
  1304. const externalNameInterop = this.findNewName(
  1305. "default",
  1306. allUsedNames,
  1307. namespaceObjectUsedNames,
  1308. info.module.readableIdentifier(requestShortener)
  1309. );
  1310. allUsedNames.add(externalNameInterop);
  1311. info.interopDefaultAccessName = externalNameInterop;
  1312. topLevelDeclarations.add(externalNameInterop);
  1313. }
  1314. }
  1315. // Find and replace references to modules
  1316. for (const info of moduleToInfoMap.values()) {
  1317. if (info.type === "concatenated") {
  1318. for (const reference of info.globalScope.through) {
  1319. const name = reference.identifier.name;
  1320. const match = ConcatenationScope.matchModuleReference(name);
  1321. if (match) {
  1322. const referencedInfo = modulesWithInfo[match.index];
  1323. if (referencedInfo.type === "reference")
  1324. throw new Error("Module reference can't point to a reference");
  1325. const finalName = getFinalName(
  1326. moduleGraph,
  1327. referencedInfo,
  1328. match.ids,
  1329. moduleToInfoMap,
  1330. runtime,
  1331. requestShortener,
  1332. runtimeTemplate,
  1333. neededNamespaceObjects,
  1334. match.call,
  1335. !match.directImport,
  1336. info.module.buildMeta.strictHarmonyModule,
  1337. match.asiSafe
  1338. );
  1339. const r = reference.identifier.range;
  1340. const source = info.source;
  1341. // range is extended by 2 chars to cover the appended "._"
  1342. source.replace(r[0], r[1] + 1, finalName);
  1343. }
  1344. }
  1345. }
  1346. }
  1347. // Map with all root exposed used exports
  1348. /** @type {Map<string, function(RequestShortener): string>} */
  1349. const exportsMap = new Map();
  1350. // Set with all root exposed unused exports
  1351. /** @type {Set<string>} */
  1352. const unusedExports = new Set();
  1353. const rootInfo = /** @type {ConcatenatedModuleInfo} */ (
  1354. moduleToInfoMap.get(this.rootModule)
  1355. );
  1356. const strictHarmonyModule = rootInfo.module.buildMeta.strictHarmonyModule;
  1357. const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module);
  1358. for (const exportInfo of exportsInfo.orderedExports) {
  1359. const name = exportInfo.name;
  1360. if (exportInfo.provided === false) continue;
  1361. const used = exportInfo.getUsedName(undefined, runtime);
  1362. if (!used) {
  1363. unusedExports.add(name);
  1364. continue;
  1365. }
  1366. exportsMap.set(used, requestShortener => {
  1367. try {
  1368. const finalName = getFinalName(
  1369. moduleGraph,
  1370. rootInfo,
  1371. [name],
  1372. moduleToInfoMap,
  1373. runtime,
  1374. requestShortener,
  1375. runtimeTemplate,
  1376. neededNamespaceObjects,
  1377. false,
  1378. false,
  1379. strictHarmonyModule,
  1380. true
  1381. );
  1382. return `/* ${
  1383. exportInfo.isReexport() ? "reexport" : "binding"
  1384. } */ ${finalName}`;
  1385. } catch (e) {
  1386. e.message += `\nwhile generating the root export '${name}' (used name: '${used}')`;
  1387. throw e;
  1388. }
  1389. });
  1390. }
  1391. const result = new ConcatSource();
  1392. // add harmony compatibility flag (must be first because of possible circular dependencies)
  1393. if (
  1394. moduleGraph.getExportsInfo(this).otherExportsInfo.getUsed(runtime) !==
  1395. UsageState.Unused
  1396. ) {
  1397. result.add(`// ESM COMPAT FLAG\n`);
  1398. result.add(
  1399. runtimeTemplate.defineEsModuleFlagStatement({
  1400. exportsArgument: this.exportsArgument,
  1401. runtimeRequirements
  1402. })
  1403. );
  1404. }
  1405. // define exports
  1406. if (exportsMap.size > 0) {
  1407. runtimeRequirements.add(RuntimeGlobals.exports);
  1408. runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
  1409. const definitions = [];
  1410. for (const [key, value] of exportsMap) {
  1411. definitions.push(
  1412. `\n ${JSON.stringify(key)}: ${runtimeTemplate.returningFunction(
  1413. value(requestShortener)
  1414. )}`
  1415. );
  1416. }
  1417. result.add(`\n// EXPORTS\n`);
  1418. result.add(
  1419. `${RuntimeGlobals.definePropertyGetters}(${
  1420. this.exportsArgument
  1421. }, {${definitions.join(",")}\n});\n`
  1422. );
  1423. }
  1424. // list unused exports
  1425. if (unusedExports.size > 0) {
  1426. result.add(
  1427. `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n`
  1428. );
  1429. }
  1430. // generate namespace objects
  1431. const namespaceObjectSources = new Map();
  1432. for (const info of neededNamespaceObjects) {
  1433. if (info.namespaceExportSymbol) continue;
  1434. const nsObj = [];
  1435. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  1436. for (const exportInfo of exportsInfo.orderedExports) {
  1437. if (exportInfo.provided === false) continue;
  1438. const usedName = exportInfo.getUsedName(undefined, runtime);
  1439. if (usedName) {
  1440. const finalName = getFinalName(
  1441. moduleGraph,
  1442. info,
  1443. [exportInfo.name],
  1444. moduleToInfoMap,
  1445. runtime,
  1446. requestShortener,
  1447. runtimeTemplate,
  1448. neededNamespaceObjects,
  1449. false,
  1450. undefined,
  1451. info.module.buildMeta.strictHarmonyModule,
  1452. true
  1453. );
  1454. nsObj.push(
  1455. `\n ${JSON.stringify(
  1456. usedName
  1457. )}: ${runtimeTemplate.returningFunction(finalName)}`
  1458. );
  1459. }
  1460. }
  1461. const name = info.namespaceObjectName;
  1462. const defineGetters =
  1463. nsObj.length > 0
  1464. ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join(
  1465. ","
  1466. )}\n});\n`
  1467. : "";
  1468. if (nsObj.length > 0)
  1469. runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
  1470. namespaceObjectSources.set(
  1471. info,
  1472. `
  1473. // NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)}
  1474. var ${name} = {};
  1475. ${RuntimeGlobals.makeNamespaceObject}(${name});
  1476. ${defineGetters}`
  1477. );
  1478. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  1479. }
  1480. // define required namespace objects (must be before evaluation modules)
  1481. for (const info of modulesWithInfo) {
  1482. if (info.type === "concatenated") {
  1483. const source = namespaceObjectSources.get(info);
  1484. if (!source) continue;
  1485. result.add(source);
  1486. }
  1487. }
  1488. const chunkInitFragments = [];
  1489. // evaluate modules in order
  1490. for (const rawInfo of modulesWithInfo) {
  1491. let name;
  1492. let isConditional = false;
  1493. const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo;
  1494. switch (info.type) {
  1495. case "concatenated": {
  1496. result.add(
  1497. `\n;// CONCATENATED MODULE: ${info.module.readableIdentifier(
  1498. requestShortener
  1499. )}\n`
  1500. );
  1501. result.add(info.source);
  1502. if (info.chunkInitFragments) {
  1503. for (const f of info.chunkInitFragments) chunkInitFragments.push(f);
  1504. }
  1505. if (info.runtimeRequirements) {
  1506. for (const r of info.runtimeRequirements) {
  1507. runtimeRequirements.add(r);
  1508. }
  1509. }
  1510. name = info.namespaceObjectName;
  1511. break;
  1512. }
  1513. case "external": {
  1514. result.add(
  1515. `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
  1516. requestShortener
  1517. )}\n`
  1518. );
  1519. runtimeRequirements.add(RuntimeGlobals.require);
  1520. const { runtimeCondition } =
  1521. /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ (rawInfo);
  1522. const condition = runtimeTemplate.runtimeConditionExpression({
  1523. chunkGraph,
  1524. runtimeCondition,
  1525. runtime,
  1526. runtimeRequirements
  1527. });
  1528. if (condition !== "true") {
  1529. isConditional = true;
  1530. result.add(`if (${condition}) {\n`);
  1531. }
  1532. result.add(
  1533. `var ${info.name} = __webpack_require__(${JSON.stringify(
  1534. chunkGraph.getModuleId(info.module)
  1535. )});`
  1536. );
  1537. name = info.name;
  1538. break;
  1539. }
  1540. default:
  1541. // @ts-expect-error never is expected here
  1542. throw new Error(`Unsupported concatenation entry type ${info.type}`);
  1543. }
  1544. if (info.interopNamespaceObjectUsed) {
  1545. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  1546. result.add(
  1547. `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);`
  1548. );
  1549. }
  1550. if (info.interopNamespaceObject2Used) {
  1551. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  1552. result.add(
  1553. `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});`
  1554. );
  1555. }
  1556. if (info.interopDefaultAccessUsed) {
  1557. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  1558. result.add(
  1559. `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});`
  1560. );
  1561. }
  1562. if (isConditional) {
  1563. result.add("\n}");
  1564. }
  1565. }
  1566. const data = new Map();
  1567. if (chunkInitFragments.length > 0)
  1568. data.set("chunkInitFragments", chunkInitFragments);
  1569. data.set("topLevelDeclarations", topLevelDeclarations);
  1570. /** @type {CodeGenerationResult} */
  1571. const resultEntry = {
  1572. sources: new Map([["javascript", new CachedSource(result)]]),
  1573. data,
  1574. runtimeRequirements
  1575. };
  1576. return resultEntry;
  1577. }
  1578. /**
  1579. * @param {Map<Module, ModuleInfo>} modulesMap modulesMap
  1580. * @param {ModuleInfo} info info
  1581. * @param {DependencyTemplates} dependencyTemplates dependencyTemplates
  1582. * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate
  1583. * @param {ModuleGraph} moduleGraph moduleGraph
  1584. * @param {ChunkGraph} chunkGraph chunkGraph
  1585. * @param {RuntimeSpec} runtime runtime
  1586. * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults
  1587. */
  1588. _analyseModule(
  1589. modulesMap,
  1590. info,
  1591. dependencyTemplates,
  1592. runtimeTemplate,
  1593. moduleGraph,
  1594. chunkGraph,
  1595. runtime,
  1596. codeGenerationResults
  1597. ) {
  1598. if (info.type === "concatenated") {
  1599. const m = info.module;
  1600. try {
  1601. // Create a concatenation scope to track and capture information
  1602. const concatenationScope = new ConcatenationScope(modulesMap, info);
  1603. // TODO cache codeGeneration results
  1604. const codeGenResult = m.codeGeneration({
  1605. dependencyTemplates,
  1606. runtimeTemplate,
  1607. moduleGraph,
  1608. chunkGraph,
  1609. runtime,
  1610. concatenationScope,
  1611. codeGenerationResults,
  1612. sourceTypes: TYPES
  1613. });
  1614. const source = codeGenResult.sources.get("javascript");
  1615. const data = codeGenResult.data;
  1616. const chunkInitFragments = data && data.get("chunkInitFragments");
  1617. const code = source.source().toString();
  1618. let ast;
  1619. try {
  1620. ast = JavascriptParser._parse(code, {
  1621. sourceType: "module"
  1622. });
  1623. } catch (err) {
  1624. if (
  1625. err.loc &&
  1626. typeof err.loc === "object" &&
  1627. typeof err.loc.line === "number"
  1628. ) {
  1629. const lineNumber = err.loc.line;
  1630. const lines = code.split("\n");
  1631. err.message +=
  1632. "\n| " +
  1633. lines
  1634. .slice(Math.max(0, lineNumber - 3), lineNumber + 2)
  1635. .join("\n| ");
  1636. }
  1637. throw err;
  1638. }
  1639. const scopeManager = eslintScope.analyze(ast, {
  1640. ecmaVersion: 6,
  1641. sourceType: "module",
  1642. optimistic: true,
  1643. ignoreEval: true,
  1644. impliedStrict: true
  1645. });
  1646. const globalScope = scopeManager.acquire(ast);
  1647. const moduleScope = globalScope.childScopes[0];
  1648. const resultSource = new ReplaceSource(source);
  1649. info.runtimeRequirements = codeGenResult.runtimeRequirements;
  1650. info.ast = ast;
  1651. info.internalSource = source;
  1652. info.source = resultSource;
  1653. info.chunkInitFragments = chunkInitFragments;
  1654. info.globalScope = globalScope;
  1655. info.moduleScope = moduleScope;
  1656. } catch (err) {
  1657. err.message += `\nwhile analyzing module ${m.identifier()} for concatenation`;
  1658. throw err;
  1659. }
  1660. }
  1661. }
  1662. /**
  1663. * @param {ModuleGraph} moduleGraph the module graph
  1664. * @param {RuntimeSpec} runtime the runtime
  1665. * @returns {[ModuleInfoOrReference[], Map<Module, ModuleInfo>]} module info items
  1666. */
  1667. _getModulesWithInfo(moduleGraph, runtime) {
  1668. const orderedConcatenationList = this._createConcatenationList(
  1669. this.rootModule,
  1670. this._modules,
  1671. runtime,
  1672. moduleGraph
  1673. );
  1674. /** @type {Map<Module, ModuleInfo>} */
  1675. const map = new Map();
  1676. const list = orderedConcatenationList.map((info, index) => {
  1677. let item = map.get(info.module);
  1678. if (item === undefined) {
  1679. switch (info.type) {
  1680. case "concatenated":
  1681. item = {
  1682. type: "concatenated",
  1683. module: info.module,
  1684. index,
  1685. ast: undefined,
  1686. internalSource: undefined,
  1687. runtimeRequirements: undefined,
  1688. source: undefined,
  1689. globalScope: undefined,
  1690. moduleScope: undefined,
  1691. internalNames: new Map(),
  1692. exportMap: undefined,
  1693. rawExportMap: undefined,
  1694. namespaceExportSymbol: undefined,
  1695. namespaceObjectName: undefined,
  1696. interopNamespaceObjectUsed: false,
  1697. interopNamespaceObjectName: undefined,
  1698. interopNamespaceObject2Used: false,
  1699. interopNamespaceObject2Name: undefined,
  1700. interopDefaultAccessUsed: false,
  1701. interopDefaultAccessName: undefined
  1702. };
  1703. break;
  1704. case "external":
  1705. item = {
  1706. type: "external",
  1707. module: info.module,
  1708. runtimeCondition: info.runtimeCondition,
  1709. index,
  1710. name: undefined,
  1711. interopNamespaceObjectUsed: false,
  1712. interopNamespaceObjectName: undefined,
  1713. interopNamespaceObject2Used: false,
  1714. interopNamespaceObject2Name: undefined,
  1715. interopDefaultAccessUsed: false,
  1716. interopDefaultAccessName: undefined
  1717. };
  1718. break;
  1719. default:
  1720. throw new Error(
  1721. `Unsupported concatenation entry type ${info.type}`
  1722. );
  1723. }
  1724. map.set(item.module, item);
  1725. return item;
  1726. } else {
  1727. /** @type {ReferenceToModuleInfo} */
  1728. const ref = {
  1729. type: "reference",
  1730. runtimeCondition: info.runtimeCondition,
  1731. target: item
  1732. };
  1733. return ref;
  1734. }
  1735. });
  1736. return [list, map];
  1737. }
  1738. findNewName(oldName, usedNamed1, usedNamed2, extraInfo) {
  1739. let name = oldName;
  1740. if (name === ConcatenationScope.DEFAULT_EXPORT) {
  1741. name = "";
  1742. }
  1743. if (name === ConcatenationScope.NAMESPACE_OBJECT_EXPORT) {
  1744. name = "namespaceObject";
  1745. }
  1746. // Remove uncool stuff
  1747. extraInfo = extraInfo.replace(
  1748. /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g,
  1749. ""
  1750. );
  1751. const splittedInfo = extraInfo.split("/");
  1752. while (splittedInfo.length) {
  1753. name = splittedInfo.pop() + (name ? "_" + name : "");
  1754. const nameIdent = Template.toIdentifier(name);
  1755. if (
  1756. !usedNamed1.has(nameIdent) &&
  1757. (!usedNamed2 || !usedNamed2.has(nameIdent))
  1758. )
  1759. return nameIdent;
  1760. }
  1761. let i = 0;
  1762. let nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  1763. while (
  1764. usedNamed1.has(nameWithNumber) ||
  1765. (usedNamed2 && usedNamed2.has(nameWithNumber))
  1766. ) {
  1767. i++;
  1768. nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  1769. }
  1770. return nameWithNumber;
  1771. }
  1772. /**
  1773. * @param {Hash} hash the hash used to track dependencies
  1774. * @param {UpdateHashContext} context context
  1775. * @returns {void}
  1776. */
  1777. updateHash(hash, context) {
  1778. const { chunkGraph, runtime } = context;
  1779. for (const info of this._createConcatenationList(
  1780. this.rootModule,
  1781. this._modules,
  1782. intersectRuntime(runtime, this._runtime),
  1783. chunkGraph.moduleGraph
  1784. )) {
  1785. switch (info.type) {
  1786. case "concatenated":
  1787. info.module.updateHash(hash, context);
  1788. break;
  1789. case "external":
  1790. hash.update(`${chunkGraph.getModuleId(info.module)}`);
  1791. // TODO runtimeCondition
  1792. break;
  1793. }
  1794. }
  1795. super.updateHash(hash, context);
  1796. }
  1797. static deserialize(context) {
  1798. const obj = new ConcatenatedModule({
  1799. identifier: undefined,
  1800. rootModule: undefined,
  1801. modules: undefined,
  1802. runtime: undefined
  1803. });
  1804. obj.deserialize(context);
  1805. return obj;
  1806. }
  1807. }
  1808. makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule");
  1809. module.exports = ConcatenatedModule;