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