next-drop-client-page-plugin.js 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.ampFirstEntryNamesMap = void 0;
  6. var _constants = require("../../../shared/lib/constants");
  7. const ampFirstEntryNamesMap = new WeakMap();
  8. exports.ampFirstEntryNamesMap = ampFirstEntryNamesMap;
  9. const PLUGIN_NAME = "DropAmpFirstPagesPlugin";
  10. class DropClientPage {
  11. ampPages = new Set();
  12. apply(compiler) {
  13. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
  14. // Recursively look up the issuer till it ends up at the root
  15. function findEntryModule(mod) {
  16. const queue = new Set([
  17. mod
  18. ]);
  19. for (const module of queue){
  20. // @ts-ignore TODO: webpack 5 types
  21. const incomingConnections = compilation.moduleGraph.getIncomingConnections(module);
  22. for (const incomingConnection of incomingConnections){
  23. if (!incomingConnection.originModule) return module;
  24. queue.add(incomingConnection.originModule);
  25. }
  26. }
  27. return null;
  28. }
  29. function handler(parser) {
  30. function markAsAmpFirst() {
  31. const entryModule = findEntryModule(parser.state.module);
  32. if (!entryModule) {
  33. return;
  34. }
  35. // @ts-ignore buildInfo exists on Module
  36. entryModule.buildInfo.NEXT_ampFirst = true;
  37. }
  38. parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator)=>{
  39. var ref;
  40. if ((declarator == null ? void 0 : (ref = declarator.id) == null ? void 0 : ref.name) === _constants.STRING_LITERAL_DROP_BUNDLE) {
  41. markAsAmpFirst();
  42. }
  43. });
  44. }
  45. normalModuleFactory.hooks.parser.for("javascript/auto").tap(PLUGIN_NAME, handler);
  46. normalModuleFactory.hooks.parser.for("javascript/esm").tap(PLUGIN_NAME, handler);
  47. normalModuleFactory.hooks.parser.for("javascript/dynamic").tap(PLUGIN_NAME, handler);
  48. if (!ampFirstEntryNamesMap.has(compilation)) {
  49. ampFirstEntryNamesMap.set(compilation, []);
  50. }
  51. const ampFirstEntryNamesItem = ampFirstEntryNamesMap.get(compilation);
  52. compilation.hooks.seal.tap(PLUGIN_NAME, ()=>{
  53. for (const [name, entryData] of compilation.entries){
  54. for (const dependency of entryData.dependencies){
  55. var ref;
  56. // @ts-ignore TODO: webpack 5 types
  57. const module = compilation.moduleGraph.getModule(dependency);
  58. if (module == null ? void 0 : (ref = module.buildInfo) == null ? void 0 : ref.NEXT_ampFirst) {
  59. ampFirstEntryNamesItem.push(name);
  60. // @ts-ignore @types/webpack has outdated types for webpack 5
  61. compilation.entries.delete(name);
  62. }
  63. }
  64. }
  65. });
  66. });
  67. }
  68. }
  69. exports.DropClientPage = DropClientPage;
  70. //# sourceMappingURL=next-drop-client-page-plugin.js.map