@depup/webpack 5.109.2-depup.0 → 5.110.3-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (647) hide show
  1. package/README.md +5 -5
  2. package/changes.json +7 -7
  3. package/lib/APIPlugin.js +123 -17
  4. package/lib/AsyncDependenciesBlock.js +10 -7
  5. package/lib/AutomaticPrefetchPlugin.js +1 -1
  6. package/lib/BannerPlugin.js +10 -6
  7. package/lib/CacheFacade.js +6 -6
  8. package/lib/Chunk.js +14 -11
  9. package/lib/ChunkGraph.js +46 -35
  10. package/lib/ChunkGroup.js +7 -7
  11. package/lib/ChunkTemplate.js +35 -44
  12. package/lib/CircularModulesPlugin.js +205 -28
  13. package/lib/CleanPlugin.js +4 -7
  14. package/lib/CodeGenerationResults.js +11 -8
  15. package/lib/CompatibilityPlugin.js +7 -7
  16. package/lib/Compilation.js +688 -409
  17. package/lib/Compiler.js +53 -38
  18. package/lib/ConcatenationScope.js +107 -8
  19. package/lib/ConditionalInitFragment.js +3 -3
  20. package/lib/ConstPlugin.js +13 -11
  21. package/lib/ContextExclusionPlugin.js +1 -1
  22. package/lib/ContextModule.js +146 -54
  23. package/lib/ContextModuleFactory.js +46 -14
  24. package/lib/ContextReplacementPlugin.js +12 -14
  25. package/lib/DefinePlugin.js +121 -37
  26. package/lib/DependenciesBlock.js +9 -6
  27. package/lib/Dependency.js +36 -16
  28. package/lib/DependencyTemplate.js +11 -12
  29. package/lib/DependencyTemplates.js +3 -3
  30. package/lib/DotenvPlugin.js +91 -26
  31. package/lib/DynamicEntryPlugin.js +8 -4
  32. package/lib/EntryOptionPlugin.js +8 -4
  33. package/lib/EntryPlugin.js +2 -2
  34. package/lib/Entrypoint.js +6 -2
  35. package/lib/EnvironmentPlugin.js +2 -2
  36. package/lib/EvalDevToolModulePlugin.js +8 -4
  37. package/lib/EvalSourceMapDevToolPlugin.js +15 -8
  38. package/lib/ExportsInfo.js +111 -14
  39. package/lib/ExportsInfoApiPlugin.js +2 -4
  40. package/lib/ExternalModule.js +232 -77
  41. package/lib/ExternalModuleFactoryPlugin.js +97 -38
  42. package/lib/ExternalsPlugin.js +10 -6
  43. package/lib/FileSystemInfo.js +44 -70
  44. package/lib/FlagAllModulesAsUsedPlugin.js +2 -3
  45. package/lib/FlagDependencyExportsPlugin.js +76 -19
  46. package/lib/FlagDependencyUsagePlugin.js +40 -49
  47. package/lib/FlagEntryExportAsUsedPlugin.js +1 -1
  48. package/lib/Generator.js +36 -15
  49. package/lib/HotModuleReplacementPlugin.js +16 -44
  50. package/lib/IgnorePlugin.js +8 -4
  51. package/lib/IgnoreWarningsPlugin.js +2 -2
  52. package/lib/InitFragment.js +8 -4
  53. package/lib/JavascriptMetaInfoPlugin.js +35 -4
  54. package/lib/LazyBarrel.js +3 -4
  55. package/lib/LibraryTemplatePlugin.js +10 -6
  56. package/lib/LoaderOptionsPlugin.js +7 -3
  57. package/lib/LoaderTargetPlugin.js +1 -1
  58. package/lib/MainTemplate.js +49 -42
  59. package/lib/ManifestPlugin.js +12 -11
  60. package/lib/Module.js +62 -33
  61. package/lib/ModuleFactory.js +3 -3
  62. package/lib/ModuleFilenameHelpers.js +9 -4
  63. package/lib/ModuleGraph.js +195 -21
  64. package/lib/ModuleGraphConnection.js +6 -13
  65. package/lib/ModuleInfoHeaderPlugin.js +8 -10
  66. package/lib/ModuleTemplate.js +62 -63
  67. package/lib/MultiCompiler.js +130 -64
  68. package/lib/MultiStats.js +40 -9
  69. package/lib/MultiWatching.js +3 -3
  70. package/lib/NoEmitOnErrorsPlugin.js +1 -1
  71. package/lib/NodeStuffPlugin.js +29 -19
  72. package/lib/NormalModule.js +152 -103
  73. package/lib/NormalModuleFactory.js +555 -110
  74. package/lib/NormalModuleReplacementPlugin.js +5 -8
  75. package/lib/NullFactory.js +6 -2
  76. package/lib/OptionsApply.js +7 -3
  77. package/lib/Parser.js +7 -3
  78. package/lib/PlatformPlugin.js +2 -2
  79. package/lib/PrefetchPlugin.js +1 -1
  80. package/lib/ProgressPlugin.js +16 -13
  81. package/lib/ProvidePlugin.js +3 -5
  82. package/lib/RawModule.js +25 -17
  83. package/lib/RecordIdsPlugin.js +3 -3
  84. package/lib/RequestShortener.js +1 -1
  85. package/lib/ResolverFactory.js +2 -2
  86. package/lib/RuntimeGlobals.js +22 -10
  87. package/lib/RuntimeModule.js +29 -19
  88. package/lib/RuntimePlugin.js +335 -169
  89. package/lib/RuntimeTemplate.js +2761 -316
  90. package/lib/SelfModuleFactory.js +7 -3
  91. package/lib/SourceMapDevToolModuleOptionsPlugin.js +6 -2
  92. package/lib/SourceMapDevToolPlugin.js +30 -20
  93. package/lib/Stats.js +3 -4
  94. package/lib/Template.js +32 -22
  95. package/lib/TemplatedPathPlugin.js +96 -14
  96. package/lib/UseStrictPlugin.js +4 -6
  97. package/lib/WarnCaseSensitiveModulesPlugin.js +4 -4
  98. package/lib/WarnDeprecatedOptionPlugin.js +1 -1
  99. package/lib/WarnNoModeSetPlugin.js +1 -1
  100. package/lib/WatchIgnorePlugin.js +8 -6
  101. package/lib/Watching.js +8 -8
  102. package/lib/WebpackIsIncludedPlugin.js +2 -4
  103. package/lib/WebpackOptionsApply.js +308 -18
  104. package/lib/WebpackOptionsDefaulter.js +6 -2
  105. package/lib/asset/AssetBytesGenerator.js +12 -10
  106. package/lib/asset/AssetBytesParser.js +2 -4
  107. package/lib/asset/AssetGenerator.js +188 -95
  108. package/lib/asset/AssetModule.js +7 -3
  109. package/lib/asset/AssetModulesPlugin.js +110 -38
  110. package/lib/asset/AssetParser.js +9 -7
  111. package/lib/asset/AssetSourceGenerator.js +60 -13
  112. package/lib/asset/AssetSourceParser.js +2 -4
  113. package/lib/asset/RawDataUrlModule.js +24 -16
  114. package/lib/asset/WebManifestGenerator.js +8 -10
  115. package/lib/asset/WebManifestParser.js +24 -10
  116. package/lib/async-modules/AsyncModuleHelpers.js +12 -6
  117. package/lib/async-modules/AwaitDependenciesInitFragment.js +2 -2
  118. package/lib/async-modules/InferAsyncModulesPlugin.js +2 -2
  119. package/lib/async-modules/isGeneratorLowered.js +4 -4
  120. package/lib/buildChunkGraph.js +36 -27
  121. package/lib/bun/BunTargetPlugin.js +1 -1
  122. package/lib/cache/AddBuildDependenciesPlugin.js +1 -1
  123. package/lib/cache/AddManagedPathsPlugin.js +1 -1
  124. package/lib/cache/IdleFileCachePlugin.js +2 -2
  125. package/lib/cache/MemoryCachePlugin.js +18 -10
  126. package/lib/cache/MemoryWithGcCachePlugin.js +34 -22
  127. package/lib/cache/PackFileCacheStrategy.js +30 -23
  128. package/lib/cache/ResolverCachePlugin.js +38 -18
  129. package/lib/cache/getLazyHashedEtag.js +1 -2
  130. package/lib/cache/mergeEtags.js +1 -1
  131. package/lib/cli.js +1 -3
  132. package/lib/config/browserslistTargetHandler.js +41 -5
  133. package/lib/config/defaults.js +270 -78
  134. package/lib/config/defineConfig.js +10 -2
  135. package/lib/config/getClaimedAssetTypes.js +65 -0
  136. package/lib/config/normalization.js +46 -16
  137. package/lib/config/target.js +46 -3
  138. package/lib/container/ContainerEntryDependency.js +1 -1
  139. package/lib/container/ContainerEntryModule.js +24 -15
  140. package/lib/container/ContainerEntryModuleFactory.js +7 -3
  141. package/lib/container/ContainerPlugin.js +9 -10
  142. package/lib/container/ContainerReferencePlugin.js +6 -2
  143. package/lib/container/FallbackDependency.js +1 -1
  144. package/lib/container/FallbackModule.js +24 -17
  145. package/lib/container/FallbackModuleFactory.js +7 -3
  146. package/lib/container/HoistContainerReferencesPlugin.js +6 -11
  147. package/lib/container/ModuleFederationPlugin.js +7 -24
  148. package/lib/container/RemoteModule.js +27 -19
  149. package/lib/container/RemoteRuntimeModule.js +10 -8
  150. package/lib/container/moduleFederationHooks.js +32 -0
  151. package/lib/css/CssGenerator.js +171 -43
  152. package/lib/css/CssInjectStyleRuntimeModule.js +7 -5
  153. package/lib/css/CssLoadingRuntimeModule.js +84 -32
  154. package/lib/css/CssModule.js +10 -7
  155. package/lib/css/CssModulesPlugin.js +172 -100
  156. package/lib/css/CssParser.js +1113 -568
  157. package/lib/css/CssServerStylesRuntimeModule.js +54 -0
  158. package/lib/css/cssMinify.js +168 -0
  159. package/lib/css/data.js +5334 -0
  160. package/lib/css/syntax.js +9647 -232
  161. package/lib/debug/ProfilingPlugin.js +14 -9
  162. package/lib/deno/DenoTargetPlugin.js +1 -1
  163. package/lib/dependencies/AMDDefineDependency.js +112 -87
  164. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +30 -17
  165. package/lib/dependencies/AMDPlugin.js +9 -7
  166. package/lib/dependencies/AMDRequireArrayDependency.js +5 -5
  167. package/lib/dependencies/AMDRequireContextDependency.js +2 -2
  168. package/lib/dependencies/AMDRequireDependenciesBlock.js +1 -1
  169. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +25 -14
  170. package/lib/dependencies/AMDRequireDependency.js +8 -7
  171. package/lib/dependencies/AMDRequireItemDependency.js +1 -1
  172. package/lib/dependencies/AMDRuntimeModules.js +21 -1
  173. package/lib/dependencies/BuildTimeConstDependency.js +102 -0
  174. package/lib/dependencies/CachedConstDependency.js +11 -8
  175. package/lib/dependencies/CommonJsDependencyHelpers.js +67 -46
  176. package/lib/dependencies/CommonJsExportRequireDependency.js +121 -45
  177. package/lib/dependencies/CommonJsExportsDependency.js +53 -49
  178. package/lib/dependencies/CommonJsExportsParserPlugin.js +207 -25
  179. package/lib/dependencies/CommonJsFullRequireDependency.js +119 -34
  180. package/lib/dependencies/CommonJsImportsParserPlugin.js +100 -50
  181. package/lib/dependencies/CommonJsObjectExportDependency.js +188 -0
  182. package/lib/dependencies/CommonJsPlugin.js +35 -6
  183. package/lib/dependencies/CommonJsRequireContextDependency.js +5 -6
  184. package/lib/dependencies/CommonJsRequireDependency.js +170 -27
  185. package/lib/dependencies/CommonJsSelfReferenceDependency.js +63 -38
  186. package/lib/dependencies/ConstDependency.js +8 -9
  187. package/lib/dependencies/ContextDependency.js +12 -8
  188. package/lib/dependencies/ContextDependencyHelpers.js +14 -9
  189. package/lib/dependencies/ContextDependencyTemplateAsId.js +4 -4
  190. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +24 -11
  191. package/lib/dependencies/ContextElementDependency.js +31 -12
  192. package/lib/dependencies/CreateRequireParserPlugin.js +12 -7
  193. package/lib/dependencies/CreateScriptUrlDependency.js +4 -4
  194. package/lib/dependencies/CssIcssExportDependency.js +56 -28
  195. package/lib/dependencies/CssIcssImportDependency.js +17 -13
  196. package/lib/dependencies/CssIcssSymbolDependency.js +9 -10
  197. package/lib/dependencies/CssImportDependency.js +18 -9
  198. package/lib/dependencies/CssUrlDependency.js +17 -13
  199. package/lib/dependencies/DllEntryDependency.js +1 -1
  200. package/lib/dependencies/DynamicExports.js +2 -2
  201. package/lib/dependencies/ExportBindingInitFragment.js +36 -9
  202. package/lib/dependencies/ExportsInfoDependency.js +7 -8
  203. package/lib/dependencies/ExternalModuleDependency.js +9 -5
  204. package/lib/dependencies/ExternalModuleInitFragment.js +2 -2
  205. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +8 -5
  206. package/lib/dependencies/HarmonyAcceptDependency.js +5 -5
  207. package/lib/dependencies/HarmonyCompatibilityDependency.js +52 -17
  208. package/lib/dependencies/HarmonyDetectionParserPlugin.js +11 -7
  209. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +23 -14
  210. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +80 -12
  211. package/lib/dependencies/HarmonyExportExpressionDependency.js +23 -18
  212. package/lib/dependencies/HarmonyExportHeaderDependency.js +7 -7
  213. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +286 -80
  214. package/lib/dependencies/HarmonyExportInitFragment.js +18 -6
  215. package/lib/dependencies/HarmonyExportSpecifierDependency.js +51 -14
  216. package/lib/dependencies/HarmonyExports.js +7 -4
  217. package/lib/dependencies/HarmonyImportDependency.js +121 -60
  218. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +124 -38
  219. package/lib/dependencies/HarmonyImportGuard.js +20 -30
  220. package/lib/dependencies/HarmonyImportSideEffectDependency.js +152 -9
  221. package/lib/dependencies/HarmonyImportSpecifierDependency.js +97 -49
  222. package/lib/dependencies/HarmonyModulesPlugin.js +7 -3
  223. package/lib/dependencies/HarmonyTopLevelThisParserPlugin.js +1 -3
  224. package/lib/dependencies/HtmlEntryDependency.js +49 -31
  225. package/lib/dependencies/HtmlInlineHtmlDependency.js +7 -8
  226. package/lib/dependencies/HtmlInlineScriptDependency.js +11 -8
  227. package/lib/dependencies/HtmlInlineStyleDependency.js +7 -10
  228. package/lib/dependencies/HtmlSourceDependency.js +22 -14
  229. package/lib/dependencies/ImportContextDependency.js +45 -5
  230. package/lib/dependencies/ImportDependency.js +33 -50
  231. package/lib/dependencies/ImportEagerDependency.js +6 -9
  232. package/lib/dependencies/ImportMetaContextDependency.js +2 -2
  233. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +14 -13
  234. package/lib/dependencies/ImportMetaContextPlugin.js +7 -3
  235. package/lib/dependencies/ImportMetaGlobDependency.js +2 -2
  236. package/lib/dependencies/ImportMetaGlobDependencyParserPlugin.js +2 -3
  237. package/lib/dependencies/ImportMetaGlobHelpers.js +19 -22
  238. package/lib/dependencies/ImportMetaHotAcceptDependency.js +1 -1
  239. package/lib/dependencies/ImportMetaHotDeclineDependency.js +1 -1
  240. package/lib/dependencies/ImportMetaPlugin.js +154 -71
  241. package/lib/dependencies/ImportMetaResolveDependency.js +3 -4
  242. package/lib/dependencies/ImportParserPlugin.js +73 -49
  243. package/lib/dependencies/ImportPhase.js +12 -5
  244. package/lib/dependencies/ImportPlugin.js +7 -3
  245. package/lib/dependencies/ImportWeakDependency.js +6 -9
  246. package/lib/dependencies/JsonExportsDependency.js +11 -7
  247. package/lib/dependencies/LoaderDependency.js +2 -2
  248. package/lib/dependencies/LoaderImportDependency.js +2 -2
  249. package/lib/dependencies/LoaderPlugin.js +11 -7
  250. package/lib/dependencies/LocalModuleDependency.js +5 -5
  251. package/lib/dependencies/LocalModulesHelpers.js +1 -1
  252. package/lib/dependencies/ModuleDecoratorDependency.js +6 -7
  253. package/lib/dependencies/ModuleDependency.js +9 -6
  254. package/lib/dependencies/ModuleDependencyTemplateAsId.js +4 -4
  255. package/lib/dependencies/ModuleDependencyTemplateAsRequireId.js +3 -3
  256. package/lib/dependencies/ModuleHotAcceptDependency.js +1 -1
  257. package/lib/dependencies/ModuleHotDeclineDependency.js +1 -1
  258. package/lib/dependencies/ModuleInitFragmentDependency.js +24 -10
  259. package/lib/dependencies/NullDependency.js +3 -3
  260. package/lib/dependencies/ProvidedDependency.js +14 -10
  261. package/lib/dependencies/PureExpressionDependency.js +9 -10
  262. package/lib/dependencies/RequireContextDependency.js +2 -2
  263. package/lib/dependencies/RequireContextDependencyParserPlugin.js +2 -4
  264. package/lib/dependencies/RequireContextPlugin.js +8 -4
  265. package/lib/dependencies/RequireEnsureDependenciesBlock.js +2 -2
  266. package/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +5 -8
  267. package/lib/dependencies/RequireEnsureDependency.js +8 -7
  268. package/lib/dependencies/RequireEnsurePlugin.js +7 -3
  269. package/lib/dependencies/RequireHeaderDependency.js +50 -12
  270. package/lib/dependencies/RequireIncludeDependency.js +6 -6
  271. package/lib/dependencies/RequireIncludeDependencyParserPlugin.js +2 -3
  272. package/lib/dependencies/RequireIncludePlugin.js +7 -3
  273. package/lib/dependencies/RequireJsStuffPlugin.js +7 -3
  274. package/lib/dependencies/RequireResolveContextDependency.js +2 -2
  275. package/lib/dependencies/RequireResolveDependency.js +4 -4
  276. package/lib/dependencies/RequireResolveHeaderDependency.js +4 -4
  277. package/lib/dependencies/RuntimeRequirementsDependency.js +5 -6
  278. package/lib/dependencies/StaticExportsDependency.js +2 -2
  279. package/lib/dependencies/SystemPlugin.js +10 -6
  280. package/lib/dependencies/SystemRuntimeModule.js +10 -0
  281. package/lib/dependencies/TopLevelAwaitDependency.js +11 -7
  282. package/lib/dependencies/URLContextDependency.js +2 -2
  283. package/lib/dependencies/URLDependency.js +110 -64
  284. package/lib/dependencies/URLPlugin.js +7 -3
  285. package/lib/dependencies/UnsupportedDependency.js +4 -4
  286. package/lib/dependencies/WebAssemblyExportImportedDependency.js +3 -4
  287. package/lib/dependencies/WebAssemblyImportDependency.js +5 -5
  288. package/lib/dependencies/WebpackIsIncludedDependency.js +6 -6
  289. package/lib/dependencies/WorkerAndWorkletPlugin.js +47 -28
  290. package/lib/dependencies/WorkerDependency.js +22 -22
  291. package/lib/dependencies/WorkletDependency.js +18 -21
  292. package/lib/dependencies/getFunctionExpression.js +8 -4
  293. package/lib/dependencies/importOptionsCheck.js +47 -0
  294. package/lib/dependencies/processExportInfo.js +5 -5
  295. package/lib/dll/DelegatedModule.js +34 -22
  296. package/lib/dll/DelegatedModuleFactoryPlugin.js +15 -7
  297. package/lib/dll/DelegatedPlugin.js +2 -2
  298. package/lib/dll/DllEntryPlugin.js +2 -2
  299. package/lib/dll/DllModule.js +22 -15
  300. package/lib/dll/DllModuleFactory.js +7 -3
  301. package/lib/dll/DllPlugin.js +7 -5
  302. package/lib/dll/DllReferencePlugin.js +10 -7
  303. package/lib/dll/LibManifestPlugin.js +5 -5
  304. package/lib/electron/ElectronTargetPlugin.js +53 -49
  305. package/lib/errors/AsyncChunkWaterfallWarning.js +36 -0
  306. package/lib/errors/AsyncDependencyToInitialChunkError.js +2 -2
  307. package/lib/errors/BroadContextsWarning.js +43 -0
  308. package/lib/errors/BuildCycleError.js +1 -1
  309. package/lib/errors/CacheEffectivenessWarning.js +55 -0
  310. package/lib/errors/ChunkRenderError.js +1 -1
  311. package/lib/errors/CircularDependenciesWarning.js +38 -0
  312. package/lib/errors/CodeGenerationError.js +1 -1
  313. package/lib/errors/CommentCompilationWarning.js +1 -1
  314. package/lib/errors/ConflictingResourceHintsWarning.js +35 -0
  315. package/lib/errors/DotenvFileError.js +29 -0
  316. package/lib/errors/DuplicateModulesWarning.js +45 -0
  317. package/lib/errors/DynamicExportsWarning.js +30 -0
  318. package/lib/errors/EmbeddedSourceMapsWarning.js +25 -0
  319. package/lib/errors/EntrypointOverlapWarning.js +45 -0
  320. package/lib/errors/EnvironmentNotSupportAsyncWarning.js +2 -2
  321. package/lib/errors/EvalUsageWarning.js +28 -0
  322. package/lib/errors/HookWebpackError.js +5 -5
  323. package/lib/errors/HotspotsWarning.js +57 -0
  324. package/lib/errors/IgnoreErrorModuleFactory.js +7 -3
  325. package/lib/errors/ImportedBindingAssignmentError.js +30 -0
  326. package/lib/errors/InlinedAssetsWarning.js +36 -0
  327. package/lib/errors/InvalidDependenciesModuleWarning.js +1 -1
  328. package/lib/errors/LargeModulesWarning.js +45 -0
  329. package/lib/errors/LegacyJavascriptWarning.js +48 -0
  330. package/lib/errors/MissingSideEffectsWarning.js +36 -0
  331. package/lib/errors/MixedExportsWarning.js +41 -0
  332. package/lib/errors/ModuleDependencyError.js +13 -16
  333. package/lib/errors/ModuleDependencyWarning.js +5 -15
  334. package/lib/errors/ModuleHashingError.js +1 -1
  335. package/lib/errors/ModuleNotFoundError.js +2 -2
  336. package/lib/errors/ModuleParseError.js +1 -2
  337. package/lib/errors/ModuleRestoreError.js +1 -1
  338. package/lib/errors/ModuleStoreError.js +1 -1
  339. package/lib/errors/NodeStuffInWebError.js +1 -1
  340. package/lib/errors/OsDependentRuleWarning.js +31 -0
  341. package/lib/errors/PureAnnotationsWarning.js +36 -0
  342. package/lib/errors/RedundantDynamicImportWarning.js +31 -0
  343. package/lib/errors/ScopeHoistingBailoutsWarning.js +41 -0
  344. package/lib/errors/SplitChunksCappedWarning.js +41 -0
  345. package/lib/errors/TinyChunksWarning.js +40 -0
  346. package/lib/errors/TopLevelThisWarning.js +34 -0
  347. package/lib/errors/UnsplitVendorsWarning.js +42 -0
  348. package/lib/errors/UnsupportedFeatureWarning.js +1 -1
  349. package/lib/errors/UnusedAliasesWarning.js +29 -0
  350. package/lib/errors/UnusedDefinesWarning.js +29 -0
  351. package/lib/errors/UnusedExternalsWarning.js +29 -0
  352. package/lib/errors/UnusedReexportsWarning.js +42 -0
  353. package/lib/errors/UnusedRuleWarning.js +29 -0
  354. package/lib/errors/WebpackError.js +9 -5
  355. package/lib/errors/deriveStackFromNestedError.js +90 -0
  356. package/lib/esm/ExportWebpackRequireRuntimeModule.js +2 -0
  357. package/lib/esm/ModuleChunkFormatPlugin.js +37 -19
  358. package/lib/esm/ModuleChunkLoadingPlugin.js +86 -51
  359. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +161 -62
  360. package/lib/hmr/HotModuleReplacement.runtime.js +24 -5
  361. package/lib/hmr/HotModuleReplacementRuntimeModule.js +1 -1
  362. package/lib/hmr/LazyCompilationPlugin.js +45 -24
  363. package/lib/hmr/lazyCompilationBackend.js +9 -6
  364. package/lib/hmr/parserHooks.js +56 -0
  365. package/lib/html/HtmlGenerator.js +277 -77
  366. package/lib/html/HtmlModule.js +7 -3
  367. package/lib/html/HtmlModulesPlugin.js +366 -200
  368. package/lib/html/HtmlParser.js +31 -86
  369. package/lib/html/data.js +1928 -0
  370. package/lib/html/htmlMinify.js +288 -0
  371. package/lib/html/syntax.js +6034 -1384
  372. package/lib/ids/ChunkModuleIdRangePlugin.js +3 -3
  373. package/lib/ids/DeterministicChunkIdsPlugin.js +1 -1
  374. package/lib/ids/DeterministicModuleIdsPlugin.js +2 -2
  375. package/lib/ids/HashedModuleIdsPlugin.js +6 -2
  376. package/lib/ids/IdHelpers.js +7 -8
  377. package/lib/ids/NamedChunkIdsPlugin.js +1 -1
  378. package/lib/ids/NamedModuleIdsPlugin.js +1 -1
  379. package/lib/ids/NaturalChunkIdsPlugin.js +2 -2
  380. package/lib/ids/NaturalModuleIdsPlugin.js +1 -1
  381. package/lib/ids/OccurrenceChunkIdsPlugin.js +7 -3
  382. package/lib/ids/OccurrenceModuleIdsPlugin.js +7 -3
  383. package/lib/ids/SyncModuleIdsPlugin.js +4 -4
  384. package/lib/index.js +10 -0
  385. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +3 -3
  386. package/lib/javascript/BasicEvaluatedExpression.js +18 -14
  387. package/lib/javascript/ChunkFormatHelpers.js +6 -6
  388. package/lib/javascript/ChunkHelpers.js +1 -1
  389. package/lib/javascript/CommonJsChunkFormatPlugin.js +11 -5
  390. package/lib/javascript/EnableChunkLoadingPlugin.js +2 -2
  391. package/lib/javascript/JavascriptGenerator.js +65 -165
  392. package/lib/javascript/JavascriptModule.js +9 -3
  393. package/lib/javascript/JavascriptModulesPlugin.js +103 -123
  394. package/lib/javascript/JavascriptParser.js +242 -99
  395. package/lib/javascript/JavascriptParserHelpers.js +10 -7
  396. package/lib/javascript/ScopeAnalyzer.js +1094 -0
  397. package/lib/javascript/StartupHelpers.js +55 -9
  398. package/lib/javascript/syntax.js +2678 -232
  399. package/lib/json/JsonData.js +8 -4
  400. package/lib/json/JsonGenerator.js +38 -16
  401. package/lib/json/JsonModule.js +7 -3
  402. package/lib/json/JsonModulesPlugin.js +1 -1
  403. package/lib/json/JsonParser.js +5 -6
  404. package/lib/library/AbstractLibraryPlugin.js +20 -14
  405. package/lib/library/AmdLibraryPlugin.js +11 -7
  406. package/lib/library/AssignLibraryPlugin.js +19 -13
  407. package/lib/library/EnableLibraryPlugin.js +2 -2
  408. package/lib/library/ExportPropertyLibraryPlugin.js +15 -8
  409. package/lib/library/JsonpLibraryPlugin.js +11 -7
  410. package/lib/library/ModuleLibraryPlugin.js +256 -64
  411. package/lib/library/SystemLibraryPlugin.js +12 -8
  412. package/lib/library/UmdLibraryPlugin.js +62 -25
  413. package/lib/loaders/LoaderRunner.js +47 -6
  414. package/lib/loaders/loadLoader.js +8 -4
  415. package/lib/logging/createConsoleLogger.js +7 -4
  416. package/lib/node/CommonJsChunkLoadingPlugin.js +36 -22
  417. package/lib/node/NodeEnvironmentPlugin.js +17 -3
  418. package/lib/node/NodeSourcePlugin.js +1 -1
  419. package/lib/node/NodeTargetPlugin.js +4 -3
  420. package/lib/node/NodeTemplatePlugin.js +1 -1
  421. package/lib/node/NodeWatchFileSystem.js +70 -9
  422. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +35 -38
  423. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +65 -19
  424. package/lib/node/ReadFileCompileWasmPlugin.js +28 -16
  425. package/lib/node/RequireChunkLoadingRuntimeModule.js +35 -38
  426. package/lib/node/nodeConsole.js +7 -3
  427. package/lib/optimize/AggressiveMergingPlugin.js +2 -2
  428. package/lib/optimize/AggressiveSplittingPlugin.js +9 -6
  429. package/lib/optimize/ConcatenatedModule.js +1030 -476
  430. package/lib/optimize/ConstExportsPlugin.js +16 -7
  431. package/lib/optimize/EnsureChunkConditionsPlugin.js +3 -3
  432. package/lib/optimize/FlagIncludedChunksPlugin.js +3 -4
  433. package/lib/optimize/InlineExports.js +130 -5
  434. package/lib/optimize/InnerGraph.js +28 -12
  435. package/lib/optimize/InnerGraphPlugin.js +23 -18
  436. package/lib/optimize/LimitChunkCountPlugin.js +7 -3
  437. package/lib/optimize/MangleExportsPlugin.js +7 -8
  438. package/lib/optimize/MergeDuplicateChunksPlugin.js +7 -3
  439. package/lib/optimize/MinChunkSizePlugin.js +7 -3
  440. package/lib/optimize/ModuleConcatenationPlugin.js +51 -35
  441. package/lib/optimize/RealContentHashPlugin.js +121 -41
  442. package/lib/optimize/RemoveEmptyChunksPlugin.js +2 -2
  443. package/lib/optimize/RemoveParentModulesPlugin.js +4 -4
  444. package/lib/optimize/RuntimeChunkPlugin.js +2 -2
  445. package/lib/optimize/SideEffectsFlagPlugin.js +262 -39
  446. package/lib/optimize/SplitChunksPlugin.js +86 -24
  447. package/lib/performance/AssetsOverSizeLimitWarning.js +10 -2
  448. package/lib/performance/AsyncChunkWaterfallsPlugin.js +136 -0
  449. package/lib/performance/BroadContextsPlugin.js +142 -0
  450. package/lib/performance/CacheEffectivenessPlugin.js +125 -0
  451. package/lib/performance/ConflictingResourceHintsPlugin.js +99 -0
  452. package/lib/performance/DuplicateModulesPlugin.js +93 -0
  453. package/lib/performance/DuplicatePackagesPlugin.js +119 -0
  454. package/lib/performance/DuplicatePackagesWarning.js +84 -0
  455. package/lib/performance/DynamicExportsPlugin.js +120 -0
  456. package/lib/performance/EmbeddedSourceMapsPlugin.js +71 -0
  457. package/lib/performance/EntrypointOverlapPlugin.js +122 -0
  458. package/lib/performance/EntrypointsOverSizeLimitWarning.js +1 -1
  459. package/lib/performance/EvalUsagePlugin.js +115 -0
  460. package/lib/performance/HotspotsPlugin.js +296 -0
  461. package/lib/performance/InlinedAssetsPlugin.js +99 -0
  462. package/lib/performance/LargeModulesPlugin.js +126 -0
  463. package/lib/performance/LegacyJavascriptPlugin.js +139 -0
  464. package/lib/performance/MissingSideEffectsPlugin.js +138 -0
  465. package/lib/performance/MixedExportsPlugin.js +136 -0
  466. package/lib/performance/OsDependentRuleWarningPlugin.js +178 -0
  467. package/lib/performance/PureAnnotationsPlugin.js +219 -0
  468. package/lib/performance/RedundantDynamicImportsPlugin.js +225 -0
  469. package/lib/performance/RuntimeInLargeChunkWarning.js +27 -0
  470. package/lib/performance/ScopeHoistingBailoutsPlugin.js +164 -0
  471. package/lib/performance/SizeLimitsPlugin.js +139 -7
  472. package/lib/performance/SplitChunksCappedPlugin.js +99 -0
  473. package/lib/performance/TinyChunksPlugin.js +128 -0
  474. package/lib/performance/TopLevelThisPlugin.js +208 -0
  475. package/lib/performance/UnsplitVendorsPlugin.js +112 -0
  476. package/lib/performance/UnusedAliasesPlugin.js +253 -0
  477. package/lib/performance/UnusedDefinesPlugin.js +87 -0
  478. package/lib/performance/UnusedExternalsPlugin.js +110 -0
  479. package/lib/performance/UnusedReexportsPlugin.js +159 -0
  480. package/lib/performance/UnusedRuleWarningPlugin.js +105 -0
  481. package/lib/performance/getModuleSize.js +22 -0
  482. package/lib/performance/getSourceModules.js +22 -0
  483. package/lib/performance/hasOnlyUnusedExports.js +40 -0
  484. package/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +24 -10
  485. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +63 -46
  486. package/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +2 -3
  487. package/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +2 -2
  488. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +2 -2
  489. package/lib/prefetch/ResourceHintPlugin.js +295 -79
  490. package/lib/prefetch/ResourceHintRuntimeModule.js +1 -21
  491. package/lib/prefetch/StartupAssetHintRuntimeModule.js +10 -133
  492. package/lib/prefetch/parseResourceHintOptions.js +31 -4
  493. package/lib/rules/BasicEffectRulePlugin.js +2 -2
  494. package/lib/rules/BasicMatcherRulePlugin.js +8 -4
  495. package/lib/rules/GlobMatcherRulePlugin.js +68 -0
  496. package/lib/rules/ObjectMatcherRulePlugin.js +12 -5
  497. package/lib/rules/RuleSetCompiler.js +146 -12
  498. package/lib/rules/UseEffectRulePlugin.js +18 -11
  499. package/lib/runtime/AsyncModuleGeneratorRuntimeModule.js +11 -1
  500. package/lib/runtime/AsyncModuleRuntimeModule.js +6 -2
  501. package/lib/runtime/AutoPublicPathRuntimeModule.js +15 -20
  502. package/lib/runtime/BaseUriRuntimeModule.js +33 -7
  503. package/lib/runtime/ChunkNameRuntimeModule.js +10 -0
  504. package/lib/runtime/CompatGetDefaultExportRuntimeModule.js +11 -1
  505. package/lib/runtime/CompatRuntimeModule.js +5 -3
  506. package/lib/runtime/ConcatenationWrapRuntimeModule.js +90 -0
  507. package/lib/runtime/ConstructRequireRuntimeModule.js +52 -0
  508. package/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +8 -6
  509. package/lib/runtime/CreateScriptRuntimeModule.js +11 -1
  510. package/lib/runtime/CreateScriptUrlRuntimeModule.js +11 -1
  511. package/lib/runtime/DefinePropertyGettersRuntimeModule.js +56 -38
  512. package/lib/runtime/EnsureChunkRuntimeModule.js +18 -2
  513. package/lib/runtime/GetChunkFilenameRuntimeModule.js +62 -37
  514. package/lib/runtime/GetFullHashRuntimeModule.js +12 -2
  515. package/lib/runtime/GetMainFilenameRuntimeModule.js +12 -2
  516. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +2 -2
  517. package/lib/runtime/GetWorkletBootstrapRuntimeModule.js +16 -3
  518. package/lib/runtime/GlobalRuntimeModule.js +18 -0
  519. package/lib/runtime/HasOwnPropertyRuntimeModule.js +12 -2
  520. package/lib/runtime/LoadScriptRuntimeModule.js +2 -2
  521. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +34 -7
  522. package/lib/runtime/MakeNamespaceObjectRuntimeModule.js +22 -6
  523. package/lib/runtime/NonceRuntimeModule.js +10 -0
  524. package/lib/runtime/OnChunksLoadedRuntimeModule.js +5 -3
  525. package/lib/runtime/PublicPathRuntimeModule.js +12 -2
  526. package/lib/runtime/RelativeUrlRuntimeModule.js +11 -1
  527. package/lib/runtime/RuntimeIdRuntimeModule.js +12 -2
  528. package/lib/runtime/SetAnonymousDefaultNameRuntimeModule.js +11 -1
  529. package/lib/runtime/StartupChunkDependenciesPlugin.js +18 -9
  530. package/lib/runtime/StartupChunkDependenciesRuntimeModule.js +3 -3
  531. package/lib/runtime/StartupEntrypointRuntimeModule.js +21 -4
  532. package/lib/runtime/SystemContextRuntimeModule.js +10 -0
  533. package/lib/runtime/ToBinaryRuntimeModule.js +1 -1
  534. package/lib/runtime/WorkerRuntimeModule.js +11 -1
  535. package/lib/runtime/baseUri.js +63 -0
  536. package/lib/schemes/DataUriPlugin.js +1 -1
  537. package/lib/schemes/FileUriPlugin.js +1 -1
  538. package/lib/schemes/HttpUriPlugin.js +46 -20
  539. package/lib/schemes/VirtualUrlPlugin.js +13 -7
  540. package/lib/serialization/AggregateErrorSerializer.js +1 -1
  541. package/lib/serialization/BinaryMiddleware.js +4 -4
  542. package/lib/serialization/ErrorObjectSerializer.js +1 -1
  543. package/lib/serialization/FileMiddleware.js +22 -9
  544. package/lib/serialization/ObjectMiddleware.js +139 -114
  545. package/lib/serialization/PlainObjectSerializer.js +19 -16
  546. package/lib/sharing/ConsumeSharedModule.js +30 -21
  547. package/lib/sharing/ConsumeSharedPlugin.js +18 -10
  548. package/lib/sharing/ConsumeSharedRuntimeModule.js +6 -9
  549. package/lib/sharing/ProvideSharedModule.js +25 -16
  550. package/lib/sharing/ProvideSharedModuleFactory.js +7 -3
  551. package/lib/sharing/ProvideSharedPlugin.js +8 -4
  552. package/lib/sharing/SharePlugin.js +17 -5
  553. package/lib/sharing/ShareRuntimeModule.js +4 -4
  554. package/lib/sharing/resolveMatchedConfigs.js +9 -6
  555. package/lib/sharing/utils.js +1 -3
  556. package/lib/stats/DefaultStatsFactoryPlugin.js +50 -29
  557. package/lib/stats/DefaultStatsPresetPlugin.js +17 -8
  558. package/lib/stats/DefaultStatsPrinterPlugin.js +36 -26
  559. package/lib/stats/StatsFactory.js +25 -26
  560. package/lib/stats/StatsPrinter.js +16 -12
  561. package/lib/typescript/TypeScriptPlugin.js +20 -24
  562. package/lib/url/URLParserPlugin.js +26 -13
  563. package/lib/util/ArrayQueue.js +3 -3
  564. package/lib/util/AsyncQueue.js +4 -3
  565. package/lib/util/Hash.js +5 -1
  566. package/lib/util/LazySet.js +35 -22
  567. package/lib/util/LocConverter.js +36 -13
  568. package/lib/util/SourceProcessor.js +1066 -24
  569. package/lib/util/StringXor.js +1 -1
  570. package/lib/util/URLAbsoluteSpecifier.js +3 -1
  571. package/lib/util/chainedImports.js +9 -5
  572. package/lib/util/cleverMerge.js +1 -1
  573. package/lib/util/comparators.js +45 -14
  574. package/lib/util/concatenate.js +203 -77
  575. package/lib/util/conventions.js +10 -2
  576. package/lib/util/createHash.js +2 -2
  577. package/lib/util/createHooksRegistry.js +8 -10
  578. package/lib/util/createMappings.js +25 -3
  579. package/lib/util/dataURL.js +225 -1
  580. package/lib/util/extractSourceMap.js +4 -3
  581. package/lib/util/findCaseMismatch.js +139 -0
  582. package/lib/util/formatLocation.js +1 -2
  583. package/lib/util/fs.js +22 -5
  584. package/lib/util/globUtils.js +298 -24
  585. package/lib/util/hash/BatchedHash.js +5 -1
  586. package/lib/util/hash/BulkUpdateHash.js +5 -1
  587. package/lib/util/hash/DebugHash.js +5 -1
  588. package/lib/util/hash/hash-digest.js +6 -2
  589. package/lib/util/identifier.js +4 -0
  590. package/lib/util/implicitTypeLoaderFallback.js +1 -1
  591. package/lib/util/internalSerializables.js +8 -0
  592. package/lib/util/lazyModule.js +56 -0
  593. package/lib/util/makeSerializable.js +7 -3
  594. package/lib/util/matchAlias.js +25 -0
  595. package/lib/util/mimeTypes.js +11 -5
  596. package/lib/util/nonNumericOnlyHash.js +4 -3
  597. package/lib/util/parseJson.js +5 -3
  598. package/lib/util/preloadModuleType.js +32 -0
  599. package/lib/util/registerExternalSerializer.js +7 -5
  600. package/lib/util/removeBOM.js +82 -1
  601. package/lib/util/runtime.js +2 -2
  602. package/lib/util/semver.js +1 -1
  603. package/lib/util/serialization.js +28 -28
  604. package/lib/util/source.js +2 -2
  605. package/lib/util/traverseDestructuringAssignmentProperties.js +6 -2
  606. package/lib/wasm/EnableWasmLoadingPlugin.js +10 -8
  607. package/lib/wasm/wasmModuleFilename.js +54 -0
  608. package/lib/wasm-async/AsyncWasmCompileRuntimeModule.js +43 -21
  609. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +45 -21
  610. package/lib/wasm-async/AsyncWasmModule.js +3 -3
  611. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +4 -5
  612. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +57 -17
  613. package/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js +34 -18
  614. package/lib/wasm-async/AsyncWebAssemblyParser.js +9 -8
  615. package/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js +29 -8
  616. package/lib/wasm-sync/SyncWasmModule.js +2 -2
  617. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +18 -13
  618. package/lib/wasm-sync/WasmFinalizeExportsPlugin.js +4 -5
  619. package/lib/wasm-sync/WebAssemblyGenerator.js +18 -17
  620. package/lib/wasm-sync/WebAssemblyInInitialChunkError.js +4 -4
  621. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +7 -7
  622. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +24 -11
  623. package/lib/wasm-sync/WebAssemblyParser.js +4 -6
  624. package/lib/wasm-sync/WebAssemblyUtils.js +2 -2
  625. package/lib/web/FetchCompileAsyncWasmPlugin.js +105 -19
  626. package/lib/web/FetchCompileWasmPlugin.js +48 -16
  627. package/lib/web/JsonpChunkLoadingPlugin.js +47 -23
  628. package/lib/web/JsonpChunkLoadingRuntimeModule.js +50 -20
  629. package/lib/web/JsonpTemplatePlugin.js +2 -2
  630. package/lib/webpack.js +22 -11
  631. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +60 -26
  632. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +30 -32
  633. package/lib/webworker/WebWorkerTemplatePlugin.js +1 -1
  634. package/module.d.ts +1 -0
  635. package/package.json +32 -25
  636. package/schemas/WebpackOptions.check.js +1 -1
  637. package/schemas/WebpackOptions.json +667 -34
  638. package/schemas/plugins/HtmlParserOptions.check.js +1 -1
  639. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  640. package/schemas/plugins/container/ContainerPlugin.json +10 -0
  641. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  642. package/schemas/plugins/container/ModuleFederationPlugin.json +10 -0
  643. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.js +1 -1
  644. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  645. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  646. package/types.d.ts +3223 -465
  647. package/lib/runtime/CommonJsWrapRuntimeModule.js +0 -37
@@ -5,8 +5,6 @@
5
5
 
6
6
  "use strict";
7
7
 
8
- const eslintScope = require("eslint-scope");
9
- const Referencer = require("eslint-scope/lib/referencer");
10
8
  const { SyncBailHook } = require("tapable");
11
9
  const {
12
10
  CachedSource,
@@ -16,18 +14,23 @@ const {
16
14
  const ConcatenationScope = require("../ConcatenationScope");
17
15
  const Dependency = require("../Dependency");
18
16
  const { UsageState } = require("../ExportsInfo");
17
+ const ExternalModule = require("../ExternalModule");
19
18
  const Module = require("../Module");
20
19
  const {
21
20
  JAVASCRIPT_TYPE,
22
21
  JAVASCRIPT_TYPES
23
22
  } = require("../ModuleSourceTypeConstants");
24
23
  const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants");
24
+ const NormalModule = require("../NormalModule");
25
25
  const RuntimeGlobals = require("../RuntimeGlobals");
26
26
  const Template = require("../Template");
27
27
  const { DEFAULTS } = require("../config/defaults");
28
+ const CommonJsExportRequireDependency = require("../dependencies/CommonJsExportRequireDependency");
29
+ const CommonJsFullRequireDependency = require("../dependencies/CommonJsFullRequireDependency");
30
+ const CommonJsRequireDependency = require("../dependencies/CommonJsRequireDependency");
28
31
  const { ImportPhaseUtils } = require("../dependencies/ImportPhase");
29
- const { isCommonJsWrapped } = require("../javascript/JavascriptGenerator");
30
32
  const JavascriptParser = require("../javascript/JavascriptParser");
33
+ const analyzeScope = require("../javascript/ScopeAnalyzer");
31
34
  const {
32
35
  getDeferredCycleModuleIds,
33
36
  getDeferredCycleModules,
@@ -36,14 +39,18 @@ const {
36
39
  } = require("../runtime/MakeDeferredNamespaceObjectRuntime");
37
40
  const { equals } = require("../util/ArrayHelpers");
38
41
  const LazySet = require("../util/LazySet");
39
- const { concatComparators } = require("../util/comparators");
42
+ const {
43
+ compareModulesByFullName,
44
+ concatComparators
45
+ } = require("../util/comparators");
40
46
  const {
41
47
  RESERVED_NAMES,
42
48
  addScopeSymbols,
43
49
  findNewName,
44
50
  getAllReferences,
45
51
  getPathInAst,
46
- getUsedNamesInScopeInfo
52
+ getUsedNamesInScopeInfo,
53
+ isCommonJsConcatenationEnabled
47
54
  } = require("../util/concatenate");
48
55
  const createHash = require("../util/createHash");
49
56
  const createHooksRegistry = require("../util/createHooksRegistry");
@@ -60,54 +67,71 @@ const {
60
67
  } = require("../util/runtime");
61
68
  const { InlinedUsedName } = require("./InlineExports");
62
69
 
63
- /** @typedef {import("webpack-sources").Source} Source */
64
- /** @typedef {import("../config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
65
- /** @typedef {import("../ChunkGraph")} ChunkGraph */
66
- /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
67
- /** @typedef {import("../Compilation")} Compilation */
68
- /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
69
- /** @typedef {import("../dependencies/ModuleDependency")} ModuleDependency */
70
- /** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */
71
- /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
72
- /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
73
- /** @typedef {import("../Module").BuildCallback} BuildCallback */
74
- /** @typedef {import("../Module").BuildInfo} BuildInfo */
75
- /** @typedef {import("../Module").FileSystemDependencies} FileSystemDependencies */
76
- /** @typedef {import("../Module").BuildMeta} BuildMeta */
77
- /** @typedef {import("../Module").ExportsType} ExportsType */
78
- /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
79
- /** @typedef {import("../Module").CodeGenerationResultData} CodeGenerationResultData */
80
- /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
81
- /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
82
- /** @typedef {import("../Module").LibIdent} LibIdent */
83
- /** @typedef {import("../Module").NameForCondition} NameForCondition */
84
- /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
85
- /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
86
- /** @typedef {import("../Module").SourceTypes} SourceTypes */
87
- /** @typedef {import("../ModuleGraph")} ModuleGraph */
88
- /** @typedef {import("../NormalModule")} NormalModule */
89
- /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
90
- /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */
91
- /** @typedef {import("../RequestShortener")} RequestShortener */
92
- /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
93
- /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
94
- /** @typedef {import("../javascript/JavascriptModule").JavascriptModuleBuildInfo} JavascriptModuleBuildInfo */
95
- /** @typedef {import("../javascript/JavascriptModule").JavascriptModuleBuildMeta} JavascriptModuleBuildMeta */
96
- /** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
97
- /** @typedef {import("../javascript/JavascriptModulesPlugin").Scope} Scope */
98
- /** @typedef {import("../javascript/JavascriptModulesPlugin").Reference} Reference */
99
- /** @typedef {import("../javascript/JavascriptModulesPlugin").Variable} Variable */
100
- /** @typedef {import("../javascript/JavascriptParser").Program} Program */
101
- /** @typedef {import("../javascript/JavascriptParser").Range} Range */
102
- /** @typedef {import("estree").Identifier} Identifier */
103
- /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
104
- /** @typedef {import("../util/Hash")} Hash */
105
- /** @typedef {import("../util/Hash").HashFunction} HashFunction */
106
- /** @typedef {import("../util/concatenate").UsedNames} UsedNames */
107
- /** @typedef {import("../util/concatenate").UsedNamesInScopeInfo} UsedNamesInScopeInfo */
108
- /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
109
- /** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
110
- /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
70
+ /** @import { Source } from "webpack-sources" */
71
+ /**
72
+ * @import {
73
+ * WebpackOptionsNormalizedWithDefaults as WebpackOptions
74
+ * } from "../config/defaults"
75
+ */
76
+ /** @import ChunkGraph from "../ChunkGraph" */
77
+ /** @import CodeGenerationResults from "../CodeGenerationResults" */
78
+ /** @import Compilation, { FileSystemDependencies } from "../Compilation" */
79
+ /** @import { UpdateHashContext } from "../Dependency" */
80
+ /** @import HarmonyImportDependency from "../dependencies/HarmonyImportDependency" */
81
+ /** @import DependencyTemplates from "../DependencyTemplates" */
82
+ /** @import { ExportInfo } from "../ExportsInfo" */
83
+ /**
84
+ * @import {
85
+ * BuildCallback,
86
+ * BuildInfo,
87
+ * BuildMeta,
88
+ * ExportsType,
89
+ * CodeGenerationContext,
90
+ * CodeGenerationResultData,
91
+ * CodeGenerationResult,
92
+ * LibIdentOptions,
93
+ * LibIdent,
94
+ * NameForCondition,
95
+ * ReadOnlyRuntimeRequirements,
96
+ * RuntimeRequirements,
97
+ * SourceTypes
98
+ * } from "../Module"
99
+ */
100
+ /** @import ModuleGraph from "../ModuleGraph" */
101
+ /**
102
+ * @import ModuleGraphConnection, {
103
+ * ConnectionState
104
+ * } from "../ModuleGraphConnection"
105
+ */
106
+ /** @import RequestShortener from "../RequestShortener" */
107
+ /** @import { ResolverWithOptions } from "../ResolverFactory" */
108
+ /** @import RuntimeTemplate from "../RuntimeTemplate" */
109
+ /**
110
+ * @import {
111
+ * JavascriptModuleBuildInfo,
112
+ * JavascriptModuleBuildMeta
113
+ * } from "../javascript/JavascriptModule"
114
+ */
115
+ /**
116
+ * @import {
117
+ * ChunkRenderContext,
118
+ * Scope,
119
+ * Reference,
120
+ * Variable
121
+ * } from "../javascript/JavascriptModulesPlugin"
122
+ */
123
+ /** @import { Range } from "../javascript/JavascriptParser" */
124
+ /** @import { Identifier, Program } from "estree" */
125
+ /**
126
+ * @import {
127
+ * ObjectDeserializerContext
128
+ * } from "../serialization/ObjectMiddleware"
129
+ */
130
+ /** @import Hash, { HashFunction } from "../util/Hash" */
131
+ /** @import { UsedNames, UsedNamesInScopeInfo } from "../util/concatenate" */
132
+ /** @import { InputFileSystem } from "../util/fs" */
133
+ /** @import { AssociatedObjectForCache } from "../util/identifier" */
134
+ /** @import { RuntimeSpec } from "../util/runtime" */
111
135
  /**
112
136
  * @template T
113
137
  * @typedef {import("../InitFragment")<T>} InitFragment
@@ -118,13 +142,33 @@ const { InlinedUsedName } = require("./InlineExports");
118
142
  * @typedef {import("../util/comparators").Comparator<T>} Comparator
119
143
  */
120
144
 
121
- // fix eslint-scope to support class properties correctly
122
- // cspell:word Referencer
123
- const ReferencerClass = Referencer;
124
- if (!ReferencerClass.prototype.PropertyDefinition) {
125
- ReferencerClass.prototype.PropertyDefinition =
126
- ReferencerClass.prototype.Property;
127
- }
145
+ const IDENTIFIER_SCAN_REGEXP = /[$A-Za-z_][\w$]*/g;
146
+ const IDENTIFIER_SCAN_WHITESPACE = new Set([" ", "\t", "\n", "\r"]);
147
+
148
+ /**
149
+ * Finds every identifier a generated source could resolve against the enclosing
150
+ * concatenation scope. Property names are skipped; string and comment contents
151
+ * are not, which only over-reserves.
152
+ * @param {Source} source generated source
153
+ * @returns {ReadonlySet<string>} identifier names
154
+ */
155
+ const findIdentifiers = (source) => {
156
+ const code = source.source().toString();
157
+ /** @type {Set<string>} */
158
+ const result = new Set();
159
+ IDENTIFIER_SCAN_REGEXP.lastIndex = 0;
160
+ let match = IDENTIFIER_SCAN_REGEXP.exec(code);
161
+ while (match !== null) {
162
+ let i = match.index - 1;
163
+ while (i >= 0 && IDENTIFIER_SCAN_WHITESPACE.has(code[i])) i--;
164
+ // `a.b` can't bind to the outer scope, but the `b` of `...b` can
165
+ if (!(i >= 0 && code[i] === "." && code[i - 1] !== ".")) {
166
+ result.add(match[0]);
167
+ }
168
+ match = IDENTIFIER_SCAN_REGEXP.exec(code);
169
+ }
170
+ return result;
171
+ };
128
172
 
129
173
  /** @typedef {RawBinding | SymbolBinding} Binding */
130
174
 
@@ -137,6 +181,7 @@ if (!ReferencerClass.prototype.PropertyDefinition) {
137
181
  * @property {string=} comment
138
182
  * @property {ExportName} ids
139
183
  * @property {ExportName} exportName
184
+ * @property {boolean=} accessorCall the raw name is the wrapper accessor call itself, so it binds looser than the identifier it replaces
140
185
  */
141
186
 
142
187
  /**
@@ -156,20 +201,23 @@ if (!ReferencerClass.prototype.PropertyDefinition) {
156
201
  /**
157
202
  * @typedef {object} ConcatenatedModuleInfo
158
203
  * @property {"concatenated"} type
204
+ * @property {boolean} wrapped the body renders inside the lazy CJS wrapper with real module/exports instead of being scope-hoisted into the shared scope
205
+ * @property {boolean} eager a wrapped body reached by an eager import edge, so its accessor is called at its own slot in evaluation order
159
206
  * @property {Module} module
160
207
  * @property {number} index
161
- * @property {boolean=} cjsWrapped a "weird" CommonJS module executed via the CJS wrapper runtime helper with real module/exports objects
162
208
  * @property {Program | undefined} ast
163
209
  * @property {Source | undefined} internalSource
164
210
  * @property {ReplaceSource | undefined} source
165
211
  * @property {InitFragment<ChunkRenderContext>[]=} chunkInitFragments
166
212
  * @property {ReadOnlyRuntimeRequirements | undefined} runtimeRequirements
167
213
  * @property {Scope | undefined} globalScope
214
+ * @property {Reference[] | undefined} unresolvedReferences the module's free references
168
215
  * @property {Scope | undefined} moduleScope
169
216
  * @property {Map<string, string>} internalNames
170
217
  * @property {ExportMap | undefined} exportMap
171
218
  * @property {ExportMap | undefined} rawExportMap
172
219
  * @property {string=} namespaceExportSymbol
220
+ * @property {string | undefined} namespaceFnName name of the lazy wrapper accessor function (calling it evaluates the module and returns its exports)
173
221
  * @property {string | undefined} namespaceObjectName
174
222
  * @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
175
223
  * @property {ConcatenationScope | undefined} concatenationScope
@@ -186,11 +234,14 @@ if (!ReferencerClass.prototype.PropertyDefinition) {
186
234
  /**
187
235
  * @typedef {object} ExternalModuleInfo
188
236
  * @property {"external"} type
237
+ * @property {boolean} wrapped the module's `require()` call is deferred behind an accessor instead of running at its own slot; unlike a wrapped concatenated member there is no body and no CJS wrapper, so any external may be wrapped
238
+ * @property {boolean} eager a wrapped module reached by an eager import edge, so its accessor is called at its own slot in evaluation order
189
239
  * @property {Module} module
190
240
  * @property {RuntimeSpec | boolean} runtimeCondition
191
241
  * @property {NonDeferAccess} nonDeferAccess
192
242
  * @property {number} index
193
243
  * @property {string | undefined} name module.exports / harmony namespace object
244
+ * @property {string | undefined} namespaceFnName lazy module accessor
194
245
  * @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
195
246
  * @property {string | undefined} deferredName deferred module.exports / harmony namespace object
196
247
  * @property {boolean} deferred the module is deferred at least once
@@ -290,11 +341,36 @@ const subtractNonDeferAccess = (a, b) => a && !b;
290
341
  /**
291
342
  * @typedef {object} ConcatenationEntry
292
343
  * @property {"concatenated" | "external"} type
344
+ * @property {boolean} wrapped evaluation is deferred behind an accessor: a "concatenated" entry renders its body inside the lazy CJS wrapper instead of being scope-hoisted, an "external" entry only defers its `require()` call
293
345
  * @property {Module} module
294
346
  * @property {RuntimeSpec | boolean} runtimeCondition
295
347
  * @property {NonDeferAccess} nonDeferAccess
296
348
  */
297
349
 
350
+ /**
351
+ * Whether a member runs inside the lazy CJS wrapper or is scope-hoisted. Only a
352
+ * NormalModule can carry a CJS body; an ESM member starts out hoisted and is
353
+ * downgraded by {@link ConcatenatedModule._createConcatenationList}.
354
+ * @param {Module} module a module taking part in the concatenation
355
+ * @returns {boolean} true, when the module renders wrapped
356
+ */
357
+ const needWrapped = (module) =>
358
+ module instanceof NormalModule &&
359
+ module.type.startsWith("javascript/") &&
360
+ module.buildMeta !== undefined &&
361
+ module.buildMeta.exportsType !== "namespace";
362
+
363
+ /**
364
+ * Whether a hoisted member can move into the lazy wrapper instead.
365
+ * @param {ConcatenationEntry} entry a member of the concatenation
366
+ * @returns {boolean} true, when it may be wrapped
367
+ */
368
+ const entryCanBeWrapped = (entry) =>
369
+ (entry.module instanceof NormalModule &&
370
+ !entry.module.type.startsWith("css/")) ||
371
+ (entry.module instanceof ExternalModule &&
372
+ entry.module.canBeWrappedInConcatenation());
373
+
298
374
  /** @typedef {Set<ConcatenatedModuleInfo>} NeededNamespaceObjects */
299
375
 
300
376
  /** @typedef {Map<Module, ModuleInfo>} ModuleToInfoMap */
@@ -320,6 +396,40 @@ const getExportsType = (moduleGraph, info, strict) => {
320
396
  return info.exportsTypeNonStrict;
321
397
  };
322
398
 
399
+ /**
400
+ * @param {ExternalModuleInfo} info module info
401
+ * @returns {string} module exports expression
402
+ */
403
+ const getExternalModuleExpr = (info) =>
404
+ info.wrapped
405
+ ? `${
406
+ /** @type {NonNullable<ExternalModuleInfo["namespaceFnName"]>} */
407
+ (info.namespaceFnName)
408
+ }()`
409
+ : /** @type {NonNullable<ExternalModuleInfo["name"]>} */ (info.name);
410
+
411
+ /**
412
+ * A wrapped module's interop object is declared as a lazy accessor, so reading
413
+ * it is a call. See `declareInterop`.
414
+ * @param {ModuleInfo} info module info
415
+ * @param {string | undefined} interopName interop variable name
416
+ * @returns {string} interop object expression
417
+ */
418
+ const getInteropExpr = (info, interopName) =>
419
+ info.wrapped ? `${interopName}()` : /** @type {string} */ (interopName);
420
+
421
+ /**
422
+ * Expression for an export that is not used. A hoisted body runs at its own
423
+ * slot, but a wrapped one only runs when its accessor is called, so dropping
424
+ * the reference would drop the module's side effects with it.
425
+ * @param {ConcatenatedModuleInfo} info module info
426
+ * @returns {string} expression evaluating to undefined
427
+ */
428
+ const getUnusedExportExpr = (info) =>
429
+ info.wrapped
430
+ ? `/* unused export */ (${info.namespaceObjectName}, undefined)`
431
+ : "/* unused export */ undefined";
432
+
323
433
  /**
324
434
  * @param {ModuleGraph} moduleGraph the module graph
325
435
  * @param {ModuleInfo} info module info
@@ -333,7 +443,8 @@ const getExportsType = (moduleGraph, info, strict) => {
333
443
  * @param {boolean} depDeferred the dependency is deferred
334
444
  * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
335
445
  * @param {boolean | undefined} asiSafe asiSafe
336
- * @param {Set<ExportInfo>=} alreadyVisited alreadyVisited
446
+ * @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
447
+ * @param {Set<InstanceType<ExportInfo>>=} alreadyVisited alreadyVisited
337
448
  * @returns {Binding} the final variable
338
449
  */
339
450
  const getFinalBinding = (
@@ -349,6 +460,7 @@ const getFinalBinding = (
349
460
  depDeferred,
350
461
  strictHarmonyModule,
351
462
  asiSafe,
463
+ moduleExportsAccess,
352
464
  alreadyVisited
353
465
  ) => {
354
466
  const exportsType = getExportsType(moduleGraph, info, strictHarmonyModule);
@@ -357,37 +469,64 @@ const getFinalBinding = (
357
469
  info.deferred &&
358
470
  !(/** @type {BuildMeta} */ (info.module.buildMeta).async);
359
471
  const deferred = depDeferred && moduleDeferred;
360
- if (exportName.length === 0) {
472
+
473
+ if (moduleExportsAccess && info.type === "concatenated") {
474
+ neededNamespaceObjects.add(info);
475
+ // ids arrive as declared names and the rendered exports object is keyed by
476
+ // used ones, so resolve here — the same way `case "external"` does below.
477
+ // Resolving in the caller instead would mangle twice.
478
+ const usedName =
479
+ exportName.length === 0
480
+ ? exportName
481
+ : moduleGraph
482
+ .getExportsInfo(info.module)
483
+ .getUsedName(exportName, runtime);
484
+ if (!usedName) {
485
+ return {
486
+ info,
487
+ rawName: getUnusedExportExpr(info),
488
+ ids: [],
489
+ exportName
490
+ };
491
+ }
492
+ return {
493
+ info,
494
+ rawName:
495
+ /** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
496
+ (info.namespaceObjectName),
497
+ ids: /** @type {ExportName} */ (usedName),
498
+ exportName,
499
+ accessorCall: info.wrapped
500
+ };
501
+ }
502
+
503
+ if (moduleExportsAccess) {
504
+ // Skip ESM interop when require() targets a module outside the concatenation
505
+ } else if (exportName.length === 0) {
361
506
  switch (exportsType) {
362
507
  case "default-only":
363
- // a concatenated CommonJS module has no runtime exports object;
364
- // its fake namespace is built over the generated namespace object
365
- if (info.type === "concatenated") neededNamespaceObjects.add(info);
366
508
  if (deferred) info.deferredNamespaceObjectUsed = true;
367
509
  else info.interopNamespaceObject2Used = true;
368
510
  return {
369
511
  info,
370
- rawName: /** @type {string} */ (
371
- deferred
372
- ? info.deferredNamespaceObjectName
373
- : info.interopNamespaceObject2Name
374
- ),
512
+ rawName: deferred
513
+ ? /** @type {string} */ (info.deferredNamespaceObjectName)
514
+ : getInteropExpr(info, info.interopNamespaceObject2Name),
375
515
  ids: exportName,
376
- exportName
516
+ exportName,
517
+ accessorCall: !deferred && info.wrapped
377
518
  };
378
519
  case "default-with-named":
379
- if (info.type === "concatenated") neededNamespaceObjects.add(info);
380
520
  if (deferred) info.deferredNamespaceObjectUsed = true;
381
521
  else info.interopNamespaceObjectUsed = true;
382
522
  return {
383
523
  info,
384
- rawName: /** @type {string} */ (
385
- deferred
386
- ? info.deferredNamespaceObjectName
387
- : info.interopNamespaceObjectName
388
- ),
524
+ rawName: deferred
525
+ ? /** @type {string} */ (info.deferredNamespaceObjectName)
526
+ : getInteropExpr(info, info.interopNamespaceObjectName),
389
527
  ids: exportName,
390
- exportName
528
+ exportName,
529
+ accessorCall: !deferred && info.wrapped
391
530
  };
392
531
  case "namespace":
393
532
  case "dynamic":
@@ -476,19 +615,24 @@ const getFinalBinding = (
476
615
  if (moduleDeferred) {
477
616
  return {
478
617
  info,
479
- rawName: /** @type {string} */ (info.name),
618
+ rawName: getExternalModuleExpr(info),
480
619
  ids: exportName,
481
- exportName
620
+ exportName,
621
+ accessorCall: info.wrapped
482
622
  };
483
623
  }
484
624
  info.interopDefaultAccessUsed = true;
625
+ const accessor = getInteropExpr(
626
+ info,
627
+ info.interopDefaultAccessName
628
+ );
485
629
  const defaultExport = asCall
486
- ? `${info.interopDefaultAccessName}()`
630
+ ? `${accessor}()`
487
631
  : asiSafe
488
- ? `(${info.interopDefaultAccessName}())`
632
+ ? `(${accessor}())`
489
633
  : asiSafe === false
490
- ? `;(${info.interopDefaultAccessName}())`
491
- : `${info.interopDefaultAccessName}.a`;
634
+ ? `;(${accessor}())`
635
+ : `${accessor}.a`;
492
636
  return {
493
637
  info,
494
638
  rawName: defaultExport,
@@ -509,6 +653,7 @@ const getFinalBinding = (
509
653
  throw new Error(`Unexpected exportsType ${exportsType}`);
510
654
  }
511
655
  }
656
+
512
657
  if (exportName.length === 0) {
513
658
  switch (info.type) {
514
659
  case "concatenated":
@@ -519,7 +664,8 @@ const getFinalBinding = (
519
664
  /** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
520
665
  (info.namespaceObjectName),
521
666
  ids: exportName,
522
- exportName
667
+ exportName,
668
+ accessorCall: info.wrapped
523
669
  };
524
670
  case "external":
525
671
  if (deferred) {
@@ -533,11 +679,10 @@ const getFinalBinding = (
533
679
  }
534
680
  return {
535
681
  info,
536
- rawName:
537
- /** @type {NonNullable<ExternalModuleInfo["name"]>} */
538
- (info.name),
682
+ rawName: getExternalModuleExpr(info),
539
683
  ids: exportName,
540
- exportName
684
+ exportName,
685
+ accessorCall: info.wrapped
541
686
  };
542
687
  }
543
688
  }
@@ -664,19 +809,41 @@ const getFinalBinding = (
664
809
  /** @type {BuildMeta} */
665
810
  (info.module.buildMeta).strictHarmonyModule,
666
811
  asiSafe,
812
+ false,
667
813
  alreadyVisited
668
814
  );
669
815
  }
670
816
  // A wrapped module resolves every export through its live exports
671
817
  // alias (namespaceObjectName), same as namespaceExportSymbol modules.
672
- if (info.namespaceExportSymbol || info.cjsWrapped) {
673
- const usedName = /** @type {ExportName} */ (
674
- exportsInfo.getUsedName(exportName, runtime)
675
- );
818
+ if (info.namespaceExportSymbol || info.wrapped) {
819
+ const usedName = exportsInfo.getUsedName(exportName, runtime);
820
+ if (!usedName) {
821
+ return {
822
+ info,
823
+ rawName: "/* unused export */ undefined",
824
+ ids: exportName.slice(1),
825
+ exportName
826
+ };
827
+ }
828
+ // an inlined export never reaches the exports object, so render the
829
+ // literal instead of reading the namespace
830
+ if (usedName instanceof InlinedUsedName) {
831
+ return {
832
+ info,
833
+ // Literal only; suffix is appended once via `ids` (see directExport branch).
834
+ rawName: usedName.render(
835
+ Template.toNormalComment(
836
+ `inlined export ${propertyAccess(exportName)}`
837
+ )
838
+ ),
839
+ ids: usedName.suffix,
840
+ exportName
841
+ };
842
+ }
676
843
  return {
677
844
  info,
678
845
  rawName: /** @type {string} */ (info.namespaceObjectName),
679
- ids: usedName,
846
+ ids: /** @type {ExportName} */ (usedName),
680
847
  exportName
681
848
  };
682
849
  }
@@ -717,8 +884,7 @@ const getFinalBinding = (
717
884
  return {
718
885
  info,
719
886
  rawName:
720
- (deferred ? info.deferredName : info.name) +
721
- (deferred ? ".a" : "") +
887
+ (deferred ? `${info.deferredName}.a` : getExternalModuleExpr(info)) +
722
888
  comment,
723
889
  ids: usedName,
724
890
  exportName
@@ -741,6 +907,7 @@ const getFinalBinding = (
741
907
  * @param {boolean | undefined} callContext callContext
742
908
  * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
743
909
  * @param {boolean | undefined} asiSafe asiSafe
910
+ * @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
744
911
  * @returns {string} the final name
745
912
  */
746
913
  const getFinalName = (
@@ -756,7 +923,8 @@ const getFinalName = (
756
923
  depDeferred,
757
924
  callContext,
758
925
  strictHarmonyModule,
759
- asiSafe
926
+ asiSafe,
927
+ moduleExportsAccess
760
928
  ) => {
761
929
  const binding = getFinalBinding(
762
930
  moduleGraph,
@@ -770,7 +938,8 @@ const getFinalName = (
770
938
  asCall,
771
939
  depDeferred,
772
940
  strictHarmonyModule,
773
- asiSafe
941
+ asiSafe,
942
+ moduleExportsAccess
774
943
  );
775
944
  {
776
945
  const { ids, comment } = binding;
@@ -778,9 +947,13 @@ const getFinalName = (
778
947
  let reference;
779
948
  /** @type {boolean} */
780
949
  let isPropertyAccess;
950
+ // the raw name is the wrapper accessor call itself, so the reference binds
951
+ // looser than the identifier it stands in for
952
+ let accessorCall = false;
781
953
  if ("rawName" in binding) {
782
954
  reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`;
783
955
  isPropertyAccess = ids.length > 0;
956
+ accessorCall = binding.accessorCall === true;
784
957
  } else {
785
958
  const { info, name: exportId } = binding;
786
959
  const name = info.internalNames.get(exportId);
@@ -799,13 +972,23 @@ const getFinalName = (
799
972
  reference = `${name}${comment || ""}${propertyAccess(ids)}`;
800
973
  isPropertyAccess = ids.length > 1;
801
974
  }
802
- if (isPropertyAccess && asCall && callContext === false) {
803
- return asiSafe
804
- ? `(0,${reference})`
805
- : asiSafe === false
806
- ? `;(0,${reference})`
807
- : `/*#__PURE__*/Object(${reference})`;
975
+
976
+ if (isPropertyAccess) {
977
+ if (asCall && callContext === false) {
978
+ return asiSafe
979
+ ? `(0,${reference})`
980
+ : asiSafe === false
981
+ ? `;(0,${reference})`
982
+ : `/*#__PURE__*/Object(${reference})`;
983
+ } else if (binding.info.wrapped) {
984
+ return asiSafe === false ? `;(${reference})` : `(${reference})`;
985
+ }
986
+ } else if (accessorCall && !asCall) {
987
+ // without parentheses `new X()` would construct the accessor rather
988
+ // than what it returns
989
+ return asiSafe === false ? `;(${reference})` : `(${reference})`;
808
990
  }
991
+
809
992
  return reference;
810
993
  }
811
994
  };
@@ -973,6 +1156,9 @@ class ConcatenatedModule extends Module {
973
1156
  */
974
1157
  build(options, compilation, resolver, fs, callback) {
975
1158
  const { rootModule } = this;
1159
+ const concatenateCommonJsModules = isCommonJsConcatenationEnabled(
1160
+ options.optimization.concatenateModules
1161
+ );
976
1162
  const { moduleArgument, exportsArgument } =
977
1163
  /** @type {BuildInfo} */
978
1164
  (rootModule.buildInfo);
@@ -1015,7 +1201,7 @@ class ConcatenatedModule extends Module {
1015
1201
  // populate dependencies — keep only deps that leave the concat set
1016
1202
  for (const d of m.dependencies) {
1017
1203
  if (
1018
- !Dependency.canConcatenate(d) ||
1204
+ !Dependency.canConcatenate(d, concatenateCommonJsModules) ||
1019
1205
  !this._modules.has(
1020
1206
  /** @type {Module} */
1021
1207
  (compilation.moduleGraph.getModule(d))
@@ -1127,11 +1313,19 @@ class ConcatenatedModule extends Module {
1127
1313
  * @returns {ConcatenationEntry[]} concatenation list
1128
1314
  */
1129
1315
  _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) {
1316
+ const concatenateCommonJsModules = isCommonJsConcatenationEnabled(
1317
+ this.compilation.options.optimization.concatenateModules
1318
+ );
1130
1319
  /** @type {ConcatenationEntry[]} */
1131
1320
  const list = [];
1132
1321
  /** @type {Map<Module, { runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} */
1133
1322
  const existingEntries = new Map();
1134
1323
 
1324
+ /** @type {Map<Module, Module[]>} */
1325
+ const importConnections = new Map();
1326
+ /** @type {Set<Module>} */
1327
+ const wrappedModules = new Set();
1328
+
1135
1329
  /**
1136
1330
  * @param {Module} module a module
1137
1331
  * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} imported modules in order
@@ -1150,7 +1344,10 @@ class ConcatenatedModule extends Module {
1150
1344
  .filter((connection) => {
1151
1345
  if (
1152
1346
  !connection.dependency ||
1153
- !Dependency.canConcatenate(connection.dependency)
1347
+ !Dependency.canConcatenate(
1348
+ connection.dependency,
1349
+ concatenateCommonJsModules
1350
+ )
1154
1351
  ) {
1155
1352
  return false;
1156
1353
  }
@@ -1172,7 +1369,12 @@ class ConcatenatedModule extends Module {
1172
1369
  (connection.dependency);
1173
1370
  return {
1174
1371
  connection,
1175
- sourceOrder: /** @type {number} */ (dep.sourceOrder),
1372
+ // A require() edge carries no sourceOrder; Infinity sorts it last,
1373
+ // matching the low-priority sentinel. NaN must not be used here:
1374
+ // compareNumbers returns 0 against every number, which makes the
1375
+ // comparator non-transitive and the order depend on insertion order.
1376
+ sourceOrder:
1377
+ typeof dep.sourceOrder === "number" ? dep.sourceOrder : Infinity,
1176
1378
  rangeStart: dep.range && dep.range[0],
1177
1379
  defer: ImportPhaseUtils.isDefer(dep.phase)
1178
1380
  };
@@ -1196,6 +1398,8 @@ class ConcatenatedModule extends Module {
1196
1398
  references.sort(concatComparators(bySourceOrder, byRangeStart));
1197
1399
  /** @type {Map<Module, { connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} */
1198
1400
  const referencesMap = new Map();
1401
+ /** @type {Module[] | undefined} */
1402
+ let targets;
1199
1403
  for (const { connection, defer } of references) {
1200
1404
  const runtimeCondition = filterRuntime(runtime, (r) =>
1201
1405
  connection.isTargetActive(r)
@@ -1203,6 +1407,17 @@ class ConcatenatedModule extends Module {
1203
1407
  if (runtimeCondition === false) continue;
1204
1408
  const nonDeferAccess = !defer;
1205
1409
  const module = connection.module;
1410
+ if (targets === undefined) targets = [module];
1411
+ else if (!targets.includes(module)) targets.push(module);
1412
+ if (
1413
+ [
1414
+ CommonJsRequireDependency,
1415
+ CommonJsFullRequireDependency,
1416
+ CommonJsExportRequireDependency
1417
+ ].some((Dep) => connection.dependency instanceof Dep)
1418
+ ) {
1419
+ wrappedModules.add(module);
1420
+ }
1206
1421
  const entry = referencesMap.get(module);
1207
1422
  if (entry === undefined) {
1208
1423
  referencesMap.set(module, {
@@ -1217,11 +1432,20 @@ class ConcatenatedModule extends Module {
1217
1432
  runtimeCondition,
1218
1433
  runtime
1219
1434
  );
1435
+ const wasDeferredOnly = !entry.nonDeferAccess;
1220
1436
  entry.nonDeferAccess = mergeNonDeferAccess(
1221
1437
  entry.nonDeferAccess,
1222
1438
  nonDeferAccess
1223
1439
  );
1440
+ // A deferred import does not evaluate, so the first eager reference
1441
+ // fixes the position; insertion order is emit order.
1442
+ if (wasDeferredOnly && nonDeferAccess) {
1443
+ entry.connection = connection;
1444
+ referencesMap.delete(module);
1445
+ referencesMap.set(module, entry);
1446
+ }
1224
1447
  }
1448
+ if (targets !== undefined) importConnections.set(module, targets);
1225
1449
  return referencesMap.values();
1226
1450
  };
1227
1451
 
@@ -1269,6 +1493,7 @@ class ConcatenatedModule extends Module {
1269
1493
  }
1270
1494
  list.push({
1271
1495
  type: "concatenated",
1496
+ wrapped: needWrapped(module),
1272
1497
  module: connection.module,
1273
1498
  runtimeCondition,
1274
1499
  nonDeferAccess
@@ -1335,6 +1560,7 @@ class ConcatenatedModule extends Module {
1335
1560
  }
1336
1561
  list.push({
1337
1562
  type: "external",
1563
+ wrapped: wrappedModules.has(connection.module),
1338
1564
  get module() {
1339
1565
  // We need to use a getter here, because the module in the dependency
1340
1566
  // could be replaced by some other process (i. e. also replaced with a
@@ -1357,11 +1583,39 @@ class ConcatenatedModule extends Module {
1357
1583
  }
1358
1584
  list.push({
1359
1585
  type: "concatenated",
1586
+ wrapped: needWrapped(rootModule),
1360
1587
  module: rootModule,
1361
1588
  runtimeCondition: true,
1362
1589
  nonDeferAccess: true
1363
1590
  });
1364
1591
 
1592
+ // A lazily evaluated member may only depend on lazily evaluated members,
1593
+ // so wrapping propagates forward from every `require()` target along all
1594
+ // import edges, ESM included.
1595
+ /** @type {Set<Module>} */
1596
+ const modules = new Set(wrappedModules);
1597
+ for (const entry of list) {
1598
+ if (entry.wrapped) modules.add(entry.module);
1599
+ }
1600
+ const queue = [...modules];
1601
+ for (let i = 0; i < queue.length; i++) {
1602
+ const targets = importConnections.get(queue[i]);
1603
+ if (targets === undefined) continue;
1604
+ for (const target of targets) {
1605
+ if (modules.has(target)) continue;
1606
+ modules.add(target);
1607
+ queue.push(target);
1608
+ }
1609
+ }
1610
+ for (const entry of list) {
1611
+ if (
1612
+ !entry.wrapped &&
1613
+ modules.has(entry.module) &&
1614
+ entryCanBeWrapped(entry)
1615
+ ) {
1616
+ entry.wrapped = true;
1617
+ }
1618
+ }
1365
1619
  return list;
1366
1620
  }
1367
1621
 
@@ -1416,6 +1670,40 @@ class ConcatenatedModule extends Module {
1416
1670
  }
1417
1671
  }
1418
1672
 
1673
+ /*
1674
+ * How the inner modules become one flat source. Stages [1]-[5] only mutate the
1675
+ * per-module info records (names, ReplaceSource patches); stages [6]-[9] append
1676
+ * to the single output ConcatSource, in exactly the order shown.
1677
+ *
1678
+ * _getModulesWithInfo() — ordered concatenation list + one info per module
1679
+ * | (concatenated [+wrapped] | external | reference)
1680
+ * v
1681
+ * [1] ANALYSE — inner codeGeneration() per module, into a ConcatenationScope
1682
+ * | plain -> ReplaceSource + ast + scope analysis
1683
+ * | wrapped -> ReplaceSource only, body kept verbatim
1684
+ * | external -> nothing yet, rendered as a require() below
1685
+ * [2] RESERVE — free globals of the analysed bodies enter allUsedNames, so
1686
+ * | renaming in [3] can't shadow them (a wrapped body is not analysed;
1687
+ * | the reserved `__webpack_` prefix protects it)
1688
+ * [3] RENAME — module-scope variables renamed inside the ReplaceSource, then
1689
+ * | the generated names allocated: wrapper accessor, namespace object,
1690
+ * | interop helpers, external import variable
1691
+ * [4] LINK — __WEBPACK_MODULE_REFERENCE__ tokens replaced by their final
1692
+ * | binding; through the ast for analysed bodies, textually for wrapped
1693
+ * [5] COLLECT EXPORTS — root exports split into used / unused / inlined
1694
+ * v
1695
+ * ---- from here on everything is appended to the result ConcatSource ----
1696
+ * |
1697
+ * [6] EMIT EXPORTS — __esModule flag + exports getters, UNUSED/INLINED lists
1698
+ * [7] BUILD NS — namespace object sources built as strings (not emitted yet)
1699
+ * [8] DEFINE — everything that must exist before any body runs: namespace
1700
+ * | objects, wrapper accessors (wrapped modules and wrapped externals),
1701
+ * | deferred external loaders
1702
+ * [9] EVALUATE — bodies in concatenation order: plain bodies inline, externals
1703
+ * | as require(); a wrapped body stays behind its accessor
1704
+ * v
1705
+ * [10] RESULT — CodeGenerationResult { sources, data, runtimeRequirements }
1706
+ */
1419
1707
  /**
1420
1708
  * Generates code and runtime requirements for this module.
1421
1709
  * @param {CodeGenerationContext} context context for code generation
@@ -1439,12 +1727,39 @@ class ConcatenatedModule extends Module {
1439
1727
  const runtime = intersectRuntime(generationRuntime, this._runtime);
1440
1728
 
1441
1729
  const requestShortener = runtimeTemplate.requestShortener;
1442
- // Meta info for each module
1730
+ // Meta info for each module, in evaluation order (repeats become references)
1443
1731
  const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo(
1444
1732
  moduleGraph,
1445
1733
  runtime
1446
1734
  );
1447
1735
 
1736
+ // This module's body is the root's body, so a wrapped root still evaluates
1737
+ // at its slot. No import edge inside the concatenation expresses that.
1738
+ const rootModuleInfo = moduleToInfoMap.get(this.rootModule);
1739
+ if (rootModuleInfo !== undefined) rootModuleInfo.eager = true;
1740
+
1741
+ // State shared by all stages below, in the order they are filled
1742
+
1743
+ // List of all used names to avoid conflicts
1744
+ const allUsedNames = new Set(RESERVED_NAMES);
1745
+
1746
+ // Updated Top level declarations are created by renaming
1747
+ /** @type {TopLevelDeclarations} */
1748
+ const topLevelDeclarations = new Set();
1749
+
1750
+ // Free names remaining in the rendered source (runtime globals are
1751
+ // tracked by runtimeRequirements instead)
1752
+ /** @type {Set<string>} */
1753
+ const freeNames = new Set();
1754
+
1755
+ // List of additional names in scope for module references
1756
+ /** @type {UsedNamesInScopeInfo} */
1757
+ const usedNamesInScopeInfo = new Map();
1758
+
1759
+ // Set of already checked scopes
1760
+ /** @type {Set<Scope>} */
1761
+ const ignoredScopes = new Set();
1762
+
1448
1763
  // Set with modules that need a generated namespace object
1449
1764
  /** @type {NeededNamespaceObjects} */
1450
1765
  const neededNamespaceObjects = new Set();
@@ -1454,11 +1769,8 @@ class ConcatenatedModule extends Module {
1454
1769
  /** @type {Set<ConcatenatedModuleInfo | ExternalModuleInfo>} */
1455
1770
  const neededEscapeNamespaceObjects = new Set();
1456
1771
 
1457
- // List of all used names to avoid conflicts
1458
- const allUsedNames = new Set(RESERVED_NAMES);
1459
-
1460
- // Generate source code and analyse scopes
1461
- // Prepare a ReplaceSource for the final source
1772
+ // #region [1] ANALYSE: run each inner module's own codeGeneration; a
1773
+ // non-wrapped body is parsed and scope-analysed so [3] can rename its locals
1462
1774
  for (const info of moduleToInfoMap.values()) {
1463
1775
  this._analyseModule(
1464
1776
  moduleToInfoMap,
@@ -1474,23 +1786,7 @@ class ConcatenatedModule extends Module {
1474
1786
  allUsedNames
1475
1787
  );
1476
1788
  }
1477
-
1478
- // Updated Top level declarations are created by renaming
1479
- /** @type {TopLevelDeclarations} */
1480
- const topLevelDeclarations = new Set();
1481
-
1482
- // Free names remaining in the rendered source (runtime globals are
1483
- // tracked by runtimeRequirements instead)
1484
- /** @type {Set<string>} */
1485
- const freeNames = new Set();
1486
-
1487
- // List of additional names in scope for module references
1488
- /** @type {UsedNamesInScopeInfo} */
1489
- const usedNamesInScopeInfo = new Map();
1490
-
1491
- // Set of already checked scopes
1492
- /** @type {Set<Scope>} */
1493
- const ignoredScopes = new Set();
1789
+ // #endregion
1494
1790
 
1495
1791
  /**
1496
1792
  * Lazily allocates a decoupled namespace object for a concatenated module
@@ -1501,12 +1797,22 @@ class ConcatenatedModule extends Module {
1501
1797
  * @returns {string | undefined} the escape namespace object name
1502
1798
  */
1503
1799
  const getEscapeNamespaceObjectName = (info) => {
1504
- if (info.type === "concatenated" && info.namespaceExportSymbol) {
1800
+ // Only a hoisted member's namespaceExportSymbol is a real variable
1801
+ // holding the original names; a wrapped one reuses the field for its
1802
+ // `X_namespaceFn()` call, which exposes the mangled keys
1803
+ if (
1804
+ info.type === "concatenated" &&
1805
+ !info.wrapped &&
1806
+ info.namespaceExportSymbol
1807
+ ) {
1505
1808
  return undefined;
1506
1809
  }
1810
+
1507
1811
  // Deferred external modules keep their special deferred namespace object
1508
1812
  // and are rendered through a different path that wouldn't emit ours.
1509
- if (info.type === "external" && info.deferred) return undefined;
1813
+ if (info.type === "external" && info.deferred) {
1814
+ return undefined;
1815
+ }
1510
1816
  // Only real ES module namespaces are decoupled; non-harmony modules use
1511
1817
  // their interop/fake namespace object as before.
1512
1818
  const buildMeta = /** @type {BuildMeta} */ (info.module.buildMeta);
@@ -1539,118 +1845,143 @@ class ConcatenatedModule extends Module {
1539
1845
  return name;
1540
1846
  };
1541
1847
 
1542
- // get all global names
1848
+ // #region [2] RESERVE: the free globals of every analysed body. Claiming
1849
+ // them up front is what lets [3] rename without shadowing any of them
1543
1850
  for (const info of modulesWithInfo) {
1544
- if (info.type === "concatenated" && !info.cjsWrapped) {
1545
- // ignore symbols from moduleScope
1546
- if (info.moduleScope) {
1547
- ignoredScopes.add(info.moduleScope);
1548
- }
1549
-
1550
- // The super class expression in class scopes behaves weird
1551
- // We get ranges of all super class expressions to make
1552
- // renaming to work correctly
1553
- /** @typedef {{ range: Range, variables: Variable[] }} ClassInfo */
1554
- /** @type {WeakMap<Scope, ClassInfo[]>} */
1555
- const superClassCache = new WeakMap();
1556
- /**
1557
- * @param {Scope} scope scope
1558
- * @returns {ClassInfo[]} result
1559
- */
1560
- const getSuperClassExpressions = (scope) => {
1561
- const cacheEntry = superClassCache.get(scope);
1562
- if (cacheEntry !== undefined) return cacheEntry;
1563
- /** @type {ClassInfo[]} */
1564
- const superClassExpressions = [];
1565
- for (const childScope of scope.childScopes) {
1566
- if (childScope.type !== "class") continue;
1567
- const block = childScope.block;
1851
+ if (info.type === "concatenated") {
1852
+ if (info.wrapped) {
1853
+ // The body is emitted verbatim and never renamed, so every identifier
1854
+ // in it is claimed: its declarations must not shadow a name [3]
1855
+ // generates, and its free globals must not be captured by one.
1856
+ for (const name of findIdentifiers(
1857
+ /** @type {Source} */ (info.internalSource)
1858
+ )) {
1859
+ allUsedNames.add(name);
1860
+ }
1861
+ // A wrapped body has no scope analysis, so its references are found
1862
+ // textually. They still have to be resolved here: binding one is what
1863
+ // flags the interop objects it needs, and [3] allocates their names.
1864
+ /** @type {Set<string>} */
1865
+ const visitedReferences = new Set();
1866
+ for (const reference of ConcatenationScope.findModuleReferences(
1867
+ /** @type {Source} */ (info.internalSource)
1868
+ )) {
1869
+ if (reference.leaked) {
1870
+ throw new Error(
1871
+ `Unsubstituted module reference "${reference.name}" in ${info.module.readableIdentifier(
1872
+ requestShortener
1873
+ )}`
1874
+ );
1875
+ }
1876
+ if (visitedReferences.has(reference.name)) continue;
1877
+ visitedReferences.add(reference.name);
1878
+ const match = ConcatenationScope.matchModuleReference(
1879
+ reference.name
1880
+ );
1881
+ if (!match) continue;
1882
+ const referencedInfo = modulesWithInfo[match.index];
1883
+ if (referencedInfo.type === "reference") {
1884
+ throw new Error("Module reference can't point to a reference");
1885
+ }
1568
1886
  if (
1569
- (block.type === "ClassDeclaration" ||
1570
- block.type === "ClassExpression") &&
1571
- block.superClass
1887
+ match.mangleableNamespace &&
1888
+ match.ids.length === 0 &&
1889
+ getEscapeNamespaceObjectName(referencedInfo) !== undefined
1572
1890
  ) {
1573
- superClassExpressions.push({
1574
- range: /** @type {Range} */ (block.superClass.range),
1575
- variables: childScope.variables
1576
- });
1891
+ continue;
1577
1892
  }
1893
+ getFinalBinding(
1894
+ moduleGraph,
1895
+ referencedInfo,
1896
+ match.ids,
1897
+ moduleToInfoMap,
1898
+ runtime,
1899
+ requestShortener,
1900
+ runtimeTemplate,
1901
+ neededNamespaceObjects,
1902
+ match.call,
1903
+ match.deferredImport,
1904
+ /** @type {BuildMeta} */
1905
+ (info.module.buildMeta).strictHarmonyModule,
1906
+ match.asiSafe,
1907
+ match.moduleExportsAccess
1908
+ );
1909
+ }
1910
+ } else {
1911
+ // ignore symbols from moduleScope
1912
+ if (info.moduleScope) {
1913
+ ignoredScopes.add(info.moduleScope);
1578
1914
  }
1579
- superClassCache.set(scope, superClassExpressions);
1580
- return superClassExpressions;
1581
- };
1582
1915
 
1583
- // add global symbols
1584
- if (info.globalScope) {
1585
- for (const reference of info.globalScope.through) {
1586
- const name = reference.identifier.name;
1587
- if (ConcatenationScope.isModuleReference(name)) {
1588
- const match = ConcatenationScope.matchModuleReference(name);
1589
- if (!match) continue;
1590
- const referencedInfo = modulesWithInfo[match.index];
1591
- if (referencedInfo.type === "reference") {
1592
- throw new Error("Module reference can't point to a reference");
1593
- }
1594
- // An escaping mangled namespace resolves to its own decoupled
1595
- // namespace object (a unique top-level name), so it neither needs
1596
- // the regular namespace object nor super-class scope handling.
1597
- if (
1598
- match.mangleableNamespace &&
1599
- match.ids.length === 0 &&
1600
- (referencedInfo.type === "concatenated" ||
1601
- referencedInfo.type === "external") &&
1602
- getEscapeNamespaceObjectName(referencedInfo) !== undefined
1603
- ) {
1604
- continue;
1605
- }
1606
- const binding = getFinalBinding(
1607
- moduleGraph,
1608
- referencedInfo,
1609
- match.ids,
1610
- moduleToInfoMap,
1611
- runtime,
1612
- requestShortener,
1613
- runtimeTemplate,
1614
- neededNamespaceObjects,
1615
- false,
1616
- match.deferredImport,
1617
- /** @type {BuildMeta} */
1618
- (info.module.buildMeta).strictHarmonyModule,
1619
- true
1620
- );
1621
- if (!binding.ids) continue;
1622
- const { usedNames, alreadyCheckedScopes } =
1623
- getUsedNamesInScopeInfo(
1624
- usedNamesInScopeInfo,
1625
- binding.info.module.identifier(),
1626
- "name" in binding ? binding.name : ""
1627
- );
1628
- for (const expr of getSuperClassExpressions(reference.from)) {
1916
+ // add global symbols
1917
+ if (info.unresolvedReferences) {
1918
+ for (const reference of info.unresolvedReferences) {
1919
+ const name = reference.identifier.name;
1920
+ if (ConcatenationScope.isModuleReference(name)) {
1921
+ const match = ConcatenationScope.matchModuleReference(name);
1922
+ if (!match) continue;
1923
+ const referencedInfo = modulesWithInfo[match.index];
1924
+ if (referencedInfo.type === "reference") {
1925
+ throw new Error(
1926
+ "Module reference can't point to a reference"
1927
+ );
1928
+ }
1929
+ // An escaping mangled namespace resolves to its own decoupled
1930
+ // namespace object (a unique top-level name), so it neither needs
1931
+ // the regular namespace object nor super-class scope handling.
1629
1932
  if (
1630
- expr.range[0] <=
1631
- /** @type {Range} */ (reference.identifier.range)[0] &&
1632
- expr.range[1] >=
1633
- /** @type {Range} */ (reference.identifier.range)[1]
1933
+ match.mangleableNamespace &&
1934
+ match.ids.length === 0 &&
1935
+ getEscapeNamespaceObjectName(referencedInfo) !== undefined
1634
1936
  ) {
1635
- for (const variable of expr.variables) {
1636
- usedNames.add(variable.name);
1637
- }
1937
+ continue;
1638
1938
  }
1939
+ const binding = getFinalBinding(
1940
+ moduleGraph,
1941
+ referencedInfo,
1942
+ match.ids,
1943
+ moduleToInfoMap,
1944
+ runtime,
1945
+ requestShortener,
1946
+ runtimeTemplate,
1947
+ neededNamespaceObjects,
1948
+ false,
1949
+ match.deferredImport,
1950
+ /** @type {BuildMeta} */
1951
+ (info.module.buildMeta).strictHarmonyModule,
1952
+ true,
1953
+ match.moduleExportsAccess
1954
+ );
1955
+ if (!binding.ids) continue;
1956
+ const { usedNames, alreadyCheckedScopes } =
1957
+ getUsedNamesInScopeInfo(
1958
+ usedNamesInScopeInfo,
1959
+ binding.info.module.identifier(),
1960
+ "name" in binding ? binding.name : ""
1961
+ );
1962
+ addScopeSymbols(
1963
+ reference.from,
1964
+ usedNames,
1965
+ alreadyCheckedScopes,
1966
+ ignoredScopes
1967
+ );
1968
+ } else {
1969
+ if (ConcatenationScope.isLeakedModuleReference(name)) {
1970
+ throw new Error(
1971
+ `Unsubstituted module reference "${name}" in ${info.module.readableIdentifier(
1972
+ requestShortener
1973
+ )}`
1974
+ );
1975
+ }
1976
+ allUsedNames.add(name);
1977
+ freeNames.add(name);
1639
1978
  }
1640
- addScopeSymbols(
1641
- reference.from,
1642
- usedNames,
1643
- alreadyCheckedScopes,
1644
- ignoredScopes
1645
- );
1646
- } else {
1647
- allUsedNames.add(name);
1648
- freeNames.add(name);
1649
1979
  }
1650
1980
  }
1651
1981
  }
1652
1982
  }
1653
1983
  }
1984
+ // #endregion
1654
1985
 
1655
1986
  /**
1656
1987
  * @param {string} name the name to find a new name for
@@ -1722,7 +2053,9 @@ class ConcatenatedModule extends Module {
1722
2053
  }
1723
2054
  };
1724
2055
 
1725
- // generate names for symbols
2056
+ // #region [3] RENAME: rename every module-scope variable inside its
2057
+ // ReplaceSource, then allocate the generated names (wrapper accessor,
2058
+ // namespace object, interop helpers, external import variable)
1726
2059
  for (const info of moduleToInfoMap.values()) {
1727
2060
  const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo(
1728
2061
  usedNamesInScopeInfo,
@@ -1731,82 +2064,85 @@ class ConcatenatedModule extends Module {
1731
2064
  );
1732
2065
  switch (info.type) {
1733
2066
  case "concatenated": {
1734
- if (info.cjsWrapped) {
1735
- // Wrapped modules expose one shared-scope name: the final
1736
- // exports object used as the namespace.
1737
- const namespaceObjectName = findNewName(
1738
- "namespaceObject",
2067
+ if (info.wrapped) {
2068
+ // A wrapped module declares exactly one shared-scope name: the
2069
+ // lazy wrapper accessor holding its body. [2] claimed every
2070
+ // identifier of that body, so findNewName avoids the ones that
2071
+ // would shadow the accessor from inside it.
2072
+ const namespaceFnName = findNewName(
2073
+ "namespaceFn",
1739
2074
  allUsedNames,
1740
2075
  namespaceObjectUsedNames,
1741
2076
  info.module.readableIdentifier(requestShortener)
1742
2077
  );
1743
- allUsedNames.add(namespaceObjectName);
1744
- topLevelDeclarations.add(namespaceObjectName);
1745
- info.namespaceObjectName = namespaceObjectName;
1746
- // Route every binding to the live exports alias and skip the
1747
- // materialized namespace object generated for other modules.
1748
- info.namespaceExportSymbol = namespaceObjectName;
1749
- break;
1750
- }
1751
- const variables = /** @type {Scope} */ (info.moduleScope).variables;
1752
- for (const variable of variables) {
1753
- const name = variable.name;
1754
- const references = getAllReferences(variable);
1755
- const newName = _findNewName(name, info, references);
1756
- if (newName) {
1757
- const source = /** @type {ReplaceSource} */ (info.source);
1758
- /** @type {Set<Identifier>} */
1759
- const allIdentifiers = new Set();
1760
- for (const r of references) allIdentifiers.add(r.identifier);
1761
- for (const identifier of variable.identifiers) {
1762
- allIdentifiers.add(identifier);
1763
- }
1764
- for (const identifier of allIdentifiers) {
1765
- const r = /** @type {Range} */ (identifier.range);
1766
- const path = getPathInAst(
1767
- /** @type {NonNullable<ConcatenatedModuleInfo["ast"]>} */
1768
- (info.ast),
1769
- identifier
1770
- );
1771
- if (path && path.length > 1) {
1772
- const maybeProperty =
1773
- path[1].type === "AssignmentPattern" &&
1774
- path[1].left === path[0]
1775
- ? path[2]
1776
- : path[1];
1777
- if (
1778
- maybeProperty.type === "Property" &&
1779
- maybeProperty.shorthand
1780
- ) {
1781
- source.insert(r[1], `: ${newName}`);
1782
- continue;
2078
+ allUsedNames.add(namespaceFnName);
2079
+ topLevelDeclarations.add(namespaceFnName);
2080
+ info.namespaceFnName = namespaceFnName;
2081
+ // Every reference — `require()` and ESM import alike — reads the
2082
+ // live exports object through the accessor, so the namespace is
2083
+ // the call itself, not a variable. Not a declared name.
2084
+ info.namespaceObjectName = `${namespaceFnName}()`;
2085
+ } else {
2086
+ const variables = /** @type {Scope} */ (info.moduleScope).variables;
2087
+ for (const variable of variables) {
2088
+ const name = variable.name;
2089
+ const references = getAllReferences(variable);
2090
+ const newName = _findNewName(name, info, references);
2091
+ if (newName) {
2092
+ const source = /** @type {ReplaceSource} */ (info.source);
2093
+ /** @type {Set<Identifier>} */
2094
+ const allIdentifiers = new Set();
2095
+ for (const r of references) allIdentifiers.add(r.identifier);
2096
+ for (const identifier of variable.identifiers) {
2097
+ allIdentifiers.add(identifier);
2098
+ }
2099
+ for (const identifier of allIdentifiers) {
2100
+ const r = /** @type {Range} */ (identifier.range);
2101
+ const path = getPathInAst(
2102
+ /** @type {NonNullable<ConcatenatedModuleInfo["ast"]>} */
2103
+ (info.ast),
2104
+ identifier
2105
+ );
2106
+ if (path && path.length > 1) {
2107
+ const maybeProperty =
2108
+ path[1].type === "AssignmentPattern" &&
2109
+ path[1].left === path[0]
2110
+ ? path[2]
2111
+ : path[1];
2112
+ if (
2113
+ maybeProperty.type === "Property" &&
2114
+ maybeProperty.shorthand
2115
+ ) {
2116
+ source.insert(r[1], `: ${newName}`);
2117
+ continue;
2118
+ }
1783
2119
  }
2120
+ source.replace(r[0], r[1] - 1, newName);
1784
2121
  }
1785
- source.replace(r[0], r[1] - 1, newName);
2122
+ } else {
2123
+ allUsedNames.add(name);
2124
+ info.internalNames.set(name, name);
2125
+ topLevelDeclarations.add(name);
1786
2126
  }
2127
+ }
2128
+ /** @type {string} */
2129
+ let namespaceObjectName;
2130
+ if (info.namespaceExportSymbol) {
2131
+ namespaceObjectName =
2132
+ /** @type {string} */
2133
+ (info.internalNames.get(info.namespaceExportSymbol));
1787
2134
  } else {
1788
- allUsedNames.add(name);
1789
- info.internalNames.set(name, name);
1790
- topLevelDeclarations.add(name);
2135
+ namespaceObjectName = findNewName(
2136
+ "namespaceObject",
2137
+ allUsedNames,
2138
+ namespaceObjectUsedNames,
2139
+ info.module.readableIdentifier(requestShortener)
2140
+ );
2141
+ allUsedNames.add(namespaceObjectName);
1791
2142
  }
2143
+ info.namespaceObjectName = namespaceObjectName;
2144
+ topLevelDeclarations.add(namespaceObjectName);
1792
2145
  }
1793
- /** @type {string} */
1794
- let namespaceObjectName;
1795
- if (info.namespaceExportSymbol) {
1796
- namespaceObjectName =
1797
- /** @type {string} */
1798
- (info.internalNames.get(info.namespaceExportSymbol));
1799
- } else {
1800
- namespaceObjectName = findNewName(
1801
- "namespaceObject",
1802
- allUsedNames,
1803
- namespaceObjectUsedNames,
1804
- info.module.readableIdentifier(requestShortener)
1805
- );
1806
- allUsedNames.add(namespaceObjectName);
1807
- }
1808
- info.namespaceObjectName = namespaceObjectName;
1809
- topLevelDeclarations.add(namespaceObjectName);
1810
2146
  break;
1811
2147
  }
1812
2148
  case "external": {
@@ -1820,6 +2156,18 @@ class ConcatenatedModule extends Module {
1820
2156
  info.name = externalName;
1821
2157
  topLevelDeclarations.add(externalName);
1822
2158
 
2159
+ if (info.wrapped) {
2160
+ const namespaceFnName = findNewName(
2161
+ "namespaceFn",
2162
+ allUsedNames,
2163
+ namespaceObjectUsedNames,
2164
+ info.module.readableIdentifier(requestShortener)
2165
+ );
2166
+ allUsedNames.add(namespaceFnName);
2167
+ info.namespaceFnName = namespaceFnName;
2168
+ topLevelDeclarations.add(namespaceFnName);
2169
+ }
2170
+
1823
2171
  if (info.deferred) {
1824
2172
  const externalName = findNewName(
1825
2173
  "deferred",
@@ -1883,15 +2231,20 @@ class ConcatenatedModule extends Module {
1883
2231
  topLevelDeclarations.add(externalNameInterop);
1884
2232
  }
1885
2233
  }
2234
+ // #endregion
1886
2235
 
1887
- // Find and replace references to modules
2236
+ // #region [4] LINK: resolve each cross-module reference token to the final
2237
+ // name picked in [3] and patch it in. Must run after [3] — a reference can
2238
+ // only be resolved once its target has been named
1888
2239
  for (const info of moduleToInfoMap.values()) {
1889
- if (info.type === "concatenated" && !info.cjsWrapped) {
1890
- const globalScope = /** @type {Scope} */ (info.globalScope);
2240
+ if (info.type !== "concatenated") continue;
2241
+ if (!info.wrapped) {
1891
2242
  // group references by name
1892
2243
  /** @type {Map<string, Reference[]>} */
1893
2244
  const referencesByName = new Map();
1894
- for (const reference of globalScope.through) {
2245
+ for (const reference of /** @type {Reference[]} */ (
2246
+ info.unresolvedReferences
2247
+ )) {
1895
2248
  const name = reference.identifier.name;
1896
2249
  let references = referencesByName.get(name);
1897
2250
  if (references === undefined) {
@@ -1936,10 +2289,7 @@ class ConcatenatedModule extends Module {
1936
2289
  // are mangled, point it at a decoupled namespace object that keeps
1937
2290
  // the original names so untracked access keeps working.
1938
2291
  const escapeName =
1939
- match.mangleableNamespace &&
1940
- match.ids.length === 0 &&
1941
- (referencedInfo.type === "concatenated" ||
1942
- referencedInfo.type === "external")
2292
+ match.mangleableNamespace && match.ids.length === 0
1943
2293
  ? getEscapeNamespaceObjectName(referencedInfo)
1944
2294
  : undefined;
1945
2295
  const finalName =
@@ -1959,7 +2309,8 @@ class ConcatenatedModule extends Module {
1959
2309
  !match.directImport,
1960
2310
  /** @type {BuildMeta} */
1961
2311
  (info.module.buildMeta).strictHarmonyModule,
1962
- match.asiSafe
2312
+ match.asiSafe,
2313
+ match.moduleExportsAccess
1963
2314
  );
1964
2315
 
1965
2316
  for (const reference of references) {
@@ -1970,9 +2321,64 @@ class ConcatenatedModule extends Module {
1970
2321
  }
1971
2322
  }
1972
2323
  }
2324
+ } else {
2325
+ // Wrapped bodies are not re-parsed: find their reference tokens
2326
+ // textually. [2] scanned the same source, so this reuses its result.
2327
+ /** @type {Map<string, string>} */
2328
+ const finalNames = new Map();
2329
+ const source = /** @type {ReplaceSource} */ (info.source);
2330
+ for (const reference of ConcatenationScope.findModuleReferences(
2331
+ /** @type {Source} */ (info.internalSource)
2332
+ )) {
2333
+ let finalName = finalNames.get(reference.name);
2334
+ if (finalName === undefined) {
2335
+ const match = ConcatenationScope.matchModuleReference(
2336
+ reference.name
2337
+ );
2338
+ if (!match) continue;
2339
+ const referencedInfo = modulesWithInfo[match.index];
2340
+ if (referencedInfo.type === "reference") {
2341
+ throw new Error("Module reference can't point to a reference");
2342
+ }
2343
+ // Same escaping whole-namespace rule as the hoisted branch above: a
2344
+ // wrapped target resolves to its `X_namespaceFn()` exports object,
2345
+ // whose keys are the mangled ones.
2346
+ const escapeName =
2347
+ match.mangleableNamespace && match.ids.length === 0
2348
+ ? getEscapeNamespaceObjectName(referencedInfo)
2349
+ : undefined;
2350
+ finalName =
2351
+ escapeName !== undefined
2352
+ ? escapeName
2353
+ : getFinalName(
2354
+ moduleGraph,
2355
+ referencedInfo,
2356
+ match.ids,
2357
+ moduleToInfoMap,
2358
+ runtime,
2359
+ requestShortener,
2360
+ runtimeTemplate,
2361
+ neededNamespaceObjects,
2362
+ match.call,
2363
+ match.deferredImport,
2364
+ !match.directImport,
2365
+ /** @type {BuildMeta} */
2366
+ (info.module.buildMeta).strictHarmonyModule,
2367
+ match.asiSafe,
2368
+ match.moduleExportsAccess
2369
+ );
2370
+ finalNames.set(reference.name, finalName);
2371
+ }
2372
+ // token end is extended by 2 chars to cover the appended "._"
2373
+ source.replace(reference.start, reference.end + 1, finalName);
2374
+ }
1973
2375
  }
1974
2376
  }
2377
+ // #endregion
1975
2378
 
2379
+ // #region [5] COLLECT EXPORTS: split the root module's exports into used /
2380
+ // unused / inlined. Used ones stay thunks — resolving one can still
2381
+ // register a namespace object, which [7] must see
1976
2382
  // Map with all root exposed used exports
1977
2383
  /** @type {Map<string, (requestShortener: RequestShortener) => string>} */
1978
2384
  const exportsMap = new Map();
@@ -2034,7 +2440,10 @@ class ConcatenatedModule extends Module {
2034
2440
  }
2035
2441
  });
2036
2442
  }
2443
+ // #endregion
2037
2444
 
2445
+ // #region [6] EMIT EXPORTS: first thing in the output — the exports getters
2446
+ // must exist before any body runs, so circular importers see them
2038
2447
  const result = new ConcatSource();
2039
2448
 
2040
2449
  // add harmony compatibility flag (must be first because of possible circular dependencies)
@@ -2063,15 +2472,14 @@ class ConcatenatedModule extends Module {
2063
2472
  runtimeRequirements.add(RuntimeGlobals.exports);
2064
2473
  runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
2065
2474
 
2066
- if (shouldAddHarmonyFlag) {
2067
- result.add("// ESM COMPAT FLAG\n");
2068
- result.add(
2069
- runtimeTemplate.defineEsModuleFlagStatement({
2475
+ // Goes with the definitions below: whoever takes those over emits both,
2476
+ // and the marker has to stay in front of them.
2477
+ const harmonyFlagSource = shouldAddHarmonyFlag
2478
+ ? `// ESM COMPAT FLAG\n${runtimeTemplate.defineEsModuleFlagStatement({
2070
2479
  exportsArgument: this.exportsArgument,
2071
2480
  runtimeRequirements
2072
- })
2073
- );
2074
- }
2481
+ })}`
2482
+ : "";
2075
2483
 
2076
2484
  const exportsSource =
2077
2485
  "\n// EXPORTS\n" +
@@ -2086,10 +2494,11 @@ class ConcatenatedModule extends Module {
2086
2494
  !onDemandExportsGeneration.call(
2087
2495
  this,
2088
2496
  runtimes,
2089
- exportsSource,
2497
+ `${harmonyFlagSource}${exportsSource}`,
2090
2498
  exportsFinalName
2091
2499
  )
2092
2500
  ) {
2501
+ result.add(harmonyFlagSource);
2093
2502
  result.add(exportsSource);
2094
2503
  }
2095
2504
  }
@@ -2107,7 +2516,12 @@ class ConcatenatedModule extends Module {
2107
2516
  `\n// INLINED EXPORTS: ${joinIterableWithComma(inlinedExports)}\n`
2108
2517
  );
2109
2518
  }
2519
+ // #endregion
2110
2520
 
2521
+ // #region [7] BUILD NS: namespace object sources are built as strings here
2522
+ // and emitted by [8]; an external's is emitted next to its import variable
2523
+ // or accessor instead, which is defined later.
2524
+ //
2111
2525
  // generate decoupled namespace objects for escaping mangled namespaces:
2112
2526
  // same getters as the regular namespace object, but keyed by the original
2113
2527
  // export names so untracked access by name keeps working. Done before the
@@ -2139,9 +2553,7 @@ class ConcatenatedModule extends Module {
2139
2553
  // import variable; concatenated ones resolve to an internal binding.
2140
2554
  const finalName =
2141
2555
  info.type === "external"
2142
- ? `${/** @type {string} */ (info.name)}${propertyAccess([
2143
- usedName
2144
- ])}`
2556
+ ? `${getExternalModuleExpr(info)}${propertyAccess([usedName])}`
2145
2557
  : getFinalName(
2146
2558
  moduleGraph,
2147
2559
  info,
@@ -2192,50 +2604,41 @@ ${defineGetters}`
2192
2604
  /** @type {Map<ConcatenatedModuleInfo, string>} */
2193
2605
  const namespaceObjectSources = new Map();
2194
2606
  for (const info of neededNamespaceObjects) {
2195
- if (info.namespaceExportSymbol) continue;
2607
+ if (
2608
+ info.namespaceExportSymbol ||
2609
+ // Skip constructing namespace object generated for wrapped module
2610
+ info.wrapped
2611
+ ) {
2612
+ continue;
2613
+ }
2196
2614
  /** @type {string[]} */
2197
2615
  const nsObj = [];
2198
2616
  const exportsInfo = moduleGraph.getExportsInfo(info.module);
2199
2617
  for (const exportInfo of exportsInfo.orderedExports) {
2200
2618
  if (exportInfo.provided === false) continue;
2201
2619
  const usedName = exportInfo.getUsedName(undefined, runtime);
2202
- if (usedName) {
2203
- // TODO: Replace with the inlined value directly at the call site
2204
- if (usedName instanceof InlinedUsedName) {
2205
- nsObj.push(
2206
- `\n ${propertyName(
2207
- exportInfo.name
2208
- )}: ${runtimeTemplate.returningFunction(
2209
- usedName.render(
2210
- Template.toNormalComment(
2211
- `inlined export ${propertyAccess([exportInfo.name])}`
2212
- )
2213
- )
2214
- )}`
2215
- );
2216
- } else {
2217
- const finalName = getFinalName(
2218
- moduleGraph,
2219
- info,
2220
- [exportInfo.name],
2221
- moduleToInfoMap,
2222
- runtime,
2223
- requestShortener,
2224
- runtimeTemplate,
2225
- neededNamespaceObjects,
2226
- false,
2227
- false,
2228
- undefined,
2229
- /** @type {BuildMeta} */
2230
- (info.module.buildMeta).strictHarmonyModule,
2231
- true
2232
- );
2233
- nsObj.push(
2234
- `\n ${propertyName(
2235
- usedName
2236
- )}: ${runtimeTemplate.returningFunction(finalName)}`
2237
- );
2238
- }
2620
+ if (usedName && !(usedName instanceof InlinedUsedName)) {
2621
+ const finalName = getFinalName(
2622
+ moduleGraph,
2623
+ info,
2624
+ [exportInfo.name],
2625
+ moduleToInfoMap,
2626
+ runtime,
2627
+ requestShortener,
2628
+ runtimeTemplate,
2629
+ neededNamespaceObjects,
2630
+ false,
2631
+ false,
2632
+ undefined,
2633
+ /** @type {BuildMeta} */
2634
+ (info.module.buildMeta).strictHarmonyModule,
2635
+ true
2636
+ );
2637
+ nsObj.push(
2638
+ `\n ${propertyName(
2639
+ usedName
2640
+ )}: ${runtimeTemplate.returningFunction(finalName)}`
2641
+ );
2239
2642
  }
2240
2643
  }
2241
2644
  const name = info.namespaceObjectName;
@@ -2258,20 +2661,92 @@ ${defineGetters}`
2258
2661
  );
2259
2662
  runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
2260
2663
  }
2664
+ // #endregion
2665
+
2666
+ // #region [8] DEFINE: define required namespace objects and wrapper
2667
+ // (must be before evaluation modules — a cycle member calls another's
2668
+ // accessor before that module's own position in the order)
2261
2669
 
2262
- // define required namespace objects (must be before evaluation modules)
2670
+ // wrapper accessors are only called later, so their definitions may be
2671
+ // emitted in a stable order of their own instead of concatenation order
2672
+ /** @type {(ConcatenatedModuleInfo | ExternalModuleInfo)[]} */
2673
+ const wrappedInfos = [];
2263
2674
  for (const info of modulesWithInfo) {
2675
+ if (
2676
+ (info.type === "concatenated" || info.type === "external") &&
2677
+ info.wrapped
2678
+ ) {
2679
+ wrappedInfos.push(info);
2680
+ }
2681
+ }
2682
+ const compareWrappedModules = compareModulesByFullName(
2683
+ runtimeTemplate.compilation.compiler
2684
+ );
2685
+ wrappedInfos.sort((a, b) => compareWrappedModules(a.module, b.module));
2686
+
2687
+ for (const info of wrappedInfos) {
2264
2688
  if (info.type === "concatenated") {
2265
- const source = namespaceObjectSources.get(info);
2266
- if (source) result.add(source);
2267
- const escapeSource = escapeNamespaceObjectSources.get(
2268
- /** @type {ConcatenatedModuleInfo} */ (info)
2689
+ runtimeRequirements.add(RuntimeGlobals.concatenationWrap);
2690
+ result.add(
2691
+ `\n// MODULE: ${info.module.readableIdentifier(
2692
+ requestShortener
2693
+ )}\nvar ${info.namespaceFnName} = /*#__PURE__*/${
2694
+ RuntimeGlobals.concatenationWrap
2695
+ }(function(${info.module.moduleArgument}, ${
2696
+ info.module.exportsArgument
2697
+ }) {\n`
2698
+ );
2699
+ result.add(/** @type {ReplaceSource} */ (info.source));
2700
+ // A generated body (json, asset, html) binds its value to a local
2701
+ // instead of writing exports; hand that local to the accessor. The
2702
+ // name is verbatim: a wrapped body is not scope-analysed, so it keeps
2703
+ // the reserved symbol the generator registered.
2704
+ result.add(
2705
+ info.namespaceExportSymbol
2706
+ ? `\n${info.module.moduleArgument}.exports = ${info.namespaceExportSymbol};\n});\n`
2707
+ : "\n});\n"
2708
+ );
2709
+ // its getters call the accessor lazily, so this may sit right after it
2710
+ const escapeSource = escapeNamespaceObjectSources.get(info);
2711
+ if (escapeSource) result.add(escapeSource);
2712
+ } else if (info.type === "external") {
2713
+ runtimeRequirements.add(RuntimeGlobals.require);
2714
+ const { runtimeCondition } = info;
2715
+ const condition = runtimeTemplate.runtimeConditionExpression({
2716
+ chunkGraph,
2717
+ runtimeCondition,
2718
+ runtime,
2719
+ runtimeRequirements
2720
+ });
2721
+ const moduleId = JSON.stringify(chunkGraph.getModuleId(info.module));
2722
+ const body =
2723
+ condition === "true"
2724
+ ? `return ${RuntimeGlobals.require}(${moduleId});`
2725
+ : `if (${condition}) return ${RuntimeGlobals.require}(${moduleId});`;
2726
+ result.add(
2727
+ `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
2728
+ requestShortener
2729
+ )}\nvar ${info.namespaceFnName} = ${runtimeTemplate.basicFunction(
2730
+ "",
2731
+ body
2732
+ )};\n`
2269
2733
  );
2734
+ const escapeSource = escapeNamespaceObjectSources.get(info);
2270
2735
  if (escapeSource) result.add(escapeSource);
2271
- if (!source && !escapeSource) continue;
2272
2736
  }
2737
+ }
2273
2738
 
2274
- if (info.type === "external" && info.deferred) {
2739
+ for (const info of modulesWithInfo) {
2740
+ if (info.type === "concatenated") {
2741
+ if (!info.wrapped) {
2742
+ const source = namespaceObjectSources.get(info);
2743
+ if (source) result.add(source);
2744
+ const escapeSource = escapeNamespaceObjectSources.get(
2745
+ /** @type {ConcatenatedModuleInfo} */ (info)
2746
+ );
2747
+ if (escapeSource) result.add(escapeSource);
2748
+ }
2749
+ } else if (info.type === "external" && info.deferred) {
2275
2750
  const moduleId = JSON.stringify(chunkGraph.getModuleId(info.module));
2276
2751
  const loader = getOptimizedDeferredModule(
2277
2752
  moduleId,
@@ -2316,10 +2791,13 @@ ${defineGetters}`
2316
2791
  }
2317
2792
  }
2318
2793
 
2794
+ // #endregion
2795
+
2796
+ // #region [9] EVALUATE: emit the bodies in concatenation order and collect
2797
+ // what they need — runtime requirements, chunk init fragments, interop
2319
2798
  /** @type {InitFragment<ChunkRenderContext>[]} */
2320
2799
  const chunkInitFragments = [];
2321
2800
 
2322
- // evaluate modules in order
2323
2801
  for (const rawInfo of modulesWithInfo) {
2324
2802
  /** @type {undefined | string} */
2325
2803
  let name;
@@ -2327,35 +2805,47 @@ ${defineGetters}`
2327
2805
  const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo;
2328
2806
  switch (info.type) {
2329
2807
  case "concatenated": {
2330
- result.add(
2331
- `\n;// ${info.module.readableIdentifier(requestShortener)}\n`
2332
- );
2333
- if (info.cjsWrapped) {
2334
- // Real CommonJS semantics via the runtime helper: it calls the
2335
- // body with this = exports and returns the final module.exports.
2336
- runtimeRequirements.add(RuntimeGlobals.commonJsWrap);
2808
+ name = info.namespaceObjectName;
2809
+ // wrapped bodies are emitted above, evaluated at their call sites
2810
+ if (info.wrapped && info.eager) {
2811
+ // This slot is the module's place in evaluation order; calling from
2812
+ // the importing body would run it too late.
2337
2813
  result.add(
2338
- `var ${info.namespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.commonJsWrap}(function(${info.module.moduleArgument}, ${info.module.exportsArgument}) {\n`
2814
+ `\n;// ${info.module.readableIdentifier(
2815
+ requestShortener
2816
+ )}\n${info.namespaceFnName}();\n`
2817
+ );
2818
+ } else if (!info.wrapped) {
2819
+ result.add(
2820
+ `\n;// ${info.module.readableIdentifier(requestShortener)}\n`
2339
2821
  );
2340
- result.add(/** @type {ReplaceSource} */ (info.source));
2341
- result.add("\n});\n");
2342
- } else {
2343
2822
  result.add(/** @type {ReplaceSource} */ (info.source));
2344
2823
  }
2824
+
2345
2825
  if (info.chunkInitFragments) {
2346
2826
  for (const f of info.chunkInitFragments) chunkInitFragments.push(f);
2347
2827
  }
2348
2828
  if (info.runtimeRequirements) {
2349
2829
  for (const r of info.runtimeRequirements) {
2830
+ // Wrapped module supplies module/exports/this itself
2831
+ if (
2832
+ info.wrapped &&
2833
+ (r === RuntimeGlobals.module ||
2834
+ r === RuntimeGlobals.exports ||
2835
+ r === RuntimeGlobals.thisAsExports)
2836
+ ) {
2837
+ continue;
2838
+ }
2350
2839
  runtimeRequirements.add(r);
2351
2840
  }
2352
2841
  }
2353
- name = info.namespaceObjectName;
2842
+
2354
2843
  break;
2355
2844
  }
2356
2845
  case "external": {
2357
- // deferred case is handled in the "const info of modulesWithInfo" loop above
2358
- if (!info.deferred) {
2846
+ name = getExternalModuleExpr(info);
2847
+ // deferred and wrapped cases are handled in the "const info of modulesWithInfo" loop above
2848
+ if (!info.deferred && !info.wrapped) {
2359
2849
  result.add(
2360
2850
  `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
2361
2851
  requestShortener
@@ -2382,11 +2872,17 @@ ${defineGetters}`
2382
2872
  // runtime-condition `if` blocks but referenced outside,
2383
2873
  // so they must remain function-scoped (`var`).
2384
2874
  result.add(`var ${info.name} = __webpack_require__(${moduleId});`);
2385
- name = info.name;
2875
+
2386
2876
  // Decoupled namespace object for an escaping mangled external
2387
2877
  // module must come after its import variable is defined.
2388
2878
  const escapeSource = escapeNamespaceObjectSources.get(info);
2389
2879
  if (escapeSource) result.add(escapeSource);
2880
+ } else if (info.wrapped && info.eager) {
2881
+ result.add(
2882
+ `\n;// EXTERNAL MODULE: ${info.module.readableIdentifier(
2883
+ requestShortener
2884
+ )}\n${info.namespaceFnName}();\n`
2885
+ );
2390
2886
  }
2391
2887
  // If a module is deferred in other places, but used as non-deferred here,
2392
2888
  // the module itself will be emitted as mod_deferred (in the case "external"),
@@ -2394,7 +2890,7 @@ ${defineGetters}`
2394
2890
  const { nonDeferAccess } =
2395
2891
  /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */
2396
2892
  (rawInfo);
2397
- if (info.deferred && nonDeferAccess) {
2893
+ if (info.deferred && nonDeferAccess && !info.wrapped) {
2398
2894
  result.add(
2399
2895
  `\n// non-deferred import to a deferred module (${info.module.readableIdentifier(
2400
2896
  requestShortener
@@ -2407,29 +2903,54 @@ ${defineGetters}`
2407
2903
  // @ts-expect-error never is expected here
2408
2904
  throw new Error(`Unsupported concatenation entry type ${info.type}`);
2409
2905
  }
2906
+ // Building a wrapped module's interop object here would evaluate its body
2907
+ // at the top level and break require() cycles, so defer it behind a
2908
+ // hoisted function. The memo lives on the function object: it keeps the
2909
+ // identity stable without claiming a second top-level name.
2910
+ /**
2911
+ * @param {string} interopName interop variable name
2912
+ * @param {string} expr interop object expression
2913
+ * @returns {string} the declaration
2914
+ */
2915
+ const declareInterop = (interopName, expr) =>
2916
+ info.wrapped
2917
+ ? `\nfunction ${interopName}() { return ${interopName}.c || (${interopName}.c = ${expr}); }`
2918
+ : `\nvar ${interopName} = /*#__PURE__*/${expr};`;
2410
2919
  if (info.interopNamespaceObjectUsed) {
2411
2920
  runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
2412
2921
  result.add(
2413
- `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);`
2922
+ declareInterop(
2923
+ /** @type {string} */ (info.interopNamespaceObjectName),
2924
+ `${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2)`
2925
+ )
2414
2926
  );
2415
2927
  }
2416
2928
  if (info.interopNamespaceObject2Used) {
2417
2929
  runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
2418
2930
  result.add(
2419
- `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});`
2931
+ declareInterop(
2932
+ /** @type {string} */ (info.interopNamespaceObject2Name),
2933
+ `${RuntimeGlobals.createFakeNamespaceObject}(${name})`
2934
+ )
2420
2935
  );
2421
2936
  }
2422
2937
  if (info.interopDefaultAccessUsed) {
2423
2938
  runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
2424
2939
  result.add(
2425
- `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});`
2940
+ declareInterop(
2941
+ /** @type {string} */ (info.interopDefaultAccessName),
2942
+ `${RuntimeGlobals.compatGetDefaultExport}(${name})`
2943
+ )
2426
2944
  );
2427
2945
  }
2428
2946
  if (isConditional) {
2429
2947
  result.add("\n}");
2430
2948
  }
2431
2949
  }
2950
+ // #endregion
2432
2951
 
2952
+ // #region [10] RESULT: topLevelDeclarations and freeNames let consumers
2953
+ // (mangling, an outer concatenation) reason about this source unparsed
2433
2954
  /** @type {CodeGenerationResultData} */
2434
2955
  const data = new Map();
2435
2956
  if (chunkInitFragments.length > 0) {
@@ -2444,6 +2965,7 @@ ${defineGetters}`
2444
2965
  data,
2445
2966
  runtimeRequirements
2446
2967
  };
2968
+ // #endregion
2447
2969
 
2448
2970
  return resultEntry;
2449
2971
  }
@@ -2474,43 +2996,17 @@ ${defineGetters}`
2474
2996
  ) {
2475
2997
  if (info.type === "concatenated") {
2476
2998
  const m = info.module;
2477
- try {
2478
- if (info.cjsWrapped) {
2479
- // A wrapped module renders its normal module source (real
2480
- // module/exports objects, own module ids) inside an IIFE, so it
2481
- // needs no concatenation scope, reference rewriting, or scope
2482
- // analysis — the wrapper isolates its top-level declarations.
2483
- const codeGenResult = m.codeGeneration({
2484
- dependencyTemplates,
2485
- runtimeTemplate,
2486
- moduleGraph,
2487
- chunkGraph,
2488
- runtime,
2489
- runtimes,
2490
- codeGenerationResults,
2491
- sourceTypes: JAVASCRIPT_TYPES
2492
- });
2493
- const source =
2494
- /** @type {Source} */
2495
- (codeGenResult.sources.get(JAVASCRIPT_TYPE));
2496
- const data = codeGenResult.data;
2497
- info.runtimeRequirements =
2498
- /** @type {ReadOnlyRuntimeRequirements} */
2499
- (codeGenResult.runtimeRequirements);
2500
- info.internalSource = source;
2501
- info.source = new ReplaceSource(source);
2502
- info.chunkInitFragments = data && data.get("chunkInitFragments");
2503
- return;
2504
- }
2505
- // Create a concatenation scope to track and capture information
2999
+ if (info.wrapped) {
3000
+ // the wrapper isolates the body's top-level declarations, so no
3001
+ // renaming is needed -- only a concatenation scope, to rewrite in-scope
3002
+ // `require()` targets to accessor references. [2] claims its identifiers
3003
+ // textually in place of the scope analysis skipped here.
2506
3004
  const concatenationScope = new ConcatenationScope(
2507
3005
  modulesMap,
2508
3006
  info,
2509
3007
  usedNames
2510
3008
  );
2511
-
2512
- // Not cached: Compilation memoizes the outer codeGeneration per
2513
- // (module, runtime), so inner generation never recomputes usefully.
3009
+ info.concatenationScope = concatenationScope;
2514
3010
  const codeGenResult = m.codeGeneration({
2515
3011
  dependencyTemplates,
2516
3012
  runtimeTemplate,
@@ -2526,69 +3022,95 @@ ${defineGetters}`
2526
3022
  /** @type {Source} */
2527
3023
  (codeGenResult.sources.get(JAVASCRIPT_TYPE));
2528
3024
  const data = codeGenResult.data;
2529
- const chunkInitFragments = data && data.get("chunkInitFragments");
2530
- const code = source.source().toString();
2531
-
2532
- /** @type {Program} */
2533
- let ast;
2534
-
2535
- try {
2536
- const { experiments } = this.compilation.options;
2537
-
2538
- ({ ast } = JavascriptParser._parse(
2539
- code,
2540
- {
2541
- sourceType: "module",
2542
- ranges: true,
2543
- // generated code contains phase imports when the experiments are on
2544
- importPhases: Boolean(
2545
- experiments.deferImport || experiments.sourceImport
2546
- )
2547
- },
2548
- JavascriptParser._getModuleParseFunction(this.compilation, m)
2549
- ));
2550
- } catch (_err) {
2551
- const err =
2552
- /** @type {Error & { loc?: { line: number, column: number } }} */
2553
- (_err);
2554
- if (
2555
- err.loc &&
2556
- typeof err.loc === "object" &&
2557
- typeof err.loc.line === "number"
2558
- ) {
2559
- const lineNumber = err.loc.line;
2560
- const lines = code.split("\n");
2561
- err.message += `\n| ${lines
2562
- .slice(Math.max(0, lineNumber - 3), lineNumber + 2)
2563
- .join("\n| ")}`;
2564
- }
2565
- throw err;
2566
- }
2567
- const scopeManager = eslintScope.analyze(ast, {
2568
- ecmaVersion: 6,
2569
- sourceType: "module",
2570
- optimistic: true,
2571
- ignoreEval: true,
2572
- impliedStrict: true
2573
- });
2574
- const globalScope = /** @type {Scope} */ (scopeManager.acquire(ast));
2575
- const moduleScope = globalScope.childScopes[0];
2576
- const resultSource = new ReplaceSource(source);
2577
3025
  info.runtimeRequirements =
2578
3026
  /** @type {ReadOnlyRuntimeRequirements} */
2579
3027
  (codeGenResult.runtimeRequirements);
2580
- info.ast = ast;
2581
3028
  info.internalSource = source;
2582
- info.source = resultSource;
2583
- info.chunkInitFragments = chunkInitFragments;
2584
- info.globalScope = globalScope;
2585
- info.moduleScope = moduleScope;
2586
- info.concatenationScope = concatenationScope;
2587
- } catch (err) {
2588
- /** @type {Error} */
2589
- (err).message +=
2590
- `\nwhile analyzing module ${m.identifier()} for concatenation`;
2591
- throw err;
3029
+ info.source = new ReplaceSource(source);
3030
+ info.chunkInitFragments = data && data.get("chunkInitFragments");
3031
+ } else {
3032
+ try {
3033
+ // Create a concatenation scope to track and capture information
3034
+ const concatenationScope = new ConcatenationScope(
3035
+ modulesMap,
3036
+ info,
3037
+ usedNames
3038
+ );
3039
+
3040
+ // Not cached: Compilation memoizes the outer codeGeneration per
3041
+ // (module, runtime), so inner generation never recomputes usefully.
3042
+ const codeGenResult = m.codeGeneration({
3043
+ dependencyTemplates,
3044
+ runtimeTemplate,
3045
+ moduleGraph,
3046
+ chunkGraph,
3047
+ runtime,
3048
+ runtimes,
3049
+ concatenationScope,
3050
+ codeGenerationResults,
3051
+ sourceTypes: JAVASCRIPT_TYPES
3052
+ });
3053
+ const source =
3054
+ /** @type {Source} */
3055
+ (codeGenResult.sources.get(JAVASCRIPT_TYPE));
3056
+ const data = codeGenResult.data;
3057
+ const chunkInitFragments = data && data.get("chunkInitFragments");
3058
+ const code = source.source().toString();
3059
+
3060
+ /** @type {Program} */
3061
+ let ast;
3062
+
3063
+ try {
3064
+ const { experiments } = this.compilation.options;
3065
+
3066
+ ({ ast } = JavascriptParser._parse(
3067
+ code,
3068
+ {
3069
+ sourceType: "module",
3070
+ ranges: true,
3071
+ // generated code contains phase imports when the experiments are on
3072
+ importPhases: Boolean(
3073
+ experiments.deferImport || experiments.sourceImport
3074
+ )
3075
+ },
3076
+ JavascriptParser._getModuleParseFunction(this.compilation, m)
3077
+ ));
3078
+ } catch (_err) {
3079
+ const err =
3080
+ /** @type {Error & { loc?: { line: number, column: number } }} */
3081
+ (_err);
3082
+ if (
3083
+ err.loc &&
3084
+ typeof err.loc === "object" &&
3085
+ typeof err.loc.line === "number"
3086
+ ) {
3087
+ const lineNumber = err.loc.line;
3088
+ const lines = code.split("\n");
3089
+ err.message += `\n| ${lines
3090
+ .slice(Math.max(0, lineNumber - 3), lineNumber + 2)
3091
+ .join("\n| ")}`;
3092
+ }
3093
+ throw err;
3094
+ }
3095
+ const analysis = analyzeScope(ast);
3096
+ const resultSource = new ReplaceSource(source);
3097
+ info.runtimeRequirements =
3098
+ /** @type {ReadOnlyRuntimeRequirements} */
3099
+ (codeGenResult.runtimeRequirements);
3100
+ info.ast = ast;
3101
+ info.internalSource = source;
3102
+ info.source = resultSource;
3103
+ info.chunkInitFragments = chunkInitFragments;
3104
+ info.globalScope = analysis.globalScope;
3105
+ info.moduleScope = analysis.moduleScope;
3106
+ info.unresolvedReferences = analysis.unresolvedReferences;
3107
+ info.concatenationScope = concatenationScope;
3108
+ } catch (err) {
3109
+ /** @type {Error} */
3110
+ (err).message +=
3111
+ `\nwhile analyzing module ${m.identifier()} for concatenation`;
3112
+ throw err;
3113
+ }
2592
3114
  }
2593
3115
  }
2594
3116
  }
@@ -2614,17 +3136,18 @@ ${defineGetters}`
2614
3136
  case "concatenated":
2615
3137
  item = {
2616
3138
  type: "concatenated",
3139
+ wrapped: info.wrapped,
3140
+ eager: false,
2617
3141
  module: info.module,
2618
3142
  index,
2619
- cjsWrapped: isCommonJsWrapped(
2620
- /** @type {NormalModule} */ (info.module)
2621
- ),
3143
+ namespaceFnName: undefined,
2622
3144
  ast: undefined,
2623
3145
  chunkInitFragments: undefined,
2624
3146
  internalSource: undefined,
2625
3147
  runtimeRequirements: undefined,
2626
3148
  source: undefined,
2627
3149
  globalScope: undefined,
3150
+ unresolvedReferences: undefined,
2628
3151
  moduleScope: undefined,
2629
3152
  internalNames: new Map(),
2630
3153
  exportMap: undefined,
@@ -2646,11 +3169,14 @@ ${defineGetters}`
2646
3169
  case "external":
2647
3170
  item = {
2648
3171
  type: "external",
3172
+ wrapped: info.wrapped,
3173
+ eager: false,
2649
3174
  module: info.module,
2650
3175
  runtimeCondition: info.runtimeCondition,
2651
3176
  nonDeferAccess: info.nonDeferAccess,
2652
3177
  index,
2653
3178
  name: undefined,
3179
+ namespaceFnName: undefined,
2654
3180
  escapeNamespaceObjectName: undefined,
2655
3181
  deferredName: undefined,
2656
3182
  interopNamespaceObjectUsed: false,
@@ -2761,4 +3287,32 @@ ConcatenatedModule.getCompilationHooks = createHooksRegistry(
2761
3287
 
2762
3288
  makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule");
2763
3289
 
3290
+ /** @type {WeakMap<Compilation, WeakMap<Module, ConcatenatedModule>>} */
3291
+ const absorbedBy = new WeakMap();
3292
+
3293
+ /**
3294
+ * The module the chunk graph holds for `module`: concatenation replaces every module
3295
+ * it absorbs with one `ConcatenatedModule`, so an absorbed module is itself in no
3296
+ * chunk and no runtime, and asking the chunk graph about it answers about nothing.
3297
+ * @param {Compilation} compilation the compilation
3298
+ * @param {Module} module a module, possibly absorbed by concatenation
3299
+ * @returns {Module} the module the chunk graph holds, or `module` itself
3300
+ */
3301
+ ConcatenatedModule.getChunkGraphModule = (compilation, module) => {
3302
+ let map = absorbedBy.get(compilation);
3303
+ if (map === undefined) {
3304
+ map = new WeakMap();
3305
+ for (const candidate of compilation.modules) {
3306
+ if (candidate instanceof ConcatenatedModule) {
3307
+ for (const inner of candidate._modules) {
3308
+ map.set(inner, candidate);
3309
+ }
3310
+ }
3311
+ }
3312
+ absorbedBy.set(compilation, map);
3313
+ }
3314
+ const outer = map.get(module);
3315
+ return outer === undefined ? module : outer;
3316
+ };
3317
+
2764
3318
  module.exports = ConcatenatedModule;