ConcatenatedModule.js 55 KB

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