ConcatenatedModule.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Module = require("../Module");
  7. const Template = require("../Template");
  8. const Parser = require("../Parser");
  9. const crypto = require("crypto");
  10. const acorn = require("acorn");
  11. const escope = require("escope");
  12. const ReplaceSource = require("webpack-sources/lib/ReplaceSource");
  13. const ConcatSource = require("webpack-sources/lib/ConcatSource");
  14. const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
  15. const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency");
  16. const HarmonyExportSpecifierDependency = require("../dependencies/HarmonyExportSpecifierDependency");
  17. const HarmonyExportExpressionDependency = require("../dependencies/HarmonyExportExpressionDependency");
  18. const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency");
  19. const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency");
  20. function ensureNsObjSource(info, moduleToInfoMap, requestShortener) {
  21. if(!info.hasNamespaceObject) {
  22. info.hasNamespaceObject = true;
  23. const name = info.exportMap.get(true);
  24. const nsObj = [`var ${name} = {};`];
  25. for(const exportName of info.module.providedExports) {
  26. const finalName = getFinalName(info, exportName, moduleToInfoMap, requestShortener, false);
  27. nsObj.push(`__webpack_require__.d(${name}, ${JSON.stringify(exportName)}, function() { return ${finalName}; });`);
  28. }
  29. info.namespaceObjectSource = nsObj.join("\n") + "\n";
  30. }
  31. }
  32. function getExternalImport(importedModule, info, exportName, asCall) {
  33. if(exportName === true) return info.name;
  34. const used = importedModule.isUsed(exportName);
  35. if(!used) return "/* unused reexport */undefined";
  36. if(info.interop && exportName === "default") {
  37. return asCall ? `${info.interopName}()` : `${info.interopName}.a`;
  38. }
  39. // TODO use Template.toNormalComment when merging with pure-module
  40. const comment = used !== exportName ? ` /* ${exportName} */` : "";
  41. const reference = `${info.name}[${JSON.stringify(used)}${comment}]`;
  42. if(asCall)
  43. return `Object(${reference})`;
  44. return reference;
  45. }
  46. function getFinalName(info, exportName, moduleToInfoMap, requestShortener, asCall) {
  47. switch(info.type) {
  48. case "concatenated":
  49. {
  50. const directExport = info.exportMap.get(exportName);
  51. if(directExport) {
  52. if(exportName === true)
  53. ensureNsObjSource(info, moduleToInfoMap, requestShortener);
  54. const name = info.internalNames.get(directExport);
  55. if(!name)
  56. throw new Error(`The export "${directExport}" in "${info.module.readableIdentifier(requestShortener)}" has no internal name`);
  57. return name;
  58. }
  59. const reexport = info.reexportMap.get(exportName);
  60. if(reexport) {
  61. const refInfo = moduleToInfoMap.get(reexport.module);
  62. if(refInfo) {
  63. // module is in the concatenation
  64. return getFinalName(refInfo, reexport.exportName, moduleToInfoMap, requestShortener, asCall);
  65. }
  66. }
  67. const problem = `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier(requestShortener)}"` +
  68. ` (known exports: ${Array.from(info.exportMap.keys()).filter(name => name !== true).join(" ")}, ` +
  69. `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`;
  70. // TODO use Template.toNormalComment when merging with pure-module
  71. return `/* ${problem} */ undefined`;
  72. }
  73. case "external":
  74. {
  75. const importedModule = info.module;
  76. return getExternalImport(importedModule, info, exportName, asCall);
  77. }
  78. }
  79. }
  80. function getSymbolsFromScope(s, untilScope) {
  81. const allUsedNames = new Set();
  82. let scope = s;
  83. while(scope) {
  84. if(untilScope === scope) break;
  85. scope.variables.forEach(variable => allUsedNames.add(variable.name));
  86. scope = scope.upper;
  87. }
  88. return allUsedNames;
  89. }
  90. function getAllReferences(variable) {
  91. let set = variable.references;
  92. // Look for inner scope variables too (like in class Foo { t() { Foo } })
  93. const identifiers = new Set(variable.identifiers);
  94. for(const scope of variable.scope.childScopes) {
  95. for(const innerVar of scope.variables) {
  96. if(innerVar.identifiers.some(id => identifiers.has(id))) {
  97. set = set.concat(innerVar.references);
  98. break;
  99. }
  100. }
  101. }
  102. return set;
  103. }
  104. function reduceSet(a, b) {
  105. for(const item of b)
  106. a.add(item);
  107. return a;
  108. }
  109. function getPathInAst(ast, node) {
  110. if(ast === node) {
  111. return [];
  112. }
  113. const nr = node.range;
  114. var i;
  115. if(Array.isArray(ast)) {
  116. for(i = 0; i < ast.length; i++) {
  117. const enterResult = enterNode(ast[i]);
  118. if(typeof enterResult !== "undefined")
  119. return enterResult;
  120. }
  121. } else if(ast && typeof ast === "object") {
  122. const keys = Object.keys(ast);
  123. for(i = 0; i < keys.length; i++) {
  124. const value = ast[keys[i]];
  125. if(Array.isArray(value)) {
  126. const pathResult = getPathInAst(value, node);
  127. if(typeof pathResult !== "undefined")
  128. return pathResult;
  129. } else if(value && typeof value === "object") {
  130. const enterResult = enterNode(value);
  131. if(typeof enterResult !== "undefined")
  132. return enterResult;
  133. }
  134. }
  135. }
  136. function enterNode(n) {
  137. if(!n) return undefined;
  138. const r = n.range;
  139. if(r) {
  140. if(r[0] <= nr[0] && r[1] >= nr[1]) {
  141. const path = getPathInAst(n, node);
  142. if(path) {
  143. path.push(n);
  144. return path;
  145. }
  146. }
  147. }
  148. return undefined;
  149. }
  150. }
  151. class ConcatenatedModule extends Module {
  152. constructor(rootModule, modules) {
  153. super();
  154. super.setChunks(rootModule._chunks);
  155. this.rootModule = rootModule;
  156. this.usedExports = rootModule.usedExports;
  157. this.providedExports = rootModule.providedExports;
  158. this.optimizationBailout = rootModule.optimizationBailout;
  159. this.used = rootModule.used;
  160. this.index = rootModule.index;
  161. this.index2 = rootModule.index2;
  162. this.depth = rootModule.depth;
  163. this.built = modules.some(m => m.built);
  164. this.cacheable = modules.every(m => m.cacheable);
  165. const modulesSet = new Set(modules);
  166. this.reasons = rootModule.reasons.filter(reason => !(reason.dependency instanceof HarmonyImportDependency) || !modulesSet.has(reason.module));
  167. this.meta = rootModule.meta;
  168. this.moduleArgument = rootModule.moduleArgument;
  169. this.exportsArgument = rootModule.exportsArgument;
  170. this.strict = true;
  171. this._numberOfConcatenatedModules = modules.length;
  172. this.dependencies = [];
  173. this.dependenciesWarnings = [];
  174. this.dependenciesErrors = [];
  175. this.fileDependencies = [];
  176. this.contextDependencies = [];
  177. this.warnings = [];
  178. this.errors = [];
  179. this.assets = {};
  180. this._orderedConcatenationList = this._createOrderedConcatenationList(rootModule, modulesSet);
  181. for(const info of this._orderedConcatenationList) {
  182. if(info.type === "concatenated") {
  183. const m = info.module;
  184. // populate dependencies
  185. m.dependencies.filter(dep => !(dep instanceof HarmonyImportDependency) || !modulesSet.has(dep.module))
  186. .forEach(d => this.dependencies.push(d));
  187. // populate dep warning
  188. m.dependenciesWarnings.forEach(depWarning => this.dependenciesWarnings.push(depWarning));
  189. // populate dep errors
  190. m.dependenciesErrors.forEach(depError => this.dependenciesErrors.push(depError));
  191. // populate file dependencies
  192. if(m.fileDependencies) m.fileDependencies.forEach(file => this.fileDependencies.push(file));
  193. // populate context dependencies
  194. if(m.contextDependencies) m.contextDependencies.forEach(context => this.contextDependencies.push(context));
  195. // populate warnings
  196. m.warnings.forEach(warning => this.warnings.push(warning));
  197. // populate errors
  198. m.errors.forEach(error => this.errors.push(error));
  199. Object.assign(this.assets, m.assets);
  200. }
  201. }
  202. this._identifier = this._createIdentifier();
  203. }
  204. get modules() {
  205. return this._orderedConcatenationList
  206. .filter(info => info.type === "concatenated")
  207. .map(info => info.module);
  208. }
  209. identifier() {
  210. return this._identifier;
  211. }
  212. readableIdentifier(requestShortener) {
  213. return this.rootModule.readableIdentifier(requestShortener) + ` + ${this._numberOfConcatenatedModules - 1} modules`;
  214. }
  215. libIdent(options) {
  216. return this.rootModule.libIdent(options);
  217. }
  218. nameForCondition() {
  219. return this.rootModule.nameForCondition();
  220. }
  221. build(options, compilation, resolver, fs, callback) {
  222. throw new Error("Cannot build this module. It should be already built.");
  223. }
  224. size() {
  225. // Guess size from embedded modules
  226. return this._orderedConcatenationList.reduce((sum, info) => {
  227. switch(info.type) {
  228. case "concatenated":
  229. return sum + info.module.size();
  230. case "external":
  231. return sum + 5;
  232. }
  233. return sum;
  234. }, 0);
  235. }
  236. _createOrderedConcatenationList(rootModule, modulesSet) {
  237. const list = [];
  238. const set = new Set();
  239. function getConcatenatedImports(module) {
  240. // TODO need changes when merging with the pure-module branch
  241. const allDeps = module.dependencies
  242. .filter(dep => dep instanceof HarmonyImportDependency && dep.module);
  243. return allDeps.map(dep => () => dep.module);
  244. }
  245. function enterModule(getModule) {
  246. const module = getModule();
  247. if(set.has(module)) return;
  248. set.add(module);
  249. if(modulesSet.has(module)) {
  250. const imports = getConcatenatedImports(module);
  251. imports.forEach(enterModule);
  252. list.push({
  253. type: "concatenated",
  254. module
  255. });
  256. } else {
  257. list.push({
  258. type: "external",
  259. get module() {
  260. // We need to use a getter here, because the module in the dependency
  261. // could be replaced by some other process (i. e. also replaced with a
  262. // concatenated module)
  263. return getModule();
  264. }
  265. });
  266. }
  267. }
  268. enterModule(() => rootModule);
  269. return list;
  270. }
  271. _createIdentifier() {
  272. let orderedConcatenationListIdentifiers = "";
  273. for(let i = 0; i < this._orderedConcatenationList.length; i++) {
  274. if(this._orderedConcatenationList[i].type === "concatenated") {
  275. orderedConcatenationListIdentifiers += this._orderedConcatenationList[i].module.identifier();
  276. orderedConcatenationListIdentifiers += " ";
  277. }
  278. }
  279. const hash = crypto.createHash("md5");
  280. hash.update(orderedConcatenationListIdentifiers);
  281. return this.rootModule.identifier() + " " + hash.digest("hex");
  282. }
  283. source(dependencyTemplates, outputOptions, requestShortener) {
  284. // Metainfo for each module
  285. const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => {
  286. switch(info.type) {
  287. case "concatenated":
  288. {
  289. const exportMap = new Map();
  290. const reexportMap = new Map();
  291. info.module.dependencies.forEach(dep => {
  292. if(dep instanceof HarmonyExportSpecifierDependency) {
  293. if(!exportMap.has(dep.name))
  294. exportMap.set(dep.name, dep.id);
  295. } else if(dep instanceof HarmonyExportExpressionDependency) {
  296. if(!exportMap.has("default"))
  297. exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__");
  298. } else if(dep instanceof HarmonyExportImportedSpecifierDependency) {
  299. const exportName = dep.name;
  300. const importName = dep.id;
  301. const importedModule = dep.importDependency.module;
  302. if(exportName && importName) {
  303. if(!reexportMap.has(exportName)) {
  304. reexportMap.set(exportName, {
  305. module: importedModule,
  306. exportName: importName,
  307. dependency: dep
  308. });
  309. }
  310. } else if(exportName) {
  311. if(!reexportMap.has(exportName)) {
  312. reexportMap.set(exportName, {
  313. module: importedModule,
  314. exportName: true,
  315. dependency: dep
  316. });
  317. }
  318. } else if(importedModule) {
  319. importedModule.providedExports.forEach(name => {
  320. if(dep.activeExports.has(name) || name === "default")
  321. return;
  322. if(!reexportMap.has(name)) {
  323. reexportMap.set(name, {
  324. module: importedModule,
  325. exportName: name,
  326. dependency: dep
  327. });
  328. }
  329. });
  330. }
  331. }
  332. });
  333. return {
  334. type: "concatenated",
  335. module: info.module,
  336. index: idx,
  337. ast: undefined,
  338. source: undefined,
  339. globalScope: undefined,
  340. moduleScope: undefined,
  341. internalNames: new Map(),
  342. exportMap: exportMap,
  343. reexportMap: reexportMap,
  344. hasNamespaceObject: false,
  345. namespaceObjectSource: null
  346. };
  347. }
  348. case "external":
  349. return {
  350. type: "external",
  351. module: info.module,
  352. index: idx,
  353. name: undefined,
  354. interopName: undefined,
  355. interop: undefined
  356. };
  357. default:
  358. throw new Error(`Unsupported concatenation entry type ${info.type}`);
  359. }
  360. });
  361. // Create mapping from module to info
  362. const moduleToInfoMap = new Map();
  363. modulesWithInfo.forEach(m => moduleToInfoMap.set(m.module, m));
  364. // Configure template decorators for dependencies
  365. const innerDependencyTemplates = new Map(dependencyTemplates);
  366. innerDependencyTemplates.set(HarmonyImportSpecifierDependency, new HarmonyImportSpecifierDependencyConcatenatedTemplate(
  367. dependencyTemplates.get(HarmonyImportSpecifierDependency),
  368. moduleToInfoMap
  369. ));
  370. innerDependencyTemplates.set(HarmonyImportDependency, new HarmonyImportDependencyConcatenatedTemplate(
  371. dependencyTemplates.get(HarmonyImportDependency),
  372. moduleToInfoMap
  373. ));
  374. innerDependencyTemplates.set(HarmonyExportSpecifierDependency, new HarmonyExportSpecifierDependencyConcatenatedTemplate(
  375. dependencyTemplates.get(HarmonyExportSpecifierDependency),
  376. this.rootModule
  377. ));
  378. innerDependencyTemplates.set(HarmonyExportExpressionDependency, new HarmonyExportExpressionDependencyConcatenatedTemplate(
  379. dependencyTemplates.get(HarmonyExportExpressionDependency),
  380. this.rootModule,
  381. moduleToInfoMap
  382. ));
  383. innerDependencyTemplates.set(HarmonyExportImportedSpecifierDependency, new HarmonyExportImportedSpecifierDependencyConcatenatedTemplate(
  384. dependencyTemplates.get(HarmonyExportImportedSpecifierDependency),
  385. this.rootModule,
  386. moduleToInfoMap
  387. ));
  388. innerDependencyTemplates.set(HarmonyCompatibilityDependency, new HarmonyCompatibilityDependencyConcatenatedTemplate(
  389. dependencyTemplates.get(HarmonyCompatibilityDependency),
  390. this.rootModule,
  391. moduleToInfoMap
  392. ));
  393. innerDependencyTemplates.set("hash", innerDependencyTemplates.get("hash") + this.rootModule.identifier());
  394. // Generate source code and analyse scopes
  395. // Prepare a ReplaceSource for the final source
  396. modulesWithInfo.forEach(info => {
  397. if(info.type === "concatenated") {
  398. const m = info.module;
  399. const source = m.source(innerDependencyTemplates, outputOptions, requestShortener);
  400. const code = source.source();
  401. let ast;
  402. try {
  403. ast = acorn.parse(code, {
  404. ranges: true,
  405. locations: true,
  406. ecmaVersion: Parser.ECMA_VERSION,
  407. sourceType: "module"
  408. });
  409. } catch(err) {
  410. if(err.loc && typeof err.loc === "object" && typeof err.loc.line === "number") {
  411. const lineNumber = err.loc.line;
  412. const lines = code.split("\n");
  413. err.message += "\n| " + lines.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| ");
  414. }
  415. throw err;
  416. }
  417. const scopeManager = escope.analyze(ast, {
  418. ecmaVersion: 6,
  419. sourceType: "module",
  420. optimistic: true,
  421. ignoreEval: true,
  422. impliedStrict: true
  423. });
  424. const globalScope = scopeManager.acquire(ast);
  425. const moduleScope = globalScope.childScopes[0];
  426. const resultSource = new ReplaceSource(source);
  427. info.ast = ast;
  428. info.source = resultSource;
  429. info.globalScope = globalScope;
  430. info.moduleScope = moduleScope;
  431. }
  432. });
  433. // List of all used names to avoid conflicts
  434. const allUsedNames = new Set([
  435. "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name
  436. "abstract", "arguments", "async", "await", "boolean", "break", "byte", "case", "catch", "char", "class",
  437. "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "eval",
  438. "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if",
  439. "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new",
  440. "null", "package", "private", "protected", "public", "return", "short", "static", "super",
  441. "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof",
  442. "var", "void", "volatile", "while", "with", "yield",
  443. "module", "__dirname", "__filename", "exports",
  444. "Array", "Date", "eval", "function", "hasOwnProperty", "Infinity", "isFinite", "isNaN",
  445. "isPrototypeOf", "length", "Math", "NaN", "name", "Number", "Object", "prototype", "String",
  446. "toString", "undefined", "valueOf",
  447. "alert", "all", "anchor", "anchors", "area", "assign", "blur", "button", "checkbox",
  448. "clearInterval", "clearTimeout", "clientInformation", "close", "closed", "confirm", "constructor",
  449. "crypto", "decodeURI", "decodeURIComponent", "defaultStatus", "document", "element", "elements",
  450. "embed", "embeds", "encodeURI", "encodeURIComponent", "escape", "event", "fileUpload", "focus",
  451. "form", "forms", "frame", "innerHeight", "innerWidth", "layer", "layers", "link", "location",
  452. "mimeTypes", "navigate", "navigator", "frames", "frameRate", "hidden", "history", "image",
  453. "images", "offscreenBuffering", "open", "opener", "option", "outerHeight", "outerWidth",
  454. "packages", "pageXOffset", "pageYOffset", "parent", "parseFloat", "parseInt", "password", "pkcs11",
  455. "plugin", "prompt", "propertyIsEnum", "radio", "reset", "screenX", "screenY", "scroll", "secure",
  456. "select", "self", "setInterval", "setTimeout", "status", "submit", "taint", "text", "textarea",
  457. "top", "unescape", "untaint", "window",
  458. "onblur", "onclick", "onerror", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onmouseover",
  459. "onload", "onmouseup", "onmousedown", "onsubmit"
  460. ]);
  461. // get all global names
  462. modulesWithInfo.forEach(info => {
  463. if(info.globalScope) {
  464. info.globalScope.through.forEach(reference => {
  465. const name = reference.identifier.name;
  466. if(/^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?__$/.test(name)) {
  467. for(const s of getSymbolsFromScope(reference.from, info.moduleScope)) {
  468. allUsedNames.add(s);
  469. }
  470. } else {
  471. allUsedNames.add(name);
  472. }
  473. });
  474. }
  475. });
  476. // generate names for symbols
  477. modulesWithInfo.forEach(info => {
  478. switch(info.type) {
  479. case "concatenated":
  480. {
  481. const namespaceObjectName = this.findNewName("namespaceObject", allUsedNames, null, info.module.readableIdentifier(requestShortener));
  482. allUsedNames.add(namespaceObjectName);
  483. info.internalNames.set(namespaceObjectName, namespaceObjectName);
  484. info.exportMap.set(true, namespaceObjectName);
  485. info.moduleScope.variables.forEach(variable => {
  486. const name = variable.name;
  487. if(allUsedNames.has(name)) {
  488. const references = getAllReferences(variable);
  489. const symbolsInReferences = references.map(ref => getSymbolsFromScope(ref.from, info.moduleScope)).reduce(reduceSet, new Set());
  490. const newName = this.findNewName(name, allUsedNames, symbolsInReferences, info.module.readableIdentifier(requestShortener));
  491. allUsedNames.add(newName);
  492. info.internalNames.set(name, newName);
  493. const source = info.source;
  494. const allIdentifiers = new Set(references.map(r => r.identifier).concat(variable.identifiers));
  495. for(const identifier of allIdentifiers) {
  496. const r = identifier.range;
  497. const path = getPathInAst(info.ast, identifier);
  498. if(path && path.length > 1 && path[1].type === "Property" && path[1].shorthand) {
  499. source.insert(r[1], `: ${newName}`);
  500. } else {
  501. source.replace(r[0], r[1] - 1, newName);
  502. }
  503. }
  504. } else {
  505. allUsedNames.add(name);
  506. info.internalNames.set(name, name);
  507. }
  508. });
  509. break;
  510. }
  511. case "external":
  512. {
  513. info.interop = info.module.meta && !info.module.meta.harmonyModule;
  514. const externalName = this.findNewName("", allUsedNames, null, info.module.readableIdentifier(requestShortener));
  515. allUsedNames.add(externalName);
  516. info.name = externalName;
  517. if(info.interop) {
  518. const externalNameInterop = this.findNewName("default", allUsedNames, null, info.module.readableIdentifier(requestShortener));
  519. allUsedNames.add(externalNameInterop);
  520. info.interopName = externalNameInterop;
  521. }
  522. break;
  523. }
  524. }
  525. });
  526. // Find and replace referenced to modules
  527. modulesWithInfo.forEach(info => {
  528. if(info.type === "concatenated") {
  529. info.globalScope.through.forEach(reference => {
  530. const name = reference.identifier.name;
  531. const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?__$/.exec(name);
  532. if(match) {
  533. const referencedModule = modulesWithInfo[+match[1]];
  534. let exportName;
  535. if(match[2] === "ns") {
  536. exportName = true;
  537. } else {
  538. const exportData = match[2];
  539. exportName = new Buffer(exportData, "hex").toString("utf-8"); // eslint-disable-line node/no-deprecated-api
  540. }
  541. const asCall = !!match[3];
  542. const finalName = getFinalName(referencedModule, exportName, moduleToInfoMap, requestShortener, asCall);
  543. const r = reference.identifier.range;
  544. const source = info.source;
  545. source.replace(r[0], r[1] - 1, finalName);
  546. }
  547. });
  548. }
  549. });
  550. const result = new ConcatSource();
  551. // add harmony compatibility flag (must be first because of possible circular dependencies)
  552. const usedExports = this.rootModule.usedExports;
  553. if(usedExports === true) {
  554. result.add(`Object.defineProperty(${this.exportsArgument || "exports"}, "__esModule", { value: true });\n`);
  555. }
  556. // define required namespace objects (must be before evaluation modules)
  557. modulesWithInfo.forEach(info => {
  558. if(info.namespaceObjectSource) {
  559. result.add(info.namespaceObjectSource);
  560. }
  561. });
  562. // evaluate modules in order
  563. modulesWithInfo.forEach(info => {
  564. switch(info.type) {
  565. case "concatenated":
  566. result.add(`\n// CONCATENATED MODULE: ${info.module.readableIdentifier(requestShortener)}\n`);
  567. result.add(info.source);
  568. break;
  569. case "external":
  570. result.add(`\n// EXTERNAL MODULE: ${info.module.readableIdentifier(requestShortener)}\n`);
  571. result.add(`var ${info.name} = __webpack_require__(${JSON.stringify(info.module.id)});\n`);
  572. if(info.interop) {
  573. result.add(`var ${info.interopName} = /*#__PURE__*/__webpack_require__.n(${info.name});\n`);
  574. }
  575. break;
  576. default:
  577. throw new Error(`Unsupported concatenation entry type ${info.type}`);
  578. }
  579. });
  580. return result;
  581. }
  582. findNewName(oldName, usedNamed1, usedNamed2, extraInfo) {
  583. let name = oldName;
  584. if(name === "__WEBPACK_MODULE_DEFAULT_EXPORT__")
  585. name = "";
  586. // Remove uncool stuff
  587. extraInfo = extraInfo.replace(/\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, "");
  588. const splittedInfo = extraInfo.split("/");
  589. while(splittedInfo.length) {
  590. name = splittedInfo.pop() + (name ? "_" + name : "");
  591. const nameIdent = Template.toIdentifier(name);
  592. if(!usedNamed1.has(nameIdent) && (!usedNamed2 || !usedNamed2.has(nameIdent))) return nameIdent;
  593. }
  594. let i = 0;
  595. let nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  596. while(usedNamed1.has(nameWithNumber) || (usedNamed2 && usedNamed2.has(nameWithNumber))) {
  597. i++;
  598. nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  599. }
  600. return nameWithNumber;
  601. }
  602. updateHash(hash) {
  603. for(const info of this._orderedConcatenationList) {
  604. switch(info.type) {
  605. case "concatenated":
  606. info.module.updateHash(hash);
  607. break;
  608. case "external":
  609. hash.update(`${info.module.id}`);
  610. break;
  611. }
  612. }
  613. super.updateHash(hash);
  614. }
  615. }
  616. class HarmonyImportSpecifierDependencyConcatenatedTemplate {
  617. constructor(originalTemplate, modulesMap) {
  618. this.originalTemplate = originalTemplate;
  619. this.modulesMap = modulesMap;
  620. }
  621. apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
  622. const module = dep.importDependency.module;
  623. const info = this.modulesMap.get(module);
  624. if(!info) {
  625. this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
  626. return;
  627. }
  628. let content;
  629. if(dep.id === null) {
  630. content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__`;
  631. } else if(dep.namespaceObjectAsContext) {
  632. content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__[${JSON.stringify(dep.id)}]`;
  633. } else {
  634. const exportData = new Buffer(dep.id, "utf-8").toString("hex"); // eslint-disable-line node/no-deprecated-api
  635. content = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${dep.call ? "_call" : ""}__`;
  636. }
  637. if(dep.shorthand) {
  638. content = dep.name + ": " + content;
  639. }
  640. source.replace(dep.range[0], dep.range[1] - 1, content);
  641. }
  642. }
  643. class HarmonyImportDependencyConcatenatedTemplate {
  644. constructor(originalTemplate, modulesMap) {
  645. this.originalTemplate = originalTemplate;
  646. this.modulesMap = modulesMap;
  647. }
  648. apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
  649. const module = dep.module;
  650. const info = this.modulesMap.get(module);
  651. if(!info) {
  652. this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
  653. return;
  654. }
  655. source.replace(dep.range[0], dep.range[1] - 1, "");
  656. }
  657. }
  658. class HarmonyExportSpecifierDependencyConcatenatedTemplate {
  659. constructor(originalTemplate, rootModule) {
  660. this.originalTemplate = originalTemplate;
  661. this.rootModule = rootModule;
  662. }
  663. apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
  664. if(dep.originModule === this.rootModule) {
  665. this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
  666. }
  667. }
  668. }
  669. class HarmonyExportExpressionDependencyConcatenatedTemplate {
  670. constructor(originalTemplate, rootModule) {
  671. this.originalTemplate = originalTemplate;
  672. this.rootModule = rootModule;
  673. }
  674. apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
  675. let content = "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = ";
  676. if(dep.originModule === this.rootModule) {
  677. const used = dep.originModule.isUsed("default");
  678. const exportsName = dep.originModule.exportsArgument || "exports";
  679. if(used) content += `${exportsName}[${JSON.stringify(used)}] = `;
  680. }
  681. if(dep.range) {
  682. source.replace(dep.rangeStatement[0], dep.range[0] - 1, content + "(");
  683. source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");");
  684. return;
  685. }
  686. source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content);
  687. }
  688. }
  689. class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate {
  690. constructor(originalTemplate, rootModule, modulesMap) {
  691. this.originalTemplate = originalTemplate;
  692. this.rootModule = rootModule;
  693. this.modulesMap = modulesMap;
  694. }
  695. getExports(dep) {
  696. const importModule = dep.importDependency.module;
  697. if(dep.id) {
  698. // export { named } from "module"
  699. return [{
  700. name: dep.name,
  701. id: dep.id,
  702. module: importModule
  703. }];
  704. }
  705. if(dep.name) {
  706. // export * as abc from "module"
  707. return [{
  708. name: dep.name,
  709. id: true,
  710. module: importModule
  711. }];
  712. }
  713. // export * from "module"
  714. return importModule.providedExports.filter(exp => exp !== "default" && !dep.activeExports.has(exp)).map(exp => {
  715. return {
  716. name: exp,
  717. id: exp,
  718. module: importModule
  719. };
  720. });
  721. }
  722. apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
  723. if(dep.originModule === this.rootModule) {
  724. if(this.modulesMap.get(dep.importDependency.module)) {
  725. const exportDefs = this.getExports(dep);
  726. exportDefs.forEach(def => {
  727. const info = this.modulesMap.get(def.module);
  728. const used = dep.originModule.isUsed(def.name);
  729. if(!used) {
  730. source.insert(-1, `/* unused concated harmony import ${dep.name} */\n`);
  731. }
  732. let finalName;
  733. if(def.id === true) {
  734. finalName = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__`;
  735. } else {
  736. const exportData = new Buffer(def.id, "utf-8").toString("hex"); // eslint-disable-line node/no-deprecated-api
  737. finalName = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}__`;
  738. }
  739. const exportsName = this.rootModule.exportsArgument || "exports";
  740. const content = `/* concated harmony reexport */__webpack_require__.d(${exportsName}, ${JSON.stringify(used)}, function() { return ${finalName}; });\n`;
  741. source.insert(-1, content);
  742. });
  743. } else {
  744. this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
  745. }
  746. }
  747. }
  748. }
  749. class HarmonyCompatibilityDependencyConcatenatedTemplate {
  750. constructor(originalTemplate, rootModule, modulesMap) {
  751. this.originalTemplate = originalTemplate;
  752. this.rootModule = rootModule;
  753. this.modulesMap = modulesMap;
  754. }
  755. apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
  756. // do nothing
  757. }
  758. }
  759. module.exports = ConcatenatedModule;