JavascriptMetaInfoPlugin.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  4. */
  5. "use strict";
  6. const {
  7. JAVASCRIPT_MODULE_TYPE_AUTO,
  8. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  9. JAVASCRIPT_MODULE_TYPE_ESM
  10. } = require("./ModuleTypeConstants");
  11. const InnerGraph = require("./optimize/InnerGraph");
  12. /** @typedef {import("./Compiler")} Compiler */
  13. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  14. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  15. const PLUGIN_NAME = "JavascriptMetaInfoPlugin";
  16. class JavascriptMetaInfoPlugin {
  17. /**
  18. * Apply the plugin
  19. * @param {Compiler} compiler the compiler instance
  20. * @returns {void}
  21. */
  22. apply(compiler) {
  23. compiler.hooks.compilation.tap(
  24. PLUGIN_NAME,
  25. (compilation, { normalModuleFactory }) => {
  26. /**
  27. * @param {JavascriptParser} parser the parser
  28. * @returns {void}
  29. */
  30. const handler = parser => {
  31. parser.hooks.call.for("eval").tap(PLUGIN_NAME, () => {
  32. const buildInfo =
  33. /** @type {BuildInfo} */
  34. (parser.state.module.buildInfo);
  35. buildInfo.moduleConcatenationBailout = "eval()";
  36. buildInfo.usingEval = true;
  37. const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state);
  38. if (currentSymbol) {
  39. InnerGraph.addUsage(parser.state, null, currentSymbol);
  40. } else {
  41. InnerGraph.bailout(parser.state);
  42. }
  43. });
  44. parser.hooks.finish.tap(PLUGIN_NAME, () => {
  45. const buildInfo =
  46. /** @type {BuildInfo} */
  47. (parser.state.module.buildInfo);
  48. let topLevelDeclarations = buildInfo.topLevelDeclarations;
  49. if (topLevelDeclarations === undefined) {
  50. topLevelDeclarations = buildInfo.topLevelDeclarations = new Set();
  51. }
  52. for (const name of parser.scope.definitions.asSet()) {
  53. const freeInfo = parser.getFreeInfoFromVariable(name);
  54. if (freeInfo === undefined) {
  55. topLevelDeclarations.add(name);
  56. }
  57. }
  58. });
  59. };
  60. normalModuleFactory.hooks.parser
  61. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  62. .tap(PLUGIN_NAME, handler);
  63. normalModuleFactory.hooks.parser
  64. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  65. .tap(PLUGIN_NAME, handler);
  66. normalModuleFactory.hooks.parser
  67. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  68. .tap(PLUGIN_NAME, handler);
  69. }
  70. );
  71. }
  72. }
  73. module.exports = JavascriptMetaInfoPlugin;