JavascriptGenerator.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const { RawSource, ReplaceSource } = require("webpack-sources");
  8. const Generator = require("../Generator");
  9. const InitFragment = require("../InitFragment");
  10. const { JS_TYPES } = require("../ModuleSourceTypesConstants");
  11. const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency");
  12. /** @typedef {import("webpack-sources").Source} Source */
  13. /** @typedef {import("../DependenciesBlock")} DependenciesBlock */
  14. /** @typedef {import("../Dependency")} Dependency */
  15. /** @typedef {import("../DependencyTemplate")} DependencyTemplate */
  16. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  17. /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
  18. /** @typedef {import("../Generator").GenerateContext} GenerateContext */
  19. /** @typedef {import("../Module")} Module */
  20. /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
  21. /** @typedef {import("../Module").SourceTypes} SourceTypes */
  22. /** @typedef {import("../NormalModule")} NormalModule */
  23. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  24. const DEFAULT_SOURCE = {
  25. source() {
  26. return new RawSource("throw new Error('No source available');");
  27. },
  28. /**
  29. * @returns {number} size of the DEFAULT_SOURCE.source()
  30. */
  31. size() {
  32. return 39;
  33. }
  34. };
  35. // TODO: clean up this file
  36. // replace with newer constructs
  37. const deprecatedGetInitFragments = util.deprecate(
  38. /**
  39. * @param {DependencyTemplate} template template
  40. * @param {Dependency} dependency dependency
  41. * @param {DependencyTemplateContext} templateContext template context
  42. * @returns {InitFragment<GenerateContext>[]} init fragments
  43. */
  44. (template, dependency, templateContext) =>
  45. /** @type {DependencyTemplate & { getInitFragments: (dependency: Dependency, dependencyTemplateContext: DependencyTemplateContext) => InitFragment<GenerateContext>[] }} */
  46. (template).getInitFragments(dependency, templateContext),
  47. "DependencyTemplate.getInitFragment is deprecated (use apply(dep, source, { initFragments }) instead)",
  48. "DEP_WEBPACK_JAVASCRIPT_GENERATOR_GET_INIT_FRAGMENTS"
  49. );
  50. class JavascriptGenerator extends Generator {
  51. /**
  52. * @param {NormalModule} module fresh module
  53. * @returns {SourceTypes} available types (do not mutate)
  54. */
  55. getTypes(module) {
  56. return JS_TYPES;
  57. }
  58. /**
  59. * @param {NormalModule} module the module
  60. * @param {string=} type source type
  61. * @returns {number} estimate size of the module
  62. */
  63. getSize(module, type) {
  64. const originalSource = module.originalSource();
  65. if (!originalSource) {
  66. return DEFAULT_SOURCE.size();
  67. }
  68. return originalSource.size();
  69. }
  70. /**
  71. * @param {NormalModule} module module for which the bailout reason should be determined
  72. * @param {ConcatenationBailoutReasonContext} context context
  73. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  74. */
  75. getConcatenationBailoutReason(module, context) {
  76. // Only harmony modules are valid for optimization
  77. if (
  78. !module.buildMeta ||
  79. module.buildMeta.exportsType !== "namespace" ||
  80. module.presentationalDependencies === undefined ||
  81. !module.presentationalDependencies.some(
  82. d => d instanceof HarmonyCompatibilityDependency
  83. )
  84. ) {
  85. return "Module is not an ECMAScript module";
  86. }
  87. // Some expressions are not compatible with module concatenation
  88. // because they may produce unexpected results. The plugin bails out
  89. // if some were detected upfront.
  90. if (module.buildInfo && module.buildInfo.moduleConcatenationBailout) {
  91. return `Module uses ${module.buildInfo.moduleConcatenationBailout}`;
  92. }
  93. }
  94. /**
  95. * @param {NormalModule} module module for which the code should be generated
  96. * @param {GenerateContext} generateContext context for generate
  97. * @returns {Source | null} generated code
  98. */
  99. generate(module, generateContext) {
  100. const originalSource = module.originalSource();
  101. if (!originalSource) {
  102. return DEFAULT_SOURCE.source();
  103. }
  104. const source = new ReplaceSource(originalSource);
  105. /** @type {InitFragment<GenerateContext>[]} */
  106. const initFragments = [];
  107. this.sourceModule(module, initFragments, source, generateContext);
  108. return InitFragment.addToSource(source, initFragments, generateContext);
  109. }
  110. /**
  111. * @param {Error} error the error
  112. * @param {NormalModule} module module for which the code should be generated
  113. * @param {GenerateContext} generateContext context for generate
  114. * @returns {Source | null} generated code
  115. */
  116. generateError(error, module, generateContext) {
  117. return new RawSource(`throw new Error(${JSON.stringify(error.message)});`);
  118. }
  119. /**
  120. * @param {Module} module the module to generate
  121. * @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments
  122. * @param {ReplaceSource} source the current replace source which can be modified
  123. * @param {GenerateContext} generateContext the generateContext
  124. * @returns {void}
  125. */
  126. sourceModule(module, initFragments, source, generateContext) {
  127. for (const dependency of module.dependencies) {
  128. this.sourceDependency(
  129. module,
  130. dependency,
  131. initFragments,
  132. source,
  133. generateContext
  134. );
  135. }
  136. if (module.presentationalDependencies !== undefined) {
  137. for (const dependency of module.presentationalDependencies) {
  138. this.sourceDependency(
  139. module,
  140. dependency,
  141. initFragments,
  142. source,
  143. generateContext
  144. );
  145. }
  146. }
  147. for (const childBlock of module.blocks) {
  148. this.sourceBlock(
  149. module,
  150. childBlock,
  151. initFragments,
  152. source,
  153. generateContext
  154. );
  155. }
  156. }
  157. /**
  158. * @param {Module} module the module to generate
  159. * @param {DependenciesBlock} block the dependencies block which will be processed
  160. * @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments
  161. * @param {ReplaceSource} source the current replace source which can be modified
  162. * @param {GenerateContext} generateContext the generateContext
  163. * @returns {void}
  164. */
  165. sourceBlock(module, block, initFragments, source, generateContext) {
  166. for (const dependency of block.dependencies) {
  167. this.sourceDependency(
  168. module,
  169. dependency,
  170. initFragments,
  171. source,
  172. generateContext
  173. );
  174. }
  175. for (const childBlock of block.blocks) {
  176. this.sourceBlock(
  177. module,
  178. childBlock,
  179. initFragments,
  180. source,
  181. generateContext
  182. );
  183. }
  184. }
  185. /**
  186. * @param {Module} module the current module
  187. * @param {Dependency} dependency the dependency to generate
  188. * @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments
  189. * @param {ReplaceSource} source the current replace source which can be modified
  190. * @param {GenerateContext} generateContext the render context
  191. * @returns {void}
  192. */
  193. sourceDependency(module, dependency, initFragments, source, generateContext) {
  194. const constructor =
  195. /** @type {new (...args: EXPECTED_ANY[]) => Dependency} */
  196. (dependency.constructor);
  197. const template = generateContext.dependencyTemplates.get(constructor);
  198. if (!template) {
  199. throw new Error(
  200. `No template for dependency: ${dependency.constructor.name}`
  201. );
  202. }
  203. /** @type {InitFragment<GenerateContext>[] | undefined} */
  204. let chunkInitFragments;
  205. /** @type {DependencyTemplateContext} */
  206. const templateContext = {
  207. runtimeTemplate: generateContext.runtimeTemplate,
  208. dependencyTemplates: generateContext.dependencyTemplates,
  209. moduleGraph: generateContext.moduleGraph,
  210. chunkGraph: generateContext.chunkGraph,
  211. module,
  212. runtime: generateContext.runtime,
  213. runtimeRequirements: generateContext.runtimeRequirements,
  214. concatenationScope: generateContext.concatenationScope,
  215. codeGenerationResults:
  216. /** @type {NonNullable<GenerateContext["codeGenerationResults"]>} */
  217. (generateContext.codeGenerationResults),
  218. initFragments,
  219. get chunkInitFragments() {
  220. if (!chunkInitFragments) {
  221. const data =
  222. /** @type {NonNullable<GenerateContext["getData"]>} */
  223. (generateContext.getData)();
  224. chunkInitFragments = data.get("chunkInitFragments");
  225. if (!chunkInitFragments) {
  226. chunkInitFragments = [];
  227. data.set("chunkInitFragments", chunkInitFragments);
  228. }
  229. }
  230. return chunkInitFragments;
  231. }
  232. };
  233. template.apply(dependency, source, templateContext);
  234. // TODO remove in webpack 6
  235. if ("getInitFragments" in template) {
  236. const fragments = deprecatedGetInitFragments(
  237. template,
  238. dependency,
  239. templateContext
  240. );
  241. if (fragments) {
  242. for (const fragment of fragments) {
  243. initFragments.push(fragment);
  244. }
  245. }
  246. }
  247. }
  248. }
  249. module.exports = JavascriptGenerator;