ConcatenatedModule.js 29 KB

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