a zip code crypto-currency system good for red ONLY

ConcatenatedModule.js 29KB

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