@depup/webpack 5.106.0-depup.0 → 5.109.0-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 (667) hide show
  1. package/README.md +9 -11
  2. package/changes.json +16 -24
  3. package/hot/dev-server.js +2 -0
  4. package/lib/APIPlugin.js +60 -35
  5. package/lib/AsyncDependenciesBlock.js +3 -0
  6. package/lib/AutomaticPrefetchPlugin.js +6 -1
  7. package/lib/BannerPlugin.js +13 -5
  8. package/lib/Cache.js +27 -5
  9. package/lib/CacheFacade.js +41 -0
  10. package/lib/Chunk.js +71 -25
  11. package/lib/ChunkGraph.js +141 -9
  12. package/lib/ChunkGroup.js +115 -28
  13. package/lib/ChunkTemplate.js +9 -0
  14. package/lib/CircularModulesPlugin.js +190 -0
  15. package/lib/CleanPlugin.js +23 -26
  16. package/lib/CodeGenerationResults.js +19 -0
  17. package/lib/CompatibilityPlugin.js +54 -37
  18. package/lib/Compilation.js +635 -107
  19. package/lib/Compiler.js +93 -31
  20. package/lib/ConcatenationScope.js +34 -4
  21. package/lib/ConditionalInitFragment.js +6 -0
  22. package/lib/ConstPlugin.js +15 -12
  23. package/lib/ContextExclusionPlugin.js +3 -1
  24. package/lib/ContextModule.js +345 -55
  25. package/lib/ContextModuleFactory.js +193 -51
  26. package/lib/ContextReplacementPlugin.js +8 -1
  27. package/lib/DefinePlugin.js +498 -127
  28. package/lib/DependenciesBlock.js +6 -1
  29. package/lib/Dependency.js +159 -11
  30. package/lib/DependencyTemplate.js +7 -1
  31. package/lib/DependencyTemplates.js +4 -0
  32. package/lib/DotenvPlugin.js +3 -0
  33. package/lib/DynamicEntryPlugin.js +3 -1
  34. package/lib/EntryOptionPlugin.js +42 -2
  35. package/lib/EntryPlugin.js +4 -1
  36. package/lib/Entrypoint.js +5 -1
  37. package/lib/EnvironmentPlugin.js +3 -2
  38. package/lib/ErrorHelpers.js +7 -0
  39. package/lib/EvalDevToolModulePlugin.js +3 -1
  40. package/lib/EvalSourceMapDevToolPlugin.js +11 -11
  41. package/lib/ExportsInfo.js +399 -108
  42. package/lib/ExportsInfoApiPlugin.js +4 -3
  43. package/lib/ExternalModule.js +376 -78
  44. package/lib/ExternalModuleFactoryPlugin.js +75 -3
  45. package/lib/ExternalsPlugin.js +3 -1
  46. package/lib/FileSystemInfo.js +575 -149
  47. package/lib/FlagAllModulesAsUsedPlugin.js +3 -6
  48. package/lib/FlagDependencyExportsPlugin.js +82 -9
  49. package/lib/FlagDependencyUsagePlugin.js +92 -6
  50. package/lib/FlagEntryExportAsUsedPlugin.js +4 -1
  51. package/lib/Generator.js +24 -3
  52. package/lib/HotModuleReplacementPlugin.js +110 -44
  53. package/lib/IgnorePlugin.js +5 -2
  54. package/lib/IgnoreWarningsPlugin.js +2 -1
  55. package/lib/InitFragment.js +15 -0
  56. package/lib/JavascriptMetaInfoPlugin.js +9 -6
  57. package/lib/LazyBarrel.js +389 -0
  58. package/lib/LibraryTemplatePlugin.js +2 -1
  59. package/lib/LoaderOptionsPlugin.js +3 -1
  60. package/lib/LoaderTargetPlugin.js +3 -1
  61. package/lib/MainTemplate.js +15 -0
  62. package/lib/ManifestPlugin.js +9 -2
  63. package/lib/Module.js +121 -60
  64. package/lib/ModuleFactory.js +6 -1
  65. package/lib/ModuleFilenameHelpers.js +5 -2
  66. package/lib/ModuleGraph.js +69 -2
  67. package/lib/ModuleGraphConnection.js +9 -0
  68. package/lib/ModuleInfoHeaderPlugin.js +5 -0
  69. package/lib/ModuleNotFoundError.js +3 -83
  70. package/lib/ModuleProfile.js +27 -1
  71. package/lib/ModuleSourceTypeConstants.js +52 -19
  72. package/lib/ModuleTemplate.js +10 -0
  73. package/lib/ModuleTypeConstants.js +20 -4
  74. package/lib/MultiCompiler.js +59 -4
  75. package/lib/MultiStats.js +9 -0
  76. package/lib/MultiWatching.js +6 -0
  77. package/lib/NoEmitOnErrorsPlugin.js +1 -1
  78. package/lib/NodeStuffPlugin.js +78 -46
  79. package/lib/NormalModule.js +485 -181
  80. package/lib/NormalModuleFactory.js +148 -29
  81. package/lib/NormalModuleReplacementPlugin.js +3 -1
  82. package/lib/NullFactory.js +1 -0
  83. package/lib/OptionsApply.js +1 -0
  84. package/lib/Parser.js +3 -1
  85. package/lib/PlatformPlugin.js +2 -1
  86. package/lib/PrefetchPlugin.js +4 -1
  87. package/lib/ProgressPlugin.js +351 -161
  88. package/lib/ProvidePlugin.js +6 -3
  89. package/lib/RawModule.js +32 -16
  90. package/lib/RecordIdsPlugin.js +9 -0
  91. package/lib/RequestShortener.js +8 -0
  92. package/lib/ResolverFactory.js +5 -0
  93. package/lib/RuntimeGlobals.js +58 -5
  94. package/lib/RuntimeModule.js +22 -7
  95. package/lib/RuntimePlugin.js +104 -26
  96. package/lib/RuntimeTemplate.js +616 -37
  97. package/lib/SelfModuleFactory.js +3 -0
  98. package/lib/SourceMapDevToolModuleOptionsPlugin.js +2 -0
  99. package/lib/SourceMapDevToolPlugin.js +341 -63
  100. package/lib/Stats.js +6 -0
  101. package/lib/Template.js +29 -3
  102. package/lib/TemplatedPathPlugin.js +505 -138
  103. package/lib/UseStrictPlugin.js +3 -2
  104. package/lib/WarnCaseSensitiveModulesPlugin.js +72 -3
  105. package/lib/WarnDeprecatedOptionPlugin.js +6 -2
  106. package/lib/WarnNoModeSetPlugin.js +18 -2
  107. package/lib/WatchIgnorePlugin.js +5 -1
  108. package/lib/Watching.js +25 -3
  109. package/lib/WebpackError.js +3 -74
  110. package/lib/WebpackIsIncludedPlugin.js +4 -2
  111. package/lib/WebpackOptionsApply.js +88 -25
  112. package/lib/WebpackOptionsDefaulter.js +1 -0
  113. package/lib/asset/AssetBytesGenerator.js +28 -10
  114. package/lib/asset/AssetBytesParser.js +1 -0
  115. package/lib/asset/AssetGenerator.js +199 -60
  116. package/lib/asset/AssetModule.js +47 -0
  117. package/lib/asset/AssetModulesPlugin.js +115 -24
  118. package/lib/asset/AssetParser.js +4 -2
  119. package/lib/asset/AssetSourceGenerator.js +26 -8
  120. package/lib/asset/AssetSourceParser.js +1 -0
  121. package/lib/asset/RawDataUrlModule.js +23 -13
  122. package/lib/asset/WebManifestGenerator.js +164 -0
  123. package/lib/asset/WebManifestParser.js +130 -0
  124. package/lib/async-modules/AsyncModuleHelpers.js +1 -0
  125. package/lib/async-modules/AwaitDependenciesInitFragment.js +18 -4
  126. package/lib/async-modules/InferAsyncModulesPlugin.js +1 -1
  127. package/lib/async-modules/isGeneratorLowered.js +26 -0
  128. package/lib/buildChunkGraph.js +107 -15
  129. package/lib/bun/BunTargetPlugin.js +42 -0
  130. package/lib/cache/AddBuildDependenciesPlugin.js +3 -1
  131. package/lib/cache/AddManagedPathsPlugin.js +5 -1
  132. package/lib/cache/IdleFileCachePlugin.js +6 -1
  133. package/lib/cache/MemoryCachePlugin.js +1 -1
  134. package/lib/cache/MemoryWithGcCachePlugin.js +4 -1
  135. package/lib/cache/PackFileCacheStrategy.js +43 -7
  136. package/lib/cache/ResolverCachePlugin.js +12 -1
  137. package/lib/cache/getLazyHashedEtag.js +13 -2
  138. package/lib/cache/mergeEtags.js +4 -0
  139. package/lib/cli.js +142 -20
  140. package/lib/config/browserslistTargetHandler.js +141 -0
  141. package/lib/config/defaults.js +591 -41
  142. package/lib/config/defineConfig.js +31 -0
  143. package/lib/config/normalization.js +46 -1
  144. package/lib/config/target.js +200 -2
  145. package/lib/container/ContainerEntryDependency.js +2 -0
  146. package/lib/container/ContainerEntryModule.js +27 -14
  147. package/lib/container/ContainerEntryModuleFactory.js +1 -0
  148. package/lib/container/ContainerExposedDependency.js +6 -2
  149. package/lib/container/ContainerPlugin.js +2 -1
  150. package/lib/container/ContainerReferencePlugin.js +3 -2
  151. package/lib/container/FallbackDependency.js +9 -7
  152. package/lib/container/FallbackItemDependency.js +1 -0
  153. package/lib/container/FallbackModule.js +22 -9
  154. package/lib/container/FallbackModuleFactory.js +1 -0
  155. package/lib/container/ModuleFederationPlugin.js +12 -26
  156. package/lib/container/RemoteModule.js +33 -10
  157. package/lib/container/RemoteRuntimeModule.js +15 -12
  158. package/lib/container/RemoteToExternalDependency.js +1 -0
  159. package/lib/container/options.js +7 -0
  160. package/lib/css/CssGenerator.js +534 -272
  161. package/lib/css/CssInjectStyleRuntimeModule.js +86 -70
  162. package/lib/css/CssLoadingRuntimeModule.js +156 -77
  163. package/lib/{CssModule.js → css/CssModule.js} +72 -37
  164. package/lib/css/CssModulesPlugin.js +356 -204
  165. package/lib/css/CssParser.js +3452 -1950
  166. package/lib/css/syntax.js +4058 -0
  167. package/lib/debug/ProfilingPlugin.js +33 -2
  168. package/lib/deno/DenoTargetPlugin.js +41 -0
  169. package/lib/dependencies/AMDDefineDependency.js +29 -17
  170. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +19 -6
  171. package/lib/dependencies/AMDPlugin.js +6 -3
  172. package/lib/dependencies/AMDRequireArrayDependency.js +13 -11
  173. package/lib/dependencies/AMDRequireContextDependency.js +10 -11
  174. package/lib/dependencies/AMDRequireDependenciesBlock.js +1 -0
  175. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +28 -14
  176. package/lib/dependencies/AMDRequireDependency.js +28 -20
  177. package/lib/dependencies/AMDRequireItemDependency.js +1 -0
  178. package/lib/dependencies/AMDRuntimeModules.js +3 -0
  179. package/lib/dependencies/CachedConstDependency.js +9 -1
  180. package/lib/dependencies/CommonJsDependencyHelpers.js +104 -0
  181. package/lib/dependencies/CommonJsExportRequireDependency.js +138 -38
  182. package/lib/dependencies/CommonJsExportsDependency.js +74 -20
  183. package/lib/dependencies/CommonJsExportsParserPlugin.js +246 -15
  184. package/lib/dependencies/CommonJsFullRequireDependency.js +62 -27
  185. package/lib/dependencies/CommonJsImportsParserPlugin.js +187 -24
  186. package/lib/dependencies/CommonJsPlugin.js +7 -4
  187. package/lib/dependencies/CommonJsRequireContextDependency.js +13 -13
  188. package/lib/dependencies/CommonJsRequireDependency.js +135 -13
  189. package/lib/dependencies/CommonJsSelfReferenceDependency.js +60 -16
  190. package/lib/dependencies/ConstDependency.js +22 -12
  191. package/lib/dependencies/ContextDependency.js +13 -2
  192. package/lib/dependencies/ContextDependencyHelpers.js +7 -4
  193. package/lib/dependencies/ContextDependencyTemplateAsId.js +2 -1
  194. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +1 -0
  195. package/lib/dependencies/ContextElementDependency.js +27 -14
  196. package/lib/dependencies/CreateRequireParserPlugin.js +14 -7
  197. package/lib/dependencies/CreateScriptUrlDependency.js +9 -7
  198. package/lib/dependencies/CriticalDependencyWarning.js +3 -1
  199. package/lib/dependencies/CssIcssExportDependency.js +682 -368
  200. package/lib/dependencies/CssIcssImportDependency.js +62 -17
  201. package/lib/dependencies/CssIcssSymbolDependency.js +36 -17
  202. package/lib/dependencies/CssImportDependency.js +37 -1
  203. package/lib/dependencies/CssUrlDependency.js +87 -14
  204. package/lib/dependencies/DelegatedSourceDependency.js +1 -0
  205. package/lib/dependencies/DllEntryDependency.js +12 -13
  206. package/lib/dependencies/DynamicExports.js +5 -0
  207. package/lib/dependencies/EntryDependency.js +1 -0
  208. package/lib/dependencies/ExportBindingInitFragment.js +164 -0
  209. package/lib/dependencies/ExportsInfoDependency.js +18 -12
  210. package/lib/dependencies/ExternalModuleDependency.js +13 -5
  211. package/lib/dependencies/ExternalModuleInitFragment.js +10 -5
  212. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +19 -12
  213. package/lib/dependencies/HarmonyAcceptDependency.js +24 -26
  214. package/lib/dependencies/HarmonyAcceptImportDependency.js +2 -0
  215. package/lib/dependencies/HarmonyCompatibilityDependency.js +33 -14
  216. package/lib/dependencies/HarmonyDetectionParserPlugin.js +108 -30
  217. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +32 -2
  218. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +70 -33
  219. package/lib/dependencies/HarmonyExportExpressionDependency.js +140 -46
  220. package/lib/dependencies/HarmonyExportHeaderDependency.js +11 -9
  221. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +253 -37
  222. package/lib/dependencies/HarmonyExportInitFragment.js +28 -20
  223. package/lib/dependencies/HarmonyExportSpecifierDependency.js +88 -18
  224. package/lib/dependencies/HarmonyExports.js +6 -1
  225. package/lib/dependencies/HarmonyImportDependency.js +59 -3
  226. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +139 -146
  227. package/lib/dependencies/HarmonyImportGuard.js +426 -0
  228. package/lib/dependencies/HarmonyImportSideEffectDependency.js +22 -1
  229. package/lib/dependencies/HarmonyImportSpecifierDependency.js +136 -17
  230. package/lib/{HarmonyLinkingError.js → dependencies/HarmonyLinkingError.js} +6 -3
  231. package/lib/dependencies/HarmonyModulesPlugin.js +11 -1
  232. package/lib/dependencies/HarmonyTopLevelThisParserPlugin.js +2 -1
  233. package/lib/dependencies/HtmlEntryDependency.js +1295 -0
  234. package/lib/dependencies/HtmlInlineHtmlDependency.js +107 -0
  235. package/lib/dependencies/HtmlInlineScriptDependency.js +126 -0
  236. package/lib/dependencies/HtmlInlineStyleDependency.js +152 -0
  237. package/lib/dependencies/HtmlSourceDependency.js +172 -0
  238. package/lib/dependencies/ImportContextDependency.js +9 -9
  239. package/lib/dependencies/ImportDependency.js +92 -3
  240. package/lib/dependencies/ImportEagerDependency.js +2 -0
  241. package/lib/dependencies/ImportMetaContextDependency.js +1 -0
  242. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +35 -19
  243. package/lib/dependencies/ImportMetaContextPlugin.js +40 -8
  244. package/lib/dependencies/ImportMetaGlobDependency.js +81 -0
  245. package/lib/dependencies/ImportMetaGlobDependencyParserPlugin.js +78 -0
  246. package/lib/dependencies/ImportMetaGlobHelpers.js +660 -0
  247. package/lib/dependencies/ImportMetaHotAcceptDependency.js +2 -0
  248. package/lib/dependencies/ImportMetaHotDeclineDependency.js +2 -0
  249. package/lib/dependencies/ImportMetaPlugin.js +595 -209
  250. package/lib/dependencies/ImportMetaResolveDependency.js +90 -0
  251. package/lib/dependencies/ImportParserPlugin.js +114 -27
  252. package/lib/dependencies/ImportPhase.js +17 -11
  253. package/lib/dependencies/ImportPlugin.js +2 -1
  254. package/lib/dependencies/ImportWeakDependency.js +3 -0
  255. package/lib/dependencies/JsonExportsDependency.js +15 -10
  256. package/lib/dependencies/LoaderDependency.js +2 -0
  257. package/lib/dependencies/LoaderImportDependency.js +3 -0
  258. package/lib/dependencies/LoaderPlugin.js +9 -2
  259. package/lib/dependencies/LocalModule.js +15 -12
  260. package/lib/dependencies/LocalModuleDependency.js +15 -13
  261. package/lib/dependencies/LocalModulesHelpers.js +3 -0
  262. package/lib/dependencies/ModuleDecoratorDependency.js +16 -10
  263. package/lib/dependencies/ModuleDependency.js +14 -0
  264. package/lib/dependencies/ModuleDependencyTemplateAsId.js +1 -0
  265. package/lib/dependencies/ModuleDependencyTemplateAsRequireId.js +1 -0
  266. package/lib/dependencies/ModuleHotAcceptDependency.js +2 -0
  267. package/lib/dependencies/ModuleHotDeclineDependency.js +2 -0
  268. package/lib/dependencies/ModuleInitFragmentDependency.js +19 -11
  269. package/lib/dependencies/NullDependency.js +2 -0
  270. package/lib/dependencies/PrefetchDependency.js +1 -0
  271. package/lib/dependencies/ProvidedDependency.js +36 -27
  272. package/lib/dependencies/PureExpressionDependency.js +14 -10
  273. package/lib/dependencies/RequireContextDependency.js +1 -0
  274. package/lib/dependencies/RequireContextDependencyParserPlugin.js +2 -1
  275. package/lib/dependencies/RequireContextPlugin.js +2 -1
  276. package/lib/dependencies/RequireEnsureDependenciesBlock.js +1 -0
  277. package/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +4 -6
  278. package/lib/dependencies/RequireEnsureDependency.js +16 -13
  279. package/lib/dependencies/RequireEnsureItemDependency.js +1 -0
  280. package/lib/dependencies/RequireEnsurePlugin.js +2 -1
  281. package/lib/dependencies/RequireHeaderDependency.js +7 -4
  282. package/lib/dependencies/RequireIncludeDependency.js +2 -0
  283. package/lib/dependencies/RequireIncludeDependencyParserPlugin.js +11 -12
  284. package/lib/dependencies/RequireIncludePlugin.js +2 -1
  285. package/lib/{RequireJsStuffPlugin.js → dependencies/RequireJsStuffPlugin.js} +9 -8
  286. package/lib/dependencies/RequireResolveContextDependency.js +10 -11
  287. package/lib/dependencies/RequireResolveDependency.js +2 -0
  288. package/lib/dependencies/RequireResolveHeaderDependency.js +8 -5
  289. package/lib/dependencies/RuntimeRequirementsDependency.js +11 -8
  290. package/lib/dependencies/StaticExportsDependency.js +13 -10
  291. package/lib/dependencies/SystemPlugin.js +9 -6
  292. package/lib/dependencies/SystemRuntimeModule.js +1 -0
  293. package/lib/dependencies/TopLevelAwaitDependency.js +93 -0
  294. package/lib/dependencies/URLContextDependency.js +8 -7
  295. package/lib/dependencies/URLDependency.js +157 -33
  296. package/lib/dependencies/URLPlugin.js +2 -0
  297. package/lib/dependencies/UnsupportedDependency.js +12 -13
  298. package/lib/dependencies/WebAssemblyExportImportedDependency.js +15 -16
  299. package/lib/dependencies/WebAssemblyImportDependency.js +19 -18
  300. package/lib/dependencies/WebpackIsIncludedDependency.js +3 -0
  301. package/lib/dependencies/{WorkerPlugin.js → WorkerAndWorkletPlugin.js} +364 -114
  302. package/lib/dependencies/WorkerDependency.js +111 -27
  303. package/lib/dependencies/WorkletDependency.js +278 -0
  304. package/lib/dependencies/getFunctionExpression.js +1 -0
  305. package/lib/dependencies/processExportInfo.js +14 -11
  306. package/lib/{DelegatedModule.js → dll/DelegatedModule.js} +71 -44
  307. package/lib/{DelegatedModuleFactoryPlugin.js → dll/DelegatedModuleFactoryPlugin.js} +27 -4
  308. package/lib/{DelegatedPlugin.js → dll/DelegatedPlugin.js} +5 -3
  309. package/lib/{DllEntryPlugin.js → dll/DllEntryPlugin.js} +9 -5
  310. package/lib/{DllModule.js → dll/DllModule.js} +36 -24
  311. package/lib/{DllModuleFactory.js → dll/DllModuleFactory.js} +5 -4
  312. package/lib/{DllPlugin.js → dll/DllPlugin.js} +24 -6
  313. package/lib/{DllReferencePlugin.js → dll/DllReferencePlugin.js} +26 -18
  314. package/lib/{LibManifestPlugin.js → dll/LibManifestPlugin.js} +14 -10
  315. package/lib/electron/ElectronTargetPlugin.js +24 -5
  316. package/lib/{AbstractMethodError.js → errors/AbstractMethodError.js} +10 -1
  317. package/lib/{AsyncDependencyToInitialChunkError.js → errors/AsyncDependencyToInitialChunkError.js} +8 -3
  318. package/lib/errors/BuildCycleError.js +1 -1
  319. package/lib/{ChunkRenderError.js → errors/ChunkRenderError.js} +1 -1
  320. package/lib/{CodeGenerationError.js → errors/CodeGenerationError.js} +1 -1
  321. package/lib/{CommentCompilationWarning.js → errors/CommentCompilationWarning.js} +9 -3
  322. package/lib/{ConcurrentCompilationError.js → errors/ConcurrentCompilationError.js} +5 -2
  323. package/lib/{EnvironmentNotSupportAsyncWarning.js → errors/EnvironmentNotSupportAsyncWarning.js} +5 -5
  324. package/lib/{HookWebpackError.js → errors/HookWebpackError.js} +20 -16
  325. package/lib/{IgnoreErrorModuleFactory.js → errors/IgnoreErrorModuleFactory.js} +7 -4
  326. package/lib/{InvalidDependenciesModuleWarning.js → errors/InvalidDependenciesModuleWarning.js} +6 -3
  327. package/lib/errors/JSONParseError.js +115 -0
  328. package/lib/errors/LoaderLoadingError.js +20 -0
  329. package/lib/{ModuleBuildError.js → errors/ModuleBuildError.js} +22 -16
  330. package/lib/{ModuleDependencyError.js → errors/ModuleDependencyError.js} +10 -3
  331. package/lib/{ModuleDependencyWarning.js → errors/ModuleDependencyWarning.js} +13 -5
  332. package/lib/{ModuleError.js → errors/ModuleError.js} +10 -14
  333. package/lib/{ModuleHashingError.js → errors/ModuleHashingError.js} +5 -1
  334. package/lib/errors/ModuleNotFoundError.js +94 -0
  335. package/lib/errors/ModuleParseError.js +141 -0
  336. package/lib/{ModuleRestoreError.js → errors/ModuleRestoreError.js} +4 -1
  337. package/lib/{ModuleStoreError.js → errors/ModuleStoreError.js} +5 -1
  338. package/lib/{ModuleWarning.js → errors/ModuleWarning.js} +13 -14
  339. package/lib/{NodeStuffInWebError.js → errors/NodeStuffInWebError.js} +7 -5
  340. package/lib/errors/NonErrorEmittedError.js +30 -0
  341. package/lib/{UnhandledSchemeError.js → errors/UnhandledSchemeError.js} +9 -2
  342. package/lib/{UnsupportedFeatureWarning.js → errors/UnsupportedFeatureWarning.js} +4 -3
  343. package/lib/errors/WebpackError.js +84 -0
  344. package/lib/esm/ExportWebpackRequireRuntimeModule.js +2 -0
  345. package/lib/esm/ModuleChunkFormatPlugin.js +52 -15
  346. package/lib/esm/ModuleChunkLoadingPlugin.js +11 -3
  347. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +71 -49
  348. package/lib/hmr/HotModuleReplacement.runtime.js +175 -30
  349. package/lib/hmr/HotModuleReplacementRuntimeModule.js +8 -0
  350. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +173 -26
  351. package/lib/hmr/JavascriptHotModuleReplacementHelper.js +1 -0
  352. package/lib/hmr/LazyCompilationPlugin.js +154 -7
  353. package/lib/hmr/lazyCompilationBackend.js +34 -8
  354. package/lib/html/HtmlGenerator.js +1470 -0
  355. package/lib/html/HtmlModule.js +41 -0
  356. package/lib/html/HtmlModulesPlugin.js +1111 -0
  357. package/lib/html/HtmlParser.js +1970 -0
  358. package/lib/html/favicon.svg +1 -0
  359. package/lib/html/syntax.js +9020 -0
  360. package/lib/ids/ChunkModuleIdRangePlugin.js +3 -1
  361. package/lib/ids/DeterministicChunkIdsPlugin.js +3 -1
  362. package/lib/ids/DeterministicModuleIdsPlugin.js +3 -1
  363. package/lib/ids/HashedModuleIdsPlugin.js +2 -1
  364. package/lib/ids/IdHelpers.js +25 -2
  365. package/lib/ids/NamedChunkIdsPlugin.js +3 -1
  366. package/lib/ids/NamedModuleIdsPlugin.js +3 -1
  367. package/lib/ids/NaturalChunkIdsPlugin.js +1 -1
  368. package/lib/ids/NaturalModuleIdsPlugin.js +1 -1
  369. package/lib/ids/OccurrenceChunkIdsPlugin.js +2 -1
  370. package/lib/ids/OccurrenceModuleIdsPlugin.js +4 -1
  371. package/lib/ids/SyncModuleIdsPlugin.js +3 -1
  372. package/lib/index.js +66 -15
  373. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +5 -6
  374. package/lib/javascript/BasicEvaluatedExpression.js +370 -49
  375. package/lib/javascript/ChunkFormatHelpers.js +2 -1
  376. package/lib/javascript/ChunkHelpers.js +1 -0
  377. package/lib/javascript/CommonJsChunkFormatPlugin.js +1 -1
  378. package/lib/javascript/EnableChunkLoadingPlugin.js +6 -1
  379. package/lib/javascript/JavascriptGenerator.js +213 -51
  380. package/lib/javascript/JavascriptModule.js +54 -0
  381. package/lib/javascript/JavascriptModulesPlugin.js +579 -183
  382. package/lib/javascript/JavascriptParser.js +1289 -462
  383. package/lib/javascript/JavascriptParserHelpers.js +10 -7
  384. package/lib/javascript/StartupHelpers.js +5 -0
  385. package/lib/javascript/syntax.js +4380 -0
  386. package/lib/json/JsonData.js +5 -0
  387. package/lib/json/JsonGenerator.js +21 -0
  388. package/lib/json/JsonModule.js +40 -0
  389. package/lib/json/JsonModulesPlugin.js +8 -1
  390. package/lib/json/JsonParser.js +18 -27
  391. package/lib/library/AbstractLibraryPlugin.js +17 -2
  392. package/lib/library/AmdLibraryPlugin.js +8 -0
  393. package/lib/library/AssignLibraryPlugin.js +21 -3
  394. package/lib/library/EnableLibraryPlugin.js +8 -2
  395. package/lib/library/ExportPropertyLibraryPlugin.js +10 -0
  396. package/lib/{FalseIIFEUmdWarning.js → library/FalseIIFEUmdWarning.js} +2 -1
  397. package/lib/library/JsonpLibraryPlugin.js +8 -0
  398. package/lib/library/ModuleLibraryPlugin.js +154 -7
  399. package/lib/library/SystemLibraryPlugin.js +11 -3
  400. package/lib/library/UmdLibraryPlugin.js +16 -0
  401. package/lib/loaders/LoaderRunner.js +714 -0
  402. package/lib/loaders/loadLoader.js +100 -0
  403. package/lib/logging/Logger.js +17 -0
  404. package/lib/logging/createConsoleLogger.js +7 -0
  405. package/lib/logging/runtime.js +2 -0
  406. package/lib/logging/truncateArgs.js +2 -0
  407. package/lib/node/CommonJsChunkLoadingPlugin.js +5 -1
  408. package/lib/node/NodeEnvironmentPlugin.js +7 -3
  409. package/lib/node/NodeSourcePlugin.js +1 -1
  410. package/lib/node/NodeTargetPlugin.js +4 -63
  411. package/lib/node/NodeTemplatePlugin.js +3 -1
  412. package/lib/node/NodeWatchFileSystem.js +40 -22
  413. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +13 -9
  414. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +23 -1
  415. package/lib/node/ReadFileCompileWasmPlugin.js +18 -1
  416. package/lib/node/RequireChunkLoadingRuntimeModule.js +21 -16
  417. package/lib/node/nodeBuiltins.js +80 -0
  418. package/lib/node/nodeConsole.js +116 -64
  419. package/lib/optimize/AggressiveMergingPlugin.js +3 -1
  420. package/lib/optimize/AggressiveSplittingPlugin.js +6 -1
  421. package/lib/optimize/ConcatenatedModule.js +585 -116
  422. package/lib/optimize/ConstExportsPlugin.js +211 -0
  423. package/lib/optimize/EnsureChunkConditionsPlugin.js +2 -1
  424. package/lib/optimize/FlagIncludedChunksPlugin.js +15 -4
  425. package/lib/optimize/InlineExports.js +178 -0
  426. package/lib/optimize/InnerGraph.js +374 -262
  427. package/lib/optimize/InnerGraphPlugin.js +246 -117
  428. package/lib/optimize/LimitChunkCountPlugin.js +9 -0
  429. package/lib/optimize/MangleExportsPlugin.js +5 -1
  430. package/lib/optimize/MergeDuplicateChunksPlugin.js +2 -0
  431. package/lib/optimize/MinChunkSizePlugin.js +2 -1
  432. package/lib/optimize/MinMaxSizeWarning.js +5 -4
  433. package/lib/optimize/ModuleConcatenationPlugin.js +159 -34
  434. package/lib/optimize/RealContentHashPlugin.js +125 -50
  435. package/lib/optimize/RemoveEmptyChunksPlugin.js +2 -1
  436. package/lib/optimize/RemoveParentModulesPlugin.js +3 -1
  437. package/lib/optimize/RuntimeChunkPlugin.js +2 -1
  438. package/lib/optimize/SideEffectsFlagPlugin.js +381 -55
  439. package/lib/optimize/SplitChunksPlugin.js +54 -6
  440. package/lib/performance/AssetsOverSizeLimitWarning.js +3 -2
  441. package/lib/performance/EntrypointsOverSizeLimitWarning.js +3 -2
  442. package/lib/performance/NoAsyncChunksWarning.js +5 -3
  443. package/lib/performance/SizeLimitsPlugin.js +8 -2
  444. package/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +1 -0
  445. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +21 -0
  446. package/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +1 -0
  447. package/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +5 -1
  448. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +25 -13
  449. package/lib/prefetch/ResourceHintPlugin.js +663 -0
  450. package/lib/prefetch/ResourceHintRuntimeModule.js +149 -0
  451. package/lib/prefetch/StartupAssetHintRuntimeModule.js +210 -0
  452. package/lib/prefetch/parseResourceHintOptions.js +103 -0
  453. package/lib/rules/BasicEffectRulePlugin.js +3 -0
  454. package/lib/rules/BasicMatcherRulePlugin.js +3 -0
  455. package/lib/rules/ObjectMatcherRulePlugin.js +3 -0
  456. package/lib/rules/RuleSetCompiler.js +132 -0
  457. package/lib/rules/UseEffectRulePlugin.js +10 -3
  458. package/lib/runtime/AsyncModuleGeneratorRuntimeModule.js +56 -0
  459. package/lib/runtime/AsyncModuleRuntimeModule.js +52 -33
  460. package/lib/runtime/AutoPublicPathRuntimeModule.js +22 -9
  461. package/lib/runtime/BaseUriRuntimeModule.js +1 -0
  462. package/lib/runtime/ChunkNameRuntimeModule.js +1 -0
  463. package/lib/runtime/CommonJsWrapRuntimeModule.js +37 -0
  464. package/lib/runtime/CompatGetDefaultExportRuntimeModule.js +2 -1
  465. package/lib/runtime/CompatRuntimeModule.js +2 -0
  466. package/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +7 -4
  467. package/lib/runtime/CreateScriptRuntimeModule.js +1 -0
  468. package/lib/runtime/CreateScriptUrlRuntimeModule.js +1 -0
  469. package/lib/runtime/DefinePropertyGettersRuntimeModule.js +34 -4
  470. package/lib/runtime/EnsureChunkRuntimeModule.js +1 -0
  471. package/lib/runtime/GetChunkFilenameRuntimeModule.js +88 -8
  472. package/lib/runtime/GetFullHashRuntimeModule.js +1 -0
  473. package/lib/runtime/GetMainFilenameRuntimeModule.js +1 -0
  474. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +2 -1
  475. package/lib/runtime/GetWorkletBootstrapRuntimeModule.js +59 -0
  476. package/lib/runtime/GlobalRuntimeModule.js +1 -0
  477. package/lib/runtime/HasOwnPropertyRuntimeModule.js +2 -1
  478. package/lib/runtime/HelperRuntimeModule.js +5 -0
  479. package/lib/runtime/LoadScriptRuntimeModule.js +28 -37
  480. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +354 -37
  481. package/lib/runtime/MakeNamespaceObjectRuntimeModule.js +2 -1
  482. package/lib/runtime/NonceRuntimeModule.js +1 -0
  483. package/lib/runtime/OnChunksLoadedRuntimeModule.js +5 -4
  484. package/lib/runtime/PublicPathRuntimeModule.js +1 -0
  485. package/lib/runtime/RelativeUrlRuntimeModule.js +4 -2
  486. package/lib/runtime/RuntimeIdRuntimeModule.js +1 -0
  487. package/lib/runtime/SetAnonymousDefaultNameRuntimeModule.js +38 -0
  488. package/lib/runtime/StartupChunkDependenciesPlugin.js +13 -1
  489. package/lib/runtime/StartupChunkDependenciesRuntimeModule.js +2 -1
  490. package/lib/runtime/StartupEntrypointRuntimeModule.js +5 -3
  491. package/lib/runtime/SystemContextRuntimeModule.js +1 -0
  492. package/lib/runtime/ToBinaryRuntimeModule.js +1 -0
  493. package/lib/runtime/WorkerRuntimeModule.js +33 -0
  494. package/lib/schemes/DataUriPlugin.js +14 -2
  495. package/lib/schemes/FileUriPlugin.js +1 -1
  496. package/lib/schemes/HttpUriPlugin.js +86 -4
  497. package/lib/schemes/VirtualUrlPlugin.js +8 -4
  498. package/lib/serialization/AggregateErrorSerializer.js +9 -6
  499. package/lib/serialization/ArraySerializer.js +6 -8
  500. package/lib/serialization/BinaryMiddleware.js +552 -463
  501. package/lib/serialization/DateObjectSerializer.js +4 -2
  502. package/lib/serialization/ErrorObjectSerializer.js +10 -6
  503. package/lib/serialization/FileMiddleware.js +50 -3
  504. package/lib/serialization/MapObjectSerializer.js +7 -9
  505. package/lib/serialization/NullPrototypeObjectSerializer.js +9 -9
  506. package/lib/serialization/ObjectMiddleware.js +73 -13
  507. package/lib/serialization/PlainObjectSerializer.js +16 -8
  508. package/lib/serialization/RegExpObjectSerializer.js +4 -2
  509. package/lib/serialization/Serializer.js +6 -0
  510. package/lib/serialization/SerializerMiddleware.js +14 -2
  511. package/lib/serialization/SetObjectSerializer.js +6 -8
  512. package/lib/serialization/SingleItemMiddleware.js +3 -0
  513. package/lib/sharing/ConsumeSharedFallbackDependency.js +1 -0
  514. package/lib/sharing/ConsumeSharedModule.js +21 -7
  515. package/lib/sharing/ConsumeSharedPlugin.js +11 -11
  516. package/lib/sharing/ConsumeSharedRuntimeModule.js +55 -45
  517. package/lib/sharing/ProvideForSharedDependency.js +1 -0
  518. package/lib/sharing/ProvideSharedDependency.js +34 -15
  519. package/lib/sharing/ProvideSharedModule.js +42 -12
  520. package/lib/sharing/ProvideSharedModuleFactory.js +1 -0
  521. package/lib/sharing/ProvideSharedPlugin.js +13 -8
  522. package/lib/sharing/SharePlugin.js +5 -1
  523. package/lib/sharing/ShareRuntimeModule.js +19 -16
  524. package/lib/sharing/resolveMatchedConfigs.js +6 -2
  525. package/lib/sharing/utils.js +9 -1
  526. package/lib/stats/DefaultStatsFactoryPlugin.js +94 -12
  527. package/lib/stats/DefaultStatsPresetPlugin.js +14 -2
  528. package/lib/stats/DefaultStatsPrinterPlugin.js +64 -18
  529. package/lib/stats/StatsFactory.js +39 -18
  530. package/lib/stats/StatsPrinter.js +16 -2
  531. package/lib/typescript/TypeScriptPlugin.js +210 -0
  532. package/lib/url/URLParserPlugin.js +111 -23
  533. package/lib/util/ArrayHelpers.js +1 -0
  534. package/lib/util/ArrayQueue.js +10 -5
  535. package/lib/util/AsyncQueue.js +154 -74
  536. package/lib/util/Hash.js +2 -2
  537. package/lib/util/IterableHelpers.js +3 -0
  538. package/lib/util/LazyBucketSortedSet.js +26 -0
  539. package/lib/util/LazySet.js +45 -4
  540. package/lib/util/LocConverter.js +64 -0
  541. package/lib/util/ParallelismFactorCalculator.js +1 -0
  542. package/lib/util/Queue.js +6 -3
  543. package/lib/util/Semaphore.js +15 -1
  544. package/lib/util/SetHelpers.js +4 -1
  545. package/lib/util/SortableSet.js +7 -1
  546. package/lib/util/SourceProcessor.js +119 -0
  547. package/lib/util/StackedCacheMap.js +20 -3
  548. package/lib/util/StackedMap.js +162 -43
  549. package/lib/util/StringXor.js +1 -1
  550. package/lib/util/TupleQueue.js +7 -3
  551. package/lib/util/TupleSet.js +14 -0
  552. package/lib/util/URLAbsoluteSpecifier.js +1 -0
  553. package/lib/util/WeakTupleMap.js +60 -1
  554. package/lib/util/binarySearchBounds.js +3 -2
  555. package/lib/util/chainedImports.js +3 -3
  556. package/lib/util/cleverMerge.js +19 -2
  557. package/lib/util/comparators.js +35 -4
  558. package/lib/util/compileBooleanMatcher.js +9 -0
  559. package/lib/util/concatenate.js +80 -24
  560. package/lib/util/conventions.js +46 -1
  561. package/lib/util/createHash.js +0 -1
  562. package/lib/util/createHooksRegistry.js +43 -0
  563. package/lib/util/createMappings.js +118 -0
  564. package/lib/util/dataURL.js +3 -2
  565. package/lib/util/deprecation.js +19 -0
  566. package/lib/util/deterministicGrouping.js +46 -17
  567. package/lib/util/extractSourceMap.js +2 -1
  568. package/lib/util/extractUrlAndGlobal.js +1 -0
  569. package/lib/util/findGraphRoots.js +7 -0
  570. package/lib/{formatLocation.js → util/formatLocation.js} +4 -2
  571. package/lib/{SizeFormatHelpers.js → util/formatSize.js} +10 -3
  572. package/lib/util/fs.js +87 -14
  573. package/lib/util/generateDebugId.js +1 -0
  574. package/lib/util/globUtils.js +710 -0
  575. package/lib/util/hash/BatchedHash.js +1 -0
  576. package/lib/util/hash/BulkUpdateHash.js +1 -0
  577. package/lib/util/hash/DebugHash.js +1 -0
  578. package/lib/util/hash/hash-digest.js +32 -15
  579. package/lib/util/hash/md4.js +1 -1
  580. package/lib/util/hash/wasm-hash.js +5 -0
  581. package/lib/util/hash/xxhash64.js +1 -1
  582. package/lib/util/identifier.js +97 -6
  583. package/lib/util/implicitTypeLoaderFallback.js +62 -0
  584. package/lib/util/internalSerializables.js +102 -60
  585. package/lib/util/magicComment.js +149 -7
  586. package/lib/util/makeSerializable.js +7 -0
  587. package/lib/util/memoize.js +2 -0
  588. package/lib/util/mimeTypes.js +176 -0
  589. package/lib/util/nonNumericOnlyHash.js +31 -1
  590. package/lib/util/numberHash.js +2 -2
  591. package/lib/util/parseJson.js +41 -0
  592. package/lib/util/processAsyncTree.js +8 -0
  593. package/lib/util/property.js +9 -2
  594. package/lib/util/publicPathPlaceholder.js +64 -0
  595. package/lib/util/registerExternalSerializer.js +24 -4
  596. package/lib/util/removeBOM.js +1 -0
  597. package/lib/util/runtime.js +32 -0
  598. package/lib/util/semver.js +15 -0
  599. package/lib/util/serialization.js +2 -0
  600. package/lib/util/smartGrouping.js +8 -0
  601. package/lib/util/source.js +23 -0
  602. package/lib/util/topologicalSort.js +69 -0
  603. package/lib/validateSchema.js +1 -0
  604. package/lib/wasm/EnableWasmLoadingPlugin.js +15 -1
  605. package/lib/wasm-async/AsyncWasmCompileRuntimeModule.js +25 -18
  606. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +34 -22
  607. package/lib/wasm-async/AsyncWasmModule.js +77 -0
  608. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +6 -0
  609. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +6 -1
  610. package/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js +22 -126
  611. package/lib/wasm-async/AsyncWebAssemblyParser.js +3 -2
  612. package/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js +13 -2
  613. package/lib/wasm-sync/SyncWasmModule.js +39 -0
  614. package/lib/wasm-sync/UnsupportedWebAssemblyFeatureError.js +7 -3
  615. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +86 -19
  616. package/lib/wasm-sync/WasmFinalizeExportsPlugin.js +4 -3
  617. package/lib/wasm-sync/WebAssemblyGenerator.js +27 -1
  618. package/lib/wasm-sync/WebAssemblyInInitialChunkError.js +9 -3
  619. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +4 -0
  620. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +20 -1
  621. package/lib/wasm-sync/WebAssemblyParser.js +9 -3
  622. package/lib/wasm-sync/WebAssemblyUtils.js +2 -0
  623. package/lib/web/FetchCompileAsyncWasmPlugin.js +29 -1
  624. package/lib/web/FetchCompileWasmPlugin.js +27 -1
  625. package/lib/web/JsonpChunkLoadingPlugin.js +11 -1
  626. package/lib/web/JsonpChunkLoadingRuntimeModule.js +58 -64
  627. package/lib/web/JsonpTemplatePlugin.js +2 -1
  628. package/lib/webpack.js +78 -1
  629. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +10 -1
  630. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +15 -10
  631. package/lib/webworker/WebWorkerTemplatePlugin.js +1 -1
  632. package/module.d.ts +21 -0
  633. package/package.json +79 -77
  634. package/schemas/WebpackOptions.check.js +1 -1
  635. package/schemas/WebpackOptions.json +1117 -79
  636. package/schemas/plugins/{DllPlugin.check.d.ts → HtmlGeneratorOptions.check.d.ts} +1 -1
  637. package/schemas/plugins/HtmlGeneratorOptions.check.js +6 -0
  638. package/schemas/plugins/HtmlGeneratorOptions.json +3 -0
  639. package/schemas/plugins/{DllReferencePlugin.check.d.ts → HtmlParserOptions.check.d.ts} +1 -1
  640. package/schemas/plugins/HtmlParserOptions.check.js +6 -0
  641. package/schemas/plugins/HtmlParserOptions.json +3 -0
  642. package/schemas/plugins/ProgressPlugin.check.js +1 -1
  643. package/schemas/plugins/ProgressPlugin.json +38 -0
  644. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  645. package/schemas/plugins/container/ContainerReferencePlugin.json +2 -0
  646. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  647. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  648. package/schemas/plugins/container/ModuleFederationPlugin.json +2 -0
  649. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.d.ts +7 -0
  650. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.js +6 -0
  651. package/schemas/plugins/css/CssAutoOrModuleParserOptions.json +3 -0
  652. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  653. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  654. package/schemas/plugins/dll/DllPlugin.check.d.ts +7 -0
  655. package/schemas/plugins/dll/DllReferencePlugin.check.d.ts +7 -0
  656. package/types.d.ts +8608 -1159
  657. package/lib/CaseSensitiveModulesWarning.js +0 -72
  658. package/lib/GraphHelpers.js +0 -46
  659. package/lib/ModuleParseError.js +0 -125
  660. package/lib/NoModeWarning.js +0 -23
  661. package/lib/css/CssMergeStyleSheetsRuntimeModule.js +0 -56
  662. package/lib/css/walkCssTokens.js +0 -1843
  663. package/lib/util/AppendOnlyStackedSet.js +0 -78
  664. /package/schemas/plugins/{DllPlugin.check.js → dll/DllPlugin.check.js} +0 -0
  665. /package/schemas/plugins/{DllPlugin.json → dll/DllPlugin.json} +0 -0
  666. /package/schemas/plugins/{DllReferencePlugin.check.js → dll/DllReferencePlugin.check.js} +0 -0
  667. /package/schemas/plugins/{DllReferencePlugin.json → dll/DllReferencePlugin.json} +0 -0
@@ -0,0 +1,1470 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ */
4
+
5
+ "use strict";
6
+
7
+ const { RawSource, ReplaceSource } = require("webpack-sources");
8
+ const ConcatenationScope = require("../ConcatenationScope");
9
+ const Generator = require("../Generator");
10
+ const {
11
+ HTML_TYPE,
12
+ JAVASCRIPT_TYPE,
13
+ JAVASCRIPT_TYPES
14
+ } = require("../ModuleSourceTypeConstants");
15
+ const RuntimeGlobals = require("../RuntimeGlobals");
16
+ const Template = require("../Template");
17
+ const WebpackError = require("../errors/WebpackError");
18
+ const { getUndoPath } = require("../util/identifier");
19
+ const memoize = require("../util/memoize");
20
+ const { PUBLIC_PATH_AUTO } = require("../util/publicPathPlaceholder");
21
+ const { NodeType, SourceProcessor, escapeAttribute } = require("./syntax");
22
+
23
+ // Lazy so loading the HTML generator doesn't pull in the whole CSS pipeline.
24
+ const getCssModulesPlugin = memoize(() => require("../css/CssModulesPlugin"));
25
+ // The CSS tokenizer, used to locate `url(...)` when rebasing inlined stylesheets.
26
+ const getCssSyntax = memoize(() => require("../css/syntax"));
27
+ // node's crypto — real SHA hashes for Content-Security-Policy source lists
28
+ // (the wasm hashes are xxhash, unusable for CSP), loaded only when CSP is on.
29
+ const getCreateNodeHash = memoize(() => require("crypto").createHash);
30
+
31
+ // HTML void elements — serialized without a closing tag when a tag descriptor
32
+ // (`output.html` `injectTags`) doesn't say otherwise.
33
+ const VOID_TAGS = new Set([
34
+ "area",
35
+ "base",
36
+ "br",
37
+ "col",
38
+ "embed",
39
+ "hr",
40
+ "img",
41
+ "input",
42
+ "link",
43
+ "meta",
44
+ "param",
45
+ "source",
46
+ "track",
47
+ "wbr"
48
+ ]);
49
+
50
+ /**
51
+ * Serializes an attribute map: `true` → bare attribute, `false`/`undefined`/
52
+ * `null` → omitted, else a quoted (escaped) value.
53
+ * @param {Record<string, string | boolean | undefined> | undefined} attrs attributes
54
+ * @returns {string} the leading-space-prefixed attribute string
55
+ */
56
+ const serializeAttrs = (attrs) => {
57
+ let out = "";
58
+ if (attrs) {
59
+ for (const name of Object.keys(attrs)) {
60
+ const value = attrs[name];
61
+ if (value === false || value === undefined || value === null) continue;
62
+ out +=
63
+ value === true
64
+ ? ` ${name}`
65
+ : ` ${name}="${escapeAttribute(`${value}`)}"`;
66
+ }
67
+ }
68
+ return out;
69
+ };
70
+
71
+ /**
72
+ * Serializes one tag descriptor. `attrs` values: `true` → bare attribute,
73
+ * `false`/`undefined` → omitted, else a quoted (escaped) value.
74
+ * @param {HtmlTagDescriptor} tag the descriptor
75
+ * @returns {string} the tag's HTML
76
+ */
77
+ const serializeTag = (tag) => {
78
+ const attrs = serializeAttrs(tag.attrs);
79
+ const isVoid =
80
+ tag.voidTag !== undefined
81
+ ? tag.voidTag
82
+ : VOID_TAGS.has(tag.tag.toLowerCase());
83
+ return isVoid
84
+ ? `<${tag.tag}${attrs}>`
85
+ : `<${tag.tag}${attrs}>${tag.children || ""}</${tag.tag}>`;
86
+ };
87
+
88
+ /**
89
+ * Canonical string of an attribute map (present keys, sorted) — used to detect
90
+ * whether an `transformTags` plugin changed a tag, so unchanged tags stay untouched.
91
+ * `false`/`undefined`/`null` count as absent.
92
+ * @param {Record<string, string | boolean | undefined>} attrs attributes
93
+ * @returns {string} a comparable snapshot
94
+ */
95
+ const snapshotAttrs = (attrs) =>
96
+ JSON.stringify(
97
+ Object.keys(attrs)
98
+ .filter((name) => {
99
+ const value = attrs[name];
100
+ return value !== false && value !== undefined && value !== null;
101
+ })
102
+ .sort()
103
+ .map((name) => [name, attrs[name]])
104
+ );
105
+
106
+ /**
107
+ * Whether an attribute renders (present and not `false`/`undefined`/`null`).
108
+ * @param {Record<string, string | boolean | undefined>} attrs attributes
109
+ * @param {string} name attribute name
110
+ * @returns {boolean} true if it renders
111
+ */
112
+ const attrPresent = (attrs, name) => {
113
+ const value = attrs[name];
114
+ return value !== undefined && value !== false && value !== null;
115
+ };
116
+
117
+ /**
118
+ * Whether a `<meta>`'s attributes declare a Content-Security-Policy (case-
119
+ * insensitive `http-equiv`), used to detect an author-declared CSP.
120
+ * @param {Record<string, string | boolean | undefined>} attrs attributes
121
+ * @returns {boolean} true if it is a CSP meta
122
+ */
123
+ const metaIsCsp = (attrs) => {
124
+ for (const name of Object.keys(attrs)) {
125
+ const value = attrs[name];
126
+ if (
127
+ name.toLowerCase() === "http-equiv" &&
128
+ typeof value === "string" &&
129
+ value.trim().toLowerCase() === "content-security-policy"
130
+ ) {
131
+ return true;
132
+ }
133
+ }
134
+ return false;
135
+ };
136
+
137
+ /** @typedef {import("webpack-sources").Source} Source */
138
+ /** @typedef {import("../../declarations/WebpackOptions").HtmlGeneratorOptions} HtmlGeneratorOptions */
139
+ /** @typedef {import("../../declarations/WebpackOptions").OutputHtmlOptions["csp"]} CspOption */
140
+ /** @typedef {import("./HtmlModulesPlugin").HtmlTagDescriptor} HtmlTagDescriptor */
141
+ /** @typedef {import("./HtmlModulesPlugin").HtmlMutableTag} HtmlMutableTag */
142
+ /** @typedef {"head" | "body"} HtmlTagLocation */
143
+ /**
144
+ * @typedef {object} HtmlTagSpan
145
+ * @property {number} start opening `<` offset
146
+ * @property {number} openEnd offset just after the opening `>`
147
+ * @property {number} end offset just after the whole element
148
+ * @property {HtmlTagLocation} location the `<head>`/`<body>` region it sits in
149
+ * @property {number} nameEnd offset after the tag name (nonce insertion point), `-1` for non-`<script>`/`<style>`
150
+ * @property {number} contentEnd raw-text body end for `<script>`/`<style>`, `-1` otherwise
151
+ * @property {boolean} selfClosing whether the element is self-closing
152
+ */
153
+ /** @typedef {{ headOpen: number, headEnd: number, bodyOpen: number, bodyEnd: number }} HtmlAnchors */
154
+ /** @typedef {{ tags: HtmlMutableTag[], spans: (HtmlTagSpan | null)[], originals: (string | null)[], descriptors: (HtmlTagDescriptor | null)[], anchors: HtmlAnchors }} HtmlModel */
155
+ /** @typedef {import("../Chunk")} Chunk */
156
+ /** @typedef {import("../Compilation")} Compilation */
157
+ /** @typedef {boolean | string[] | ((asset: { chunk: Chunk, filename: string }) => string[] | false)} HtmlIntegrity */
158
+ /** @typedef {import("../Compilation").DependencyConstructor} DependencyConstructor */
159
+ /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
160
+ /** @typedef {import("../Dependency")} Dependency */
161
+ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
162
+ /** @typedef {import("../Generator").GenerateContext} GenerateContext */
163
+ /** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
164
+ /** @typedef {import("../Module").SourceType} SourceType */
165
+ /** @typedef {import("../Module").SourceTypes} SourceTypes */
166
+ /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
167
+ /** @typedef {import("../ModuleGraph")} ModuleGraph */
168
+ /** @typedef {import("../NormalModule")} NormalModule */
169
+ /** @typedef {import("./HtmlModule").HtmlModuleBuildInfo} HtmlModuleBuildInfo */
170
+ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
171
+ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
172
+ /** @typedef {import("../util/Hash")} Hash */
173
+ /**
174
+ * @template T
175
+ * @typedef {import("../InitFragment")<T>} InitFragment
176
+ */
177
+
178
+ /**
179
+ * @type {ReadonlySet<"javascript" | "html">}
180
+ */
181
+ const JAVASCRIPT_AND_HTML_TYPES = new Set([JAVASCRIPT_TYPE, HTML_TYPE]);
182
+
183
+ /** @type {WeakMap<Compilation, Map<string, Chunk>>} */
184
+ const chunksByIdCache = new WeakMap();
185
+
186
+ /**
187
+ * `String(chunk.id)` → chunk lookup, memoized per compilation and shared by the
188
+ * URL and integrity sentinel resolvers.
189
+ * @param {Compilation} compilation compilation
190
+ * @returns {Map<string, Chunk>} chunks keyed by stringified id
191
+ */
192
+ const getChunksById = (compilation) => {
193
+ let chunksById = chunksByIdCache.get(compilation);
194
+ if (chunksById === undefined) {
195
+ chunksById = new Map();
196
+ for (const chunk of compilation.chunks) {
197
+ chunksById.set(String(chunk.id), chunk);
198
+ }
199
+ chunksByIdCache.set(compilation, chunksById);
200
+ }
201
+ return chunksById;
202
+ };
203
+
204
+ // Hoisted so `resolveChunkUrlSentinels` (per chunk × module) doesn't allocate a
205
+ // fresh `RegExp` each call. `String#replace` resets `lastIndex`, so sharing the
206
+ // global-flag instance is safe under these synchronous, non-reentrant calls.
207
+ const CHUNK_URL_SENTINEL_REGEXP =
208
+ /__WEBPACK_HTML_CHUNK_URL__([0-9a-f]+)__([a-z]+)__END__/g;
209
+
210
+ // Sentinel for a linked HTML page (a tag mapped to the `html` source type);
211
+ // resolved to the page's emitted filename once it has been built. Keyed by the
212
+ // linked module's id so it shares the `<iframe srcdoc>` nested-module mechanism.
213
+ const HTML_PAGE_URL_SENTINEL_REGEXP =
214
+ /__WEBPACK_HTML_PAGE_URL__([0-9a-f]+)__END__/g;
215
+
216
+ // Sentinel for a URL-referenced asset (font/image/…) emitted into a resource-hint
217
+ // `<link>` tag by `HtmlEntryDependency`; resolved to the asset's real emitted
218
+ // URL from its codegen data during `HtmlModulesPlugin` render. Deferred because
219
+ // HtmlEntry deps run *while* the HTML module is being codegen'd — the asset
220
+ // module's own codegen might not have completed yet. Keyed by the asset
221
+ // module's identifier, hex-encoded so any character in it is safe in a URL.
222
+ const ASSET_URL_SENTINEL_REGEXP =
223
+ /__WEBPACK_HTML_ASSET_URL__([0-9a-f]+)__END__/g;
224
+
225
+ // Matches the whole ` integrity="<sentinel>"` so the attribute can be dropped
226
+ // entirely when the per-asset `integrity` function returns `false`.
227
+ const INTEGRITY_SENTINEL_REGEXP =
228
+ / integrity="__WEBPACK_HTML_INTEGRITY__([0-9a-f]+)__([a-z]+)__END__"/g;
229
+
230
+ // Same attribute, but tolerant of the `\"` escaping the surrounding quotes get
231
+ // when the HTML lives inside a JS string literal — used only to strip it there.
232
+ const INTEGRITY_SENTINEL_STRIP_REGEXP =
233
+ / integrity=\\?"__WEBPACK_HTML_INTEGRITY__[0-9a-f]+__[a-z]+__END__\\?"/g;
234
+
235
+ // The trailing `(?:__<hash>)?` is the inlined chunk's content hash, embedded by
236
+ // `embedInlineChunkHashes` so the host HTML's bytes (and its `[contenthash]`,
237
+ // incl. RealContentHashPlugin's recompute) change with the inlined content; the
238
+ // resolver ignores it.
239
+ const INLINE_SENTINEL_REGEXP =
240
+ /__WEBPACK_HTML_INLINE__([0-9a-f]+)__([a-z]+)(?:__[0-9a-f]+)?__END__/g;
241
+
242
+ /**
243
+ * Rewrite relative `url(...)` references in a CSS chunk so they still resolve
244
+ * after the styles are inlined into the HTML document (which may sit in a
245
+ * different directory). webpack emits every url as `undoPath(cssFile) + <asset
246
+ * path from the output root>`, so swapping the CSS file's undo prefix for the
247
+ * HTML file's re-bases them — no path math. Uses the CSS tokenizer to find url
248
+ * tokens exactly (never a `url(` inside a comment or string); webpack emits
249
+ * unquoted url()s (special characters `\`-escaped), so only that shape occurs.
250
+ * @param {string} css the CSS content
251
+ * @param {string} fromFile the CSS file's output name
252
+ * @param {string} toFile the HTML file's output name
253
+ * @param {string} outputPath the compilation output path
254
+ * @returns {string} the CSS with rebased urls
255
+ */
256
+ const rebaseCssUrls = (css, fromFile, toFile, outputPath) => {
257
+ const fromUndo = getUndoPath(fromFile, outputPath, false);
258
+ const toUndo = getUndoPath(toFile, outputPath, false);
259
+ if (fromUndo === toUndo) return css;
260
+ const { readToken, TT_URL } = getCssSyntax();
261
+ const token = {
262
+ type: 0,
263
+ start: 0,
264
+ end: 0,
265
+ isId: false,
266
+ contentStart: 0,
267
+ contentEnd: 0,
268
+ unitStart: 0
269
+ };
270
+ let pos = 0;
271
+ let last = 0;
272
+ let out = "";
273
+ while (readToken(css, pos, token) !== undefined) {
274
+ pos = token.end;
275
+ if (token.type !== TT_URL) continue;
276
+ const url = css.slice(token.contentStart, token.contentEnd);
277
+ // Rebase only the undo-path-relative urls; a root-relative (`/`), fragment
278
+ // (`#`) or scheme (`data:`, …, a `:` before any `/`) url is absolute.
279
+ const colon = url.indexOf(":");
280
+ const slash = url.indexOf("/");
281
+ if (
282
+ !url.startsWith(fromUndo) ||
283
+ url[0] === "/" ||
284
+ url[0] === "#" ||
285
+ (colon !== -1 && (slash === -1 || colon < slash))
286
+ ) {
287
+ continue;
288
+ }
289
+ out += `${css.slice(last, token.contentStart)}${toUndo}${url.slice(
290
+ fromUndo.length
291
+ )}`;
292
+ last = token.contentEnd;
293
+ }
294
+ return last === 0 ? css : out + css.slice(last);
295
+ };
296
+
297
+ class HtmlGenerator extends Generator {
298
+ /**
299
+ * Emit a sentinel for a chunk URL that can't be resolved at code-gen time
300
+ * (chunk hashes aren't computed yet); `resolveChunkUrlSentinels` swaps it
301
+ * for `${PUBLIC_PATH_AUTO}<chunkFilename>` once they are.
302
+ * @param {Chunk} chunk chunk
303
+ * @param {"javascript" | "css"} contentHashType which chunk content hash slot the resolved URL should reference
304
+ * @returns {string} sentinel
305
+ */
306
+ static makeChunkUrlSentinel(chunk, contentHashType) {
307
+ const hexId = Buffer.from(String(chunk.id), "utf8").toString("hex");
308
+ return `__WEBPACK_HTML_CHUNK_URL__${hexId}__${contentHashType}__END__`;
309
+ }
310
+
311
+ /**
312
+ * Replace every `makeChunkUrlSentinel` sentinel in `content` with
313
+ * `${PUBLIC_PATH_AUTO}<chunkFilename>`. Must run after
314
+ * `Compilation#createHash()` so `[contenthash]` resolves.
315
+ * @param {string} content content
316
+ * @param {Compilation} compilation compilation
317
+ * @returns {string} resolved content
318
+ */
319
+ static resolveChunkUrlSentinels(content, compilation) {
320
+ if (!content.includes("__WEBPACK_HTML_CHUNK_URL__")) return content;
321
+ const outputOptions = compilation.outputOptions;
322
+ const chunksById = getChunksById(compilation);
323
+ return content.replace(
324
+ CHUNK_URL_SENTINEL_REGEXP,
325
+ (_, hexId, contentHashType) => {
326
+ const chunkId = Buffer.from(hexId, "hex").toString("utf8");
327
+ const chunk = chunksById.get(chunkId);
328
+ if (!chunk) return "data:,";
329
+ // Reuse each pipeline's own filename-template resolver so the URL
330
+ // matches exactly what that plugin emits (worker/hot-update chunk
331
+ // handling included), mirroring the CSS branch.
332
+ let filenameTemplate;
333
+ if (contentHashType === "css") {
334
+ filenameTemplate = getCssModulesPlugin().getChunkFilenameTemplate(
335
+ chunk,
336
+ outputOptions
337
+ );
338
+ } else {
339
+ const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin");
340
+
341
+ filenameTemplate = JavascriptModulesPlugin.getChunkFilenameTemplate(
342
+ chunk,
343
+ outputOptions
344
+ );
345
+ }
346
+ const filename = compilation.getPath(
347
+ /** @type {import("../TemplatedPathPlugin").TemplatePath} */
348
+ (filenameTemplate),
349
+ {
350
+ chunk,
351
+ contentHashType
352
+ }
353
+ );
354
+ return `${PUBLIC_PATH_AUTO}${filename}`;
355
+ }
356
+ );
357
+ }
358
+
359
+ /**
360
+ * Emit a sentinel for a linked HTML page's URL (a tag the user mapped to
361
+ * the `html` source `type`). The page's emitted filename isn't known at
362
+ * code-gen time; `resolveHtmlPageUrlSentinels` swaps it for
363
+ * `${PUBLIC_PATH_AUTO}<htmlFilename>` once the page has been built.
364
+ * @param {string | number} moduleId id of the linked HTML module
365
+ * @returns {string} sentinel
366
+ */
367
+ static makeHtmlPageUrlSentinel(moduleId) {
368
+ const hexId = Buffer.from(String(moduleId), "utf8").toString("hex");
369
+ return `__WEBPACK_HTML_PAGE_URL__${hexId}__END__`;
370
+ }
371
+
372
+ /**
373
+ * Replace every `makeHtmlPageUrlSentinel` sentinel in `content` with
374
+ * `${PUBLIC_PATH_AUTO}<htmlFilename>`, resolving each linked page's emitted
375
+ * filename through `getFilename`.
376
+ * @param {string} content content
377
+ * @param {(moduleId: string) => string} getFilename maps a linked module id to its emitted html filename
378
+ * @returns {string} resolved content
379
+ */
380
+ static resolveHtmlPageUrlSentinels(content, getFilename) {
381
+ if (!content.includes("__WEBPACK_HTML_PAGE_URL__")) return content;
382
+ return content.replace(
383
+ HTML_PAGE_URL_SENTINEL_REGEXP,
384
+ (_, hexId) =>
385
+ `${PUBLIC_PATH_AUTO}${getFilename(
386
+ Buffer.from(hexId, "hex").toString("utf8")
387
+ )}`
388
+ );
389
+ }
390
+
391
+ /**
392
+ * Emit a sentinel for a URL-referenced asset module. Resolved by
393
+ * `resolveAssetUrlSentinels` from the asset module's own codegen data
394
+ * (`data.get("url")`), which isn't populated when `HtmlEntryDependency`
395
+ * runs — the asset module's own codegen may still be pending.
396
+ * @param {string} moduleIdentifier the referenced asset module's `identifier()`
397
+ * @returns {string} sentinel
398
+ */
399
+ static makeAssetUrlSentinel(moduleIdentifier) {
400
+ const hex = Buffer.from(moduleIdentifier, "utf8").toString("hex");
401
+ return `__WEBPACK_HTML_ASSET_URL__${hex}__END__`;
402
+ }
403
+
404
+ /**
405
+ * Replace every `makeAssetUrlSentinel` in `content` with the asset module's
406
+ * emitted URL, read from its codegen data. Unresolved sentinels (module
407
+ * absent, no codegen result yet, or no URL channel — e.g. an inlined
408
+ * data-URI) map to `data:,` so the surrounding `<link>` degrades cleanly
409
+ * instead of shipping the raw placeholder.
410
+ * @param {string} content content
411
+ * @param {Compilation} compilation compilation
412
+ * @returns {string} resolved content
413
+ */
414
+ static resolveAssetUrlSentinels(content, compilation) {
415
+ if (!content.includes("__WEBPACK_HTML_ASSET_URL__")) return content;
416
+ /** @type {Map<string, import("../Module")>} */
417
+ const byIdentifier = new Map();
418
+ for (const m of compilation.modules) byIdentifier.set(m.identifier(), m);
419
+ const codeGenerationResults =
420
+ /** @type {import("../CodeGenerationResults")} */
421
+ (compilation.codeGenerationResults);
422
+ return content.replace(ASSET_URL_SENTINEL_REGEXP, (_, hex) => {
423
+ const id = Buffer.from(hex, "hex").toString("utf8");
424
+ const module = byIdentifier.get(id);
425
+ if (!module) return "data:,";
426
+ if (!codeGenerationResults.has(module, undefined)) return "data:,";
427
+ const codeGen = codeGenerationResults.get(module, undefined);
428
+ const data = codeGen.data;
429
+ if (!data) return "data:,";
430
+ const url =
431
+ /** @type {Record<string, string | undefined> | undefined} */
432
+ (data.get("url"));
433
+ // Prefer the `asset-url` channel — it's the actual URL string
434
+ // (publicPath + filename). Also handled: assets reached only from JS
435
+ // have no `asset-url` channel (their only URL is the JS expression
436
+ // `__webpack_require__.p + "…"`); for those we reconstruct the URL
437
+ // from the emitted `filename` + `PUBLIC_PATH_AUTO` so the same
438
+ // undo-path substitution runs at asset render.
439
+ if (url && url["asset-url"]) return url["asset-url"];
440
+ const filename = /** @type {string | undefined} */ (data.get("filename"));
441
+ if (filename) return `${PUBLIC_PATH_AUTO}${filename}`;
442
+ return "data:,";
443
+ });
444
+ }
445
+
446
+ /**
447
+ * Emit a sentinel for a chunk's SRI hash. Resolved late (after
448
+ * `RealContentHashPlugin`) by `resolveChunkIntegritySentinels`, since the
449
+ * hash must cover the chunk's final emitted bytes.
450
+ * @param {Chunk} chunk chunk
451
+ * @param {"javascript" | "css"} contentHashType which chunk asset to hash
452
+ * @returns {string} sentinel
453
+ */
454
+ static makeChunkIntegritySentinel(chunk, contentHashType) {
455
+ const hexId = Buffer.from(String(chunk.id), "utf8").toString("hex");
456
+ return `__WEBPACK_HTML_INTEGRITY__${hexId}__${contentHashType}__END__`;
457
+ }
458
+
459
+ /**
460
+ * Drop every ` integrity="<sentinel>"` from `content`. Used on the HTML
461
+ * string embedded in a JS chunk (e.g. `<iframe srcdoc>`), where a real SRI
462
+ * hash can't be produced — the chunk's own bytes aren't final at render time
463
+ * — and resolving it later would mutate the chunk after its content hash was
464
+ * computed. Only real HTML output assets keep the sentinel for late resolution.
465
+ * @param {string} content content
466
+ * @returns {string} content with integrity sentinels removed
467
+ */
468
+ static stripChunkIntegritySentinels(content) {
469
+ if (!content.includes("__WEBPACK_HTML_INTEGRITY__")) return content;
470
+ return content.replace(INTEGRITY_SENTINEL_STRIP_REGEXP, "");
471
+ }
472
+
473
+ /**
474
+ * Replace every ` integrity="<sentinel>"` with the chunk's real SRI hashes,
475
+ * or drop the attribute when `integrity` (a function) returns `false` for it.
476
+ * @param {string} content content
477
+ * @param {Compilation} compilation compilation
478
+ * @param {HtmlIntegrity} integrity the `output.html.integrity` option
479
+ * @returns {string} resolved content
480
+ */
481
+ static resolveChunkIntegritySentinels(content, compilation, integrity) {
482
+ if (!content.includes("__WEBPACK_HTML_INTEGRITY__")) return content;
483
+
484
+ const crypto = require("crypto");
485
+
486
+ // Report each bad hash algorithm once, not once per referencing tag.
487
+ const reportedBadAlgorithms = new Set();
488
+
489
+ const chunksById = getChunksById(compilation);
490
+ return content.replace(
491
+ INTEGRITY_SENTINEL_REGEXP,
492
+ (_, hexId, contentHashType) => {
493
+ const chunkId = Buffer.from(hexId, "hex").toString("utf8");
494
+ const chunk = chunksById.get(chunkId);
495
+ if (!chunk) return "";
496
+ // `chunk.files` holds the real emitted names (after
497
+ // `RealContentHashPlugin`), so hash those bytes — not a name
498
+ // re-derived from the template, which still has the pre-hash value.
499
+ let filename;
500
+ for (const file of chunk.files) {
501
+ if ((contentHashType === "css") === file.endsWith(".css")) {
502
+ filename = file;
503
+ break;
504
+ }
505
+ }
506
+ if (!filename) return "";
507
+ const asset = compilation.getAsset(filename);
508
+ if (!asset) return "";
509
+ const algorithms =
510
+ typeof integrity === "function"
511
+ ? integrity({ chunk, filename })
512
+ : integrity === true
513
+ ? ["sha384"]
514
+ : integrity;
515
+ if (!algorithms || algorithms.length === 0) return "";
516
+ const buffer = asset.source.buffer();
517
+ const parts = [];
518
+ for (const algorithm of algorithms) {
519
+ // `crypto.createHash` throws on an unknown algorithm name — turn
520
+ // that into a webpack error and skip the algorithm instead of
521
+ // crashing the whole compilation out of `processAssets`.
522
+ try {
523
+ parts.push(
524
+ `${algorithm}-${crypto
525
+ .createHash(algorithm)
526
+ .update(buffer)
527
+ .digest("base64")}`
528
+ );
529
+ } catch (_err) {
530
+ if (!reportedBadAlgorithms.has(algorithm)) {
531
+ reportedBadAlgorithms.add(algorithm);
532
+ compilation.errors.push(
533
+ new WebpackError(
534
+ `output.html.integrity: unsupported hash algorithm ${JSON.stringify(
535
+ algorithm
536
+ )}`
537
+ )
538
+ );
539
+ }
540
+ }
541
+ }
542
+ if (parts.length === 0) return "";
543
+ return ` integrity="${parts.join(" ")}"`;
544
+ }
545
+ );
546
+ }
547
+
548
+ /**
549
+ * @param {Chunk} chunk chunk
550
+ * @param {"javascript" | "css"} contentHashType which chunk asset to inline
551
+ * @returns {string} sentinel
552
+ */
553
+ static makeChunkInlineSentinel(chunk, contentHashType) {
554
+ const hexId = Buffer.from(String(chunk.id), "utf8").toString("hex");
555
+ return `__WEBPACK_HTML_INLINE__${hexId}__${contentHashType}__END__`;
556
+ }
557
+
558
+ /**
559
+ * Replace every inline sentinel with the chunk's actual source content.
560
+ * Must run after `RealContentHashPlugin` so the final emitted filenames are
561
+ * known (we look up the asset by filename from `chunk.files`).
562
+ * @param {string} content content
563
+ * @param {Compilation} compilation compilation
564
+ * @param {string} htmlFilename output name of the HTML file being resolved (to rebase CSS urls)
565
+ * @param {Set<string>=} inlinedFiles collects every chunk file inlined here, so the caller can drop now-unreferenced assets
566
+ * @returns {string} resolved content
567
+ */
568
+ static resolveChunkInlineSentinels(
569
+ content,
570
+ compilation,
571
+ htmlFilename,
572
+ inlinedFiles
573
+ ) {
574
+ if (!content.includes("__WEBPACK_HTML_INLINE__")) return content;
575
+ const chunksById = getChunksById(compilation);
576
+ const outputPath = /** @type {string} */ (compilation.outputOptions.path);
577
+ return content.replace(
578
+ INLINE_SENTINEL_REGEXP,
579
+ (_, hexId, contentHashType) => {
580
+ const chunkId = Buffer.from(hexId, "hex").toString("utf8");
581
+ const chunk = chunksById.get(chunkId);
582
+ if (!chunk) return "";
583
+ const isCss = contentHashType === "css";
584
+ let out = "";
585
+ for (const file of chunk.files) {
586
+ if (isCss !== file.endsWith(".css")) continue;
587
+ const asset = compilation.getAsset(file);
588
+ if (!asset) continue;
589
+ let raw = String(asset.source.source());
590
+ if (isCss) {
591
+ // Styles move into the document, so relative `url(...)` must be
592
+ // rebased; then escape `</style` so it can't close the block early.
593
+ raw = rebaseCssUrls(raw, file, htmlFilename, outputPath).replace(
594
+ /<\/(style)/gi,
595
+ "<\\/$1"
596
+ );
597
+ } else {
598
+ // Escape `</script` (early close) and `<!--` (enters the script-data
599
+ // escaped state, where a later `<script` hides the real close); both
600
+ // only occur inside a string/comment/regex, where `<\` is inert.
601
+ raw = raw
602
+ .replace(/<\/(script)/gi, "<\\/$1")
603
+ .replace(/<!--/g, "<\\!--");
604
+ }
605
+ out += raw;
606
+ if (inlinedFiles) inlinedFiles.add(file);
607
+ }
608
+ return out;
609
+ }
610
+ );
611
+ }
612
+
613
+ /**
614
+ * Parses the final HTML once and collects everything the `output.html`
615
+ * post-processing stages need: every `<script>`/`<link>`/`<style>`/`<meta>` as
616
+ * a mutable descriptor (for `transformTags`) paired with its source span, an
617
+ * attribute snapshot (to detect changes), and — for `<script>`/`<style>` — the
618
+ * raw-text body range and nonce insertion point (for CSP); plus the
619
+ * `<head>`/`<body>` open/content-end anchors (for `injectTags`). One parse feeds
620
+ * `injectTags` + `transformTags` + CSP, which `renderHtml` then applies in a
621
+ * single pass. Uses the pipeline's own parser (no regex).
622
+ * @param {string} content the final HTML (inline content already resolved)
623
+ * @returns {HtmlModel} the collected model
624
+ */
625
+ static collectHtml(content) {
626
+ /** @type {HtmlMutableTag[]} */
627
+ const tags = [];
628
+ /** @type {(HtmlTagSpan | null)[]} */
629
+ const spans = [];
630
+ /** @type {(string | null)[]} */
631
+ const originals = [];
632
+ /** @type {(HtmlTagDescriptor | null)[]} */
633
+ const descriptors = [];
634
+ let headOpen = -1;
635
+ let headEnd = -1;
636
+ let bodyOpen = -1;
637
+ let bodyEnd = -1;
638
+ let headDepth = 0;
639
+ let bodyDepth = 0;
640
+ // `skip.text` populates `contentEnd` (raw-text body end) without
641
+ // materializing text nodes; `</script` stays escaped, so CSP hashes match
642
+ // the exact bytes the browser sees.
643
+ new SourceProcessor()
644
+ .use({
645
+ [NodeType.Element]: {
646
+ enter: (path) => {
647
+ const name = path.tagName();
648
+ if (name === "head") {
649
+ if (headOpen < 0) headOpen = headEnd = path.tagEnd();
650
+ headDepth++;
651
+ return;
652
+ }
653
+ if (name === "body") {
654
+ if (bodyOpen < 0) bodyOpen = bodyEnd = path.tagEnd();
655
+ bodyDepth++;
656
+ return;
657
+ }
658
+ const end = path.end();
659
+ if (headDepth > 0 && end > headEnd) headEnd = end;
660
+ if (bodyDepth > 0 && end > bodyEnd) bodyEnd = end;
661
+ if (
662
+ name !== "script" &&
663
+ name !== "link" &&
664
+ name !== "style" &&
665
+ name !== "meta"
666
+ ) {
667
+ return;
668
+ }
669
+ /** @type {Record<string, string | boolean | undefined>} */
670
+ const attrs = {};
671
+ const count = path.attributeCount();
672
+ for (let i = 0; i < count; i++) {
673
+ const attr = path.attributeAt(i);
674
+ attrs[path.attributeName(attr)] =
675
+ path.attributeValueStart(attr) === -1
676
+ ? true
677
+ : path.attributeValue(attr);
678
+ }
679
+ const isRawText = name === "script" || name === "style";
680
+ tags.push({
681
+ tag: name,
682
+ attrs,
683
+ injectTo: bodyDepth > 0 ? "body" : "head"
684
+ });
685
+ spans.push({
686
+ start: path.start(),
687
+ openEnd: path.tagEnd(),
688
+ end,
689
+ location: bodyDepth > 0 ? "body" : "head",
690
+ nameEnd: isRawText ? path.nameEnd() : -1,
691
+ contentEnd: isRawText ? path.contentEnd() : -1,
692
+ selfClosing: path.selfClosing()
693
+ });
694
+ originals.push(snapshotAttrs(attrs));
695
+ descriptors.push(null);
696
+ },
697
+ exit: (path) => {
698
+ const name = path.tagName();
699
+ if (name === "head") {
700
+ if (headDepth > 0) headDepth--;
701
+ } else if (name === "body" && bodyDepth > 0) {
702
+ bodyDepth--;
703
+ }
704
+ }
705
+ }
706
+ })
707
+ .process(content, { skip: { text: true, doctype: true } });
708
+ return {
709
+ tags,
710
+ spans,
711
+ originals,
712
+ descriptors,
713
+ anchors: { headOpen, headEnd, bodyOpen, bodyEnd }
714
+ };
715
+ }
716
+
717
+ /**
718
+ * Appends `injectTags` descriptors to the model as spanless tags (pure inserts
719
+ * placed by `injectTo`), so `transformTags` sees them alongside the page's own
720
+ * tags and CSP hashes any injected inline `<script>`/`<style>`. `attrs` is
721
+ * copied so a `transformTags` mutation never corrupts the caller's descriptor.
722
+ * @param {HtmlModel} model the value from `collectHtml`
723
+ * @param {HtmlTagDescriptor[]} injected the `injectTags` descriptors
724
+ * @returns {void}
725
+ */
726
+ static addInjectedTags(model, injected) {
727
+ for (const descriptor of injected) {
728
+ model.tags.push({
729
+ tag: descriptor.tag,
730
+ attrs: descriptor.attrs ? { ...descriptor.attrs } : {},
731
+ injectTo: descriptor.injectTo || "head"
732
+ });
733
+ model.spans.push(null);
734
+ model.originals.push(null);
735
+ model.descriptors.push(descriptor);
736
+ }
737
+ }
738
+
739
+ /**
740
+ * Renders the collected (and hook-mutated) model back into HTML in a single
741
+ * pass: injected tags are placed by `injectTo`; an existing tag is left
742
+ * byte-for-byte unless it was removed, moved (`<head>`↔`<body>`, honoring
743
+ * `*-prepend`), or had its `attrs` changed; and — when `csp` is set and the
744
+ * page declares no CSP — a strict `<meta http-equiv="Content-Security-Policy">`
745
+ * is injected with a hash of every inline `<script>`/`<style>` (page's own and
746
+ * injected) plus an optional placeholder `nonce` on each. Edits run
747
+ * right-to-left; at a shared offset a delete/replace runs before an insert.
748
+ * @param {string} content the collected HTML (inline content already resolved)
749
+ * @param {HtmlModel} model the value from `collectHtml` after the hooks
750
+ * @param {CspOption} csp the `output.html.csp` option
751
+ * @returns {string} the rendered HTML
752
+ */
753
+ static renderHtml(content, model, csp) {
754
+ const { tags, spans, originals, descriptors, anchors } = model;
755
+ // CSP setup: an author-declared policy (page's own or injected) wins.
756
+ const options = csp ? (csp === true ? {} : csp) : undefined;
757
+ const nonce = options && options.nonce;
758
+ let hasCsp = false;
759
+ if (options) {
760
+ for (let i = 0; i < tags.length; i++) {
761
+ const tag = tags[i];
762
+ if (!tag.remove && tag.tag === "meta" && metaIsCsp(tag.attrs)) {
763
+ hasCsp = true;
764
+ break;
765
+ }
766
+ }
767
+ }
768
+ const addCsp = Boolean(options) && !hasCsp;
769
+ /** @type {Set<string>} */
770
+ const scriptSrc = new Set();
771
+ /** @type {Set<string>} */
772
+ const styleSrc = new Set();
773
+ let hashOf;
774
+ if (addCsp) {
775
+ const hashFunction =
776
+ /** @type {Exclude<CspOption, boolean | undefined>} */ (options)
777
+ .hashFunction || "sha256";
778
+ const createHash = getCreateNodeHash();
779
+ hashOf = (/** @type {string} */ body) =>
780
+ `'${hashFunction}-${createHash(hashFunction)
781
+ .update(body, "utf8")
782
+ .digest("base64")}'`;
783
+ }
784
+ // Insertions accumulated per offset (placement order preserved); range edits
785
+ // replace/delete an existing tag's span; region groups collect placements so
786
+ // `*-prepend` precedes the plain name at a shared (empty-region) anchor.
787
+ /** @type {Map<number, string>} */
788
+ const inserts = new Map();
789
+ /** @type {(pos: number, text: string) => void} */
790
+ const at = (pos, text) => {
791
+ if (text) inserts.set(pos, (inserts.get(pos) || "") + text);
792
+ };
793
+ // Placements accumulate per region so `*-prepend` always precedes the plain
794
+ // name at a shared offset (an empty `<head>`/`<body>`); emitted at the anchors
795
+ // after the loop.
796
+ /** @type {Record<string, string>} */
797
+ const groups = {
798
+ "head-prepend": "",
799
+ head: "",
800
+ "body-prepend": "",
801
+ body: ""
802
+ };
803
+ /** @type {(region: string | undefined, text: string) => void} */
804
+ const place = (region, text) => {
805
+ if (text) {
806
+ groups[region !== undefined && region in groups ? region : "head"] +=
807
+ text;
808
+ }
809
+ };
810
+ /** @type {{ start: number, end: number, text: string, insert: boolean }[]} */
811
+ const edits = [];
812
+ for (let i = 0; i < tags.length; i++) {
813
+ const tag = tags[i];
814
+ const span = spans[i];
815
+ const isRawText = tag.tag === "script" || tag.tag === "style";
816
+ const needsNonce =
817
+ addCsp &&
818
+ Boolean(nonce) &&
819
+ isRawText &&
820
+ !attrPresent(tag.attrs, "nonce");
821
+ // Hash an inline `<script>`/`<style>` (page's own or injected). External
822
+ // `<script src>` is covered by `'self'`; a self-closing tag has no body.
823
+ if (addCsp && isRawText && !tag.remove) {
824
+ const isScript = tag.tag === "script";
825
+ let body = "";
826
+ if (span) {
827
+ if (
828
+ !span.selfClosing &&
829
+ !(isScript && attrPresent(tag.attrs, "src"))
830
+ ) {
831
+ body = content.slice(span.openEnd, span.contentEnd);
832
+ }
833
+ } else if (!(isScript && attrPresent(tag.attrs, "src"))) {
834
+ body =
835
+ /** @type {HtmlTagDescriptor} */ (descriptors[i]).children || "";
836
+ }
837
+ if (body !== "") {
838
+ (isScript ? scriptSrc : styleSrc).add(
839
+ /** @type {(body: string) => string} */ (hashOf)(body)
840
+ );
841
+ }
842
+ }
843
+ if (!span) {
844
+ // Injected tag: serialize (with a nonce when CSP asks) and place it.
845
+ if (tag.remove) continue;
846
+ const descriptor = /** @type {HtmlTagDescriptor} */ (descriptors[i]);
847
+ const attrs = needsNonce
848
+ ? { nonce: /** @type {string} */ (nonce), ...tag.attrs }
849
+ : tag.attrs;
850
+ place(
851
+ tag.injectTo || "head",
852
+ serializeTag({
853
+ tag: tag.tag,
854
+ attrs,
855
+ children: descriptor.children,
856
+ voidTag: descriptor.voidTag
857
+ })
858
+ );
859
+ continue;
860
+ }
861
+ // Existing tag.
862
+ if (tag.remove) {
863
+ edits.push({
864
+ start: span.start,
865
+ end: span.end,
866
+ text: "",
867
+ insert: false
868
+ });
869
+ continue;
870
+ }
871
+ const attrsChanged = snapshotAttrs(tag.attrs) !== originals[i];
872
+ const moved =
873
+ tag.injectTo !== undefined && tag.injectTo !== span.location;
874
+ const nonceStr = needsNonce
875
+ ? ` nonce="${escapeAttribute(/** @type {string} */ (nonce))}"`
876
+ : "";
877
+ if (moved) {
878
+ const opening = `<${tag.tag}${nonceStr}${serializeAttrs(tag.attrs)}>`;
879
+ edits.push({
880
+ start: span.start,
881
+ end: span.end,
882
+ text: "",
883
+ insert: false
884
+ });
885
+ place(tag.injectTo, opening + content.slice(span.openEnd, span.end));
886
+ } else if (attrsChanged) {
887
+ // Rewrite the opening tag (a nonce, if any, lands first).
888
+ edits.push({
889
+ start: span.start,
890
+ end: span.openEnd,
891
+ text: `<${tag.tag}${nonceStr}${serializeAttrs(tag.attrs)}>`,
892
+ insert: false
893
+ });
894
+ } else if (nonceStr) {
895
+ // Nonce-only change: insert right after the tag name, rest verbatim.
896
+ edits.push({
897
+ start: span.nameEnd,
898
+ end: span.nameEnd,
899
+ text: nonceStr,
900
+ insert: true
901
+ });
902
+ }
903
+ }
904
+ if (addCsp) {
905
+ if (nonce) {
906
+ scriptSrc.add(`'nonce-${nonce}'`);
907
+ styleSrc.add(`'nonce-${nonce}'`);
908
+ }
909
+ // Strict baseline; a user `policy` directive replaces one, hashes/nonce append.
910
+ /** @type {Map<string, Set<string>>} */
911
+ const directives = new Map([
912
+ ["script-src", new Set(["'self'"])],
913
+ ["style-src", new Set(["'self'"])],
914
+ ["object-src", new Set(["'none'"])],
915
+ ["base-uri", new Set(["'self'"])]
916
+ ]);
917
+ const policyOption =
918
+ /** @type {Exclude<CspOption, boolean | undefined>} */ (options).policy;
919
+ if (policyOption) {
920
+ for (const [name, value] of Object.entries(policyOption)) {
921
+ directives.set(name, new Set(Array.isArray(value) ? value : [value]));
922
+ }
923
+ }
924
+ /** @type {(name: string, extra: Set<string>) => void} */
925
+ const append = (name, extra) => {
926
+ let set = directives.get(name);
927
+ if (!set) directives.set(name, (set = new Set()));
928
+ for (const value of extra) set.add(value);
929
+ };
930
+ append("script-src", scriptSrc);
931
+ append("style-src", styleSrc);
932
+ const policy = [...directives]
933
+ .filter(([, values]) => values.size > 0)
934
+ .map(([name, values]) => `${name} ${[...values].join(" ")}`)
935
+ .join("; ");
936
+ const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(
937
+ policy
938
+ )}">`;
939
+ // First at the head anchor, so it precedes any head-prepend tag.
940
+ at(anchors.headOpen, meta);
941
+ }
942
+ // Emit region placements at the `<head>`/`<body>` anchors (after any CSP
943
+ // meta, prepend before the plain name). The parser always synthesizes an
944
+ // implied `<head>`/`<body>`, so both anchors are always present.
945
+ at(anchors.headOpen, groups["head-prepend"]);
946
+ at(anchors.headEnd, groups.head);
947
+ at(anchors.bodyOpen, groups["body-prepend"]);
948
+ at(anchors.bodyEnd, groups.body);
949
+ for (const [pos, text] of inserts) {
950
+ edits.push({ start: pos, end: pos, text, insert: true });
951
+ }
952
+ if (edits.length === 0) return content;
953
+ edits.sort(
954
+ (a, b) => b.start - a.start || Number(a.insert) - Number(b.insert)
955
+ );
956
+ let result = content;
957
+ for (const edit of edits) {
958
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
959
+ }
960
+ return result;
961
+ }
962
+
963
+ /**
964
+ * Embeds each inlined chunk's content hash into its inline sentinel
965
+ * (`…__<type>__END__` → `…__<type>__<hash>__END__`). The sentinel otherwise
966
+ * carries only the stable chunk id, so the host HTML's bytes wouldn't change
967
+ * when the inlined content changes — the resolved chunk URL that normally
968
+ * busts the page `[contenthash]` is gone once inlined. Embedding the hash
969
+ * makes the emitted bytes content-dependent, so both the initial hash and
970
+ * RealContentHashPlugin's recompute pick up inlined-content changes. The
971
+ * resolver (`resolveChunkInlineSentinels`) ignores this segment.
972
+ * @param {string} content content with chunk-url sentinels already resolved
973
+ * @param {Compilation} compilation compilation
974
+ * @returns {string} content with content-hash-tagged inline sentinels
975
+ */
976
+ static embedInlineChunkHashes(content, compilation) {
977
+ if (!content.includes("__WEBPACK_HTML_INLINE__")) return content;
978
+ const chunksById = getChunksById(compilation);
979
+ return content.replace(
980
+ INLINE_SENTINEL_REGEXP,
981
+ (match, hexId, contentHashType) => {
982
+ const chunkId = Buffer.from(hexId, "hex").toString("utf8");
983
+ const chunk = chunksById.get(chunkId);
984
+ if (!chunk) return match;
985
+ const hash =
986
+ (chunk.contentHash && chunk.contentHash[contentHashType]) ||
987
+ chunk.renderedHash ||
988
+ chunk.hash;
989
+ if (!hash) return match;
990
+ return `__WEBPACK_HTML_INLINE__${hexId}__${contentHashType}__${hash}__END__`;
991
+ }
992
+ );
993
+ }
994
+
995
+ /**
996
+ * Creates an instance of HtmlGenerator.
997
+ * @param {HtmlGeneratorOptions=} options generator options
998
+ * @param {ModuleGraph=} moduleGraph the module graph; used to detect when an HTML module is reached as a compilation entry so `extract` can default to `true` for it
999
+ */
1000
+ constructor(options, moduleGraph) {
1001
+ super();
1002
+ /** @type {HtmlGeneratorOptions} */
1003
+ this.options = options || {};
1004
+ /** @type {ModuleGraph | undefined} */
1005
+ this._moduleGraph = moduleGraph;
1006
+ // Raw dependency-template render (before `[webpack/auto]` resolution),
1007
+ // shared between the JS and HTML type passes of a single
1008
+ // `codeGeneration()` call. Keyed by that call's `runtimeRequirements`
1009
+ // Set — created once per call and passed to every type's `generate()`,
1010
+ // so it uniquely scopes the cache to one module's one code generation
1011
+ // and releases with it. The two passes differ only in `undoPath`.
1012
+ /** @type {WeakMap<RuntimeRequirements, string>} */
1013
+ this._rawRenderCache = new WeakMap();
1014
+ }
1015
+
1016
+ /**
1017
+ * Returns the reason this module cannot be concatenated, when one exists.
1018
+ * @param {NormalModule} module module for which the bailout reason should be determined
1019
+ * @param {ConcatenationBailoutReasonContext} context context
1020
+ * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
1021
+ */
1022
+ getConcatenationBailoutReason(module, context) {
1023
+ // The HMR shim references the per-module `module.hot` object — when an
1024
+ // HTML module is concatenated, that scope is gone (the merged file
1025
+ // shares a single `module`), so the self-accept / DOM-patch wiring
1026
+ // would target the wrong module id. Bail out of concatenation so the
1027
+ // HMR-aware HTML module keeps its own module scope.
1028
+ if (module.hot) {
1029
+ return "HTML module needs its own module scope for HMR";
1030
+ }
1031
+ return undefined;
1032
+ }
1033
+
1034
+ /**
1035
+ * Whether this HTML module is reached as a compilation entry. Entry
1036
+ * modules have at least one incoming connection without an
1037
+ * `originModule` (the EntryDependency added by `compilation.addEntry`) —
1038
+ * this covers both HTML-as-entry-point and a linked `type: "html"` page
1039
+ * (added as its own entry by HtmlModulesPlugin).
1040
+ * @param {NormalModule} module module
1041
+ * @returns {boolean} true when the module is an entry
1042
+ */
1043
+ _isEntryModule(module) {
1044
+ if (!this._moduleGraph) return false;
1045
+ for (const connection of this._moduleGraph.getIncomingConnections(module)) {
1046
+ if (!connection.originModule) return true;
1047
+ }
1048
+ return false;
1049
+ }
1050
+
1051
+ /**
1052
+ * Whether to emit the extracted `.html` file for this module.
1053
+ * `options.extract === true` always extracts; `false` and `"inline"` never;
1054
+ * when the option is left unspecified, extraction defaults to on for HTML
1055
+ * modules used as compilation entries — that's the HTML-as-entry-point case
1056
+ * and a linked `type: "html"` page (which is added as its own entry).
1057
+ * @param {NormalModule} module module
1058
+ * @returns {boolean} true when the `.html` file should be emitted
1059
+ */
1060
+ _shouldExtract(module) {
1061
+ const { extract } = this.options;
1062
+ if (extract === true) return true;
1063
+ if (extract === false || extract === "inline") return false;
1064
+ return this._isEntryModule(module);
1065
+ }
1066
+
1067
+ /**
1068
+ * Whether this module exposes the `html` source type. Like `_shouldExtract`,
1069
+ * but `"inline"` also exposes it — the processed HTML is read back into the
1070
+ * host attribute (e.g. `<iframe srcdoc>`) instead of emitted as a file.
1071
+ * @param {NormalModule} module module
1072
+ * @returns {boolean} true when the `html` source type is available
1073
+ */
1074
+ _shouldExposeHtmlType(module) {
1075
+ if (this.options.extract === "inline") return true;
1076
+ return this._shouldExtract(module);
1077
+ }
1078
+
1079
+ /**
1080
+ * Returns the source types available for this module.
1081
+ * @param {NormalModule} module fresh module
1082
+ * @returns {SourceTypes} available types (do not mutate)
1083
+ */
1084
+ getTypes(module) {
1085
+ if (this._shouldExposeHtmlType(module)) {
1086
+ return JAVASCRIPT_AND_HTML_TYPES;
1087
+ }
1088
+ return JAVASCRIPT_TYPES;
1089
+ }
1090
+
1091
+ /**
1092
+ * @returns {boolean} whether getTypes() depends on the module's incoming connections
1093
+ */
1094
+ getTypesDependOnIncomingConnections() {
1095
+ // A fixed extract (`true` / `false` / `"inline"`) gives a stable type set;
1096
+ // only the unset default reads `_isEntryModule` (incoming connections).
1097
+ const { extract } = this.options;
1098
+ return extract !== true && extract !== false && extract !== "inline";
1099
+ }
1100
+
1101
+ /**
1102
+ * Returns the estimated size for the requested source type.
1103
+ * @param {NormalModule} module the module
1104
+ * @param {SourceType=} type source type
1105
+ * @returns {number} estimate size of the module
1106
+ */
1107
+ getSize(module, type) {
1108
+ const originalSource = module.originalSource();
1109
+ if (!originalSource) return 0;
1110
+ if (type === HTML_TYPE) return originalSource.size();
1111
+ return originalSource.size() + 10;
1112
+ }
1113
+
1114
+ /**
1115
+ * Processes the provided module.
1116
+ * @param {Dependency} dependency the dependency to generate
1117
+ * @param {ReplaceSource} source the current replace source which can be modified
1118
+ * @param {DependencyTemplateContext} templateContext the template context (shared across all dependencies of the module)
1119
+ * @returns {void}
1120
+ */
1121
+ sourceDependency(dependency, source, templateContext) {
1122
+ const constructor =
1123
+ /** @type {DependencyConstructor} */
1124
+ (dependency.constructor);
1125
+ const template = templateContext.dependencyTemplates.get(constructor);
1126
+ if (!template) {
1127
+ throw new Error(
1128
+ `No template for dependency: ${dependency.constructor.name}`
1129
+ );
1130
+ }
1131
+
1132
+ template.apply(dependency, source, templateContext);
1133
+ }
1134
+
1135
+ /**
1136
+ * Processes the provided dependencies block.
1137
+ * @param {import("../DependenciesBlock")} block the dependencies block which will be processed
1138
+ * @param {ReplaceSource} source the current replace source which can be modified
1139
+ * @param {DependencyTemplateContext} templateContext the template context
1140
+ * @returns {void}
1141
+ */
1142
+ sourceBlock(block, source, templateContext) {
1143
+ for (const dependency of block.dependencies) {
1144
+ this.sourceDependency(dependency, source, templateContext);
1145
+ }
1146
+
1147
+ for (const childBlock of block.blocks) {
1148
+ this.sourceBlock(childBlock, source, templateContext);
1149
+ }
1150
+ }
1151
+
1152
+ /**
1153
+ * Processes the provided module.
1154
+ * @param {NormalModule} module the module to generate
1155
+ * @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments
1156
+ * @param {ReplaceSource} source the current replace source which can be modified
1157
+ * @param {GenerateContext} generateContext the generateContext
1158
+ * @returns {void}
1159
+ */
1160
+ sourceModule(module, initFragments, source, generateContext) {
1161
+ // Only `dependency` varies across `template.apply` calls, so one context
1162
+ // (and one lazy `chunkInitFragments` getter) serves the whole module.
1163
+ /** @type {InitFragment<GenerateContext>[] | undefined} */
1164
+ let chunkInitFragments;
1165
+ /** @type {DependencyTemplateContext} */
1166
+ const templateContext = {
1167
+ runtimeTemplate: generateContext.runtimeTemplate,
1168
+ dependencyTemplates: generateContext.dependencyTemplates,
1169
+ moduleGraph: generateContext.moduleGraph,
1170
+ chunkGraph: generateContext.chunkGraph,
1171
+ module,
1172
+ runtime: generateContext.runtime,
1173
+ runtimeRequirements: generateContext.runtimeRequirements,
1174
+ concatenationScope: generateContext.concatenationScope,
1175
+ codeGenerationResults:
1176
+ /** @type {CodeGenerationResults} */
1177
+ (generateContext.codeGenerationResults),
1178
+ initFragments,
1179
+ get chunkInitFragments() {
1180
+ if (!chunkInitFragments) {
1181
+ const data =
1182
+ /** @type {NonNullable<GenerateContext["getData"]>} */
1183
+ (generateContext.getData)();
1184
+ chunkInitFragments = data.get("chunkInitFragments");
1185
+ if (!chunkInitFragments) {
1186
+ chunkInitFragments = [];
1187
+ data.set("chunkInitFragments", chunkInitFragments);
1188
+ }
1189
+ }
1190
+
1191
+ return chunkInitFragments;
1192
+ }
1193
+ };
1194
+
1195
+ for (const dependency of module.dependencies) {
1196
+ this.sourceDependency(dependency, source, templateContext);
1197
+ }
1198
+
1199
+ if (module.presentationalDependencies !== undefined) {
1200
+ for (const dependency of module.presentationalDependencies) {
1201
+ this.sourceDependency(dependency, source, templateContext);
1202
+ }
1203
+ }
1204
+
1205
+ for (const childBlock of module.blocks) {
1206
+ this.sourceBlock(childBlock, source, templateContext);
1207
+ }
1208
+ }
1209
+
1210
+ /**
1211
+ * Run all HTML dependency templates against the original module source and
1212
+ * return the rewritten HTML. When `undoPath` is a string, `[webpack/auto]`
1213
+ * placeholders left in by asset/url dependencies are resolved to that
1214
+ * undo path (use `""` to make URLs root-relative). When `undoPath` is
1215
+ * `undefined`, the placeholders are preserved so the caller (typically
1216
+ * `HtmlModulesPlugin#renderManifest`, which only knows the final
1217
+ * `.html` filename after code generation) can resolve them itself.
1218
+ * @param {NormalModule} module the module to render
1219
+ * @param {GenerateContext} generateContext the generate context
1220
+ * @param {string=} undoPath value to substitute for `[webpack/auto]` placeholders
1221
+ * @returns {string} the rewritten HTML
1222
+ */
1223
+ _renderHtml(module, generateContext, undoPath) {
1224
+ // The dependency-template pass is identical for both type passes (no
1225
+ // template branches on `type` or writes `runtimeRequirements`), so
1226
+ // compute the raw render once per `codeGeneration()` and reuse it; the
1227
+ // passes diverge only in the `[webpack/auto]` substitution below.
1228
+ const cacheKey = generateContext.runtimeRequirements;
1229
+ let rawContent = this._rawRenderCache.get(cacheKey);
1230
+ if (rawContent === undefined) {
1231
+ const originalSource = /** @type {Source} */ (module.originalSource());
1232
+ const source = new ReplaceSource(originalSource);
1233
+ /** @type {InitFragment<GenerateContext>[]} */
1234
+ const initFragments = [];
1235
+
1236
+ this.sourceModule(module, initFragments, source, generateContext);
1237
+ rawContent = /** @type {string} */ (source.source());
1238
+ this._rawRenderCache.set(cacheKey, rawContent);
1239
+ }
1240
+
1241
+ if (undoPath === undefined) {
1242
+ // HTML output — leave sentinels and `[webpack/auto]` for renderManifest.
1243
+ return rawContent;
1244
+ }
1245
+
1246
+ // JS-export path — resolve `[webpack/auto]` inline; chunk-URL sentinels
1247
+ // stay for `HtmlModulesPlugin`'s `JavascriptModulesPlugin.render` tap.
1248
+ if (!rawContent.includes(PUBLIC_PATH_AUTO)) return rawContent;
1249
+ // A relative `<base href>` prepends `../`s so the base can't misdirect
1250
+ // the rewritten URLs (see `HtmlParser`).
1251
+ const basePrefix =
1252
+ /** @type {HtmlModuleBuildInfo} */ (module.buildInfo).baseUrlPrefix || "";
1253
+ return rawContent.split(PUBLIC_PATH_AUTO).join(basePrefix + undoPath);
1254
+ }
1255
+
1256
+ /**
1257
+ * Generates generated code for this runtime module.
1258
+ * @param {NormalModule} module module for which the code should be generated
1259
+ * @param {GenerateContext} generateContext context for generate
1260
+ * @returns {Source | null} generated code
1261
+ */
1262
+ generate(module, generateContext) {
1263
+ const originalSource = module.originalSource();
1264
+
1265
+ if (!originalSource) {
1266
+ return new RawSource("");
1267
+ }
1268
+
1269
+ if (generateContext.type === HTML_TYPE) {
1270
+ // Preserve `[webpack/auto]`; renderManifest resolves it once `.html` filename is known.
1271
+ return new RawSource(
1272
+ this._renderHtml(module, generateContext, undefined)
1273
+ );
1274
+ }
1275
+
1276
+ // JS export: resolve `[webpack/auto]` to root-relative URLs.
1277
+ const generated = this._renderHtml(module, generateContext, "");
1278
+
1279
+ /** @type {string} */
1280
+ let sourceContent;
1281
+ // `module.hot` is set by `HotModuleReplacementPlugin` on every module
1282
+ // when HMR is enabled. When set, we cannot use the concatenation path
1283
+ // (it merges into a parent's module scope, where `module.hot.accept`
1284
+ // would target the wrong id) — `getConcatenationBailoutReason` keeps
1285
+ // us out of concatenation in that case.
1286
+ if (generateContext.concatenationScope && !module.hot) {
1287
+ generateContext.concatenationScope.registerNamespaceExport(
1288
+ ConcatenationScope.NAMESPACE_OBJECT_EXPORT
1289
+ );
1290
+ sourceContent = `${generateContext.runtimeTemplate.renderConst()} ${
1291
+ ConcatenationScope.NAMESPACE_OBJECT_EXPORT
1292
+ } = ${JSON.stringify(generated)};`;
1293
+ } else {
1294
+ generateContext.runtimeRequirements.add(RuntimeGlobals.module);
1295
+ if (module.hot) {
1296
+ sourceContent = this._renderHmrShim(
1297
+ module,
1298
+ generated,
1299
+ this._shouldExtract(module),
1300
+ generateContext.runtimeTemplate
1301
+ );
1302
+ } else {
1303
+ sourceContent = `${module.moduleArgument}.exports = ${JSON.stringify(
1304
+ generated
1305
+ )};`;
1306
+ }
1307
+ }
1308
+
1309
+ return new RawSource(sourceContent);
1310
+ }
1311
+
1312
+ /**
1313
+ * Emits the JS shim with HMR self-acceptance. When `extracting` is true the
1314
+ * HTML module is also the document the browser is viewing, so the shim
1315
+ * additionally patches `document.body` and `document.title` on every hot
1316
+ * update so the rendered page reflects the new HTML without a full
1317
+ * reload. The patching guard `module.hot.data` ensures the body is only
1318
+ * replaced on a re-evaluation after a hot update — never on the initial
1319
+ * page load, where `document.body` already matches the extracted HTML.
1320
+ *
1321
+ * The runtime extracts the body / title / head-sans-title sections from
1322
+ * the HTML with regexes. HTML comments are *masked* first — their
1323
+ * characters replaced with spaces, preserving length — via a `<!--…-->`
1324
+ * regex, so a `<body>` (or `</body>` / `<title>` / etc.) that appears
1325
+ * inside a comment can't fool the tag regexes — that was the one
1326
+ * well-known sharp edge of HTML+regex. Because masking keeps offsets
1327
+ * stable, the body / title content is sliced back out of the *original*
1328
+ * HTML, so real comments inside `<body>` survive into the patched DOM
1329
+ * exactly as a full page reload would render them.
1330
+ *
1331
+ * `<head>` changes beyond `<title>` (a new `<meta>`, a swapped
1332
+ * `<link rel=icon>`, an inline `<style>` block, …) can't be safely
1333
+ * DOM-patched: webpack injects its own runtime scripts and stylesheet
1334
+ * links into the head on initial load, and blindly replacing
1335
+ * `document.head.innerHTML` would tear them down. So the shim falls
1336
+ * back to a full reload — fine in a dev-server context because the
1337
+ * regular (non-hot-update) `page.html` chunk is re-emitted on every
1338
+ * rebuild, so the reloaded page picks up the new head.
1339
+ * @param {NormalModule} module module
1340
+ * @param {string} html the rewritten HTML content (with placeholders resolved)
1341
+ * @param {boolean} extracting whether the HTML module is being extracted as a real `.html` file
1342
+ * @param {RuntimeTemplate} runtimeTemplate runtime template (drives `const`/arrow emission based on environment support)
1343
+ * @returns {string} JS shim source
1344
+ */
1345
+ _renderHmrShim(module, html, extracting, runtimeTemplate) {
1346
+ const declare = runtimeTemplate.renderConst();
1347
+ const acceptBlock = extracting
1348
+ ? [
1349
+ "module.hot.accept();",
1350
+ // Mask `<!-- … -->` comments — replace their characters
1351
+ // with spaces, preserving length — before any tag regex
1352
+ // runs. Masking (rather than deleting) keeps string offsets
1353
+ // stable, so the body/title content can be sliced back out
1354
+ // of the original HTML with comments intact, while a
1355
+ // `<body>`/`</body>`/`<title>` inside a comment can no
1356
+ // longer fool the tag regexes (the non-greedy `*?` would
1357
+ // otherwise stop at the FIRST `</body>` it sees, even one
1358
+ // inside a comment).
1359
+ `${declare} __webpack_mask_comments__ = ${runtimeTemplate.returningFunction(
1360
+ `h.replace(/<!--[\\s\\S]*?-->/g, ${runtimeTemplate.returningFunction(
1361
+ 'c.replace(/[^\\n]/g, " ")',
1362
+ "c"
1363
+ )})`,
1364
+ "h"
1365
+ )};`,
1366
+ // Mask comments once per evaluation; reused for every
1367
+ // tag-boundary search (head/body/title and the dispose-time
1368
+ // head diff) so a large page isn't re-scanned per section.
1369
+ `${declare} __webpack_masked_html__ = __webpack_mask_comments__(__webpack_html__);`,
1370
+ // Slice the inner content of `<tag>…</tag>` out of the original
1371
+ // HTML, using the pre-masked copy to locate the tag boundaries.
1372
+ `${declare} __webpack_extract__ = ${runtimeTemplate.basicFunction(
1373
+ "tag",
1374
+ [
1375
+ `${declare} open = new RegExp("<" + tag + "[^>]*>", "i").exec(__webpack_masked_html__);`,
1376
+ "if (!open) return null;",
1377
+ `${declare} start = open.index + open[0].length;`,
1378
+ `${declare} close = new RegExp("</" + tag + ">", "i").exec(__webpack_masked_html__.slice(start));`,
1379
+ "if (!close) return null;",
1380
+ "return __webpack_html__.slice(start, start + close.index);"
1381
+ ]
1382
+ )};`,
1383
+ `${declare} __webpack_extract_head__ = ${runtimeTemplate.basicFunction(
1384
+ "",
1385
+ [
1386
+ // Mask only the small extracted head so a comment-only head
1387
+ // edit doesn't force a full reload.
1388
+ `${declare} head = __webpack_extract__("head");`,
1389
+ 'return head === null ? "" : __webpack_mask_comments__(head).replace(/<title[^>]*>[\\s\\S]*?<\\/title>/i, "").trim();'
1390
+ ]
1391
+ )};`,
1392
+ "if (module.hot.data && typeof document !== 'undefined') {",
1393
+ Template.indent([
1394
+ `${declare} __webpack_new_head__ = __webpack_extract_head__();`,
1395
+ "if (module.hot.data.__webpack_head__ !== undefined && __webpack_new_head__ !== module.hot.data.__webpack_head__ && typeof window !== 'undefined' && window.location && typeof window.location.reload === 'function') {",
1396
+ Template.indent("window.location.reload();"),
1397
+ "} else {",
1398
+ Template.indent([
1399
+ `${declare} __webpack_body__ = __webpack_extract__("body");`,
1400
+ "if (__webpack_body__ !== null && document.body) document.body.innerHTML = __webpack_body__;",
1401
+ `${declare} __webpack_title__ = __webpack_extract__("title");`,
1402
+ "if (__webpack_title__ !== null) document.title = __webpack_title__;"
1403
+ ]),
1404
+ "}"
1405
+ ]),
1406
+ "}",
1407
+ // Capture this evaluation's head (sans title, comments
1408
+ // masked) on dispose so the next module instance can diff
1409
+ // against it.
1410
+ `module.hot.dispose(${runtimeTemplate.basicFunction(
1411
+ "data",
1412
+ "data.__webpack_head__ = __webpack_extract_head__();"
1413
+ )});`
1414
+ ]
1415
+ : ["module.hot.accept();"];
1416
+ return Template.asString([
1417
+ `${declare} __webpack_html__ = ${JSON.stringify(html)};`,
1418
+ `${module.moduleArgument}.exports = __webpack_html__;`,
1419
+ "if (module.hot) {",
1420
+ Template.indent(acceptBlock),
1421
+ "}"
1422
+ ]);
1423
+ }
1424
+
1425
+ /**
1426
+ * Generates fallback output for the provided error condition.
1427
+ * @param {Error} error the error
1428
+ * @param {NormalModule} module module for which the code should be generated
1429
+ * @param {GenerateContext} generateContext context for generate
1430
+ * @returns {Source | null} generated code
1431
+ */
1432
+ generateError(error, module, generateContext) {
1433
+ if (generateContext.type === HTML_TYPE) {
1434
+ // Strip `<`, `>`, `--` runs from `error.message` so it can't escape the comment.
1435
+ const safe = String(error.message)
1436
+ .replace(/[<>]/g, "")
1437
+ .replace(/-{2,}/g, (m) => `${"-".repeat(m.length - 1)} `);
1438
+ return new RawSource(`<!-- webpack error: ${safe} -->`);
1439
+ }
1440
+ return new RawSource(`throw new Error(${JSON.stringify(error.message)});`);
1441
+ }
1442
+
1443
+ /**
1444
+ * Updates the hash with the data contributed by this instance.
1445
+ * @param {Hash} hash hash that will be modified
1446
+ * @param {UpdateHashContext} updateHashContext context for updating hash
1447
+ */
1448
+ updateHash(hash, updateHashContext) {
1449
+ hash.update("html");
1450
+ // Source-type set changes when html-type exposure flips; the HMR shim's
1451
+ // `extracting` branch changes when the emit decision flips. They differ
1452
+ // only for `"inline"` (exposes html, but does not emit), so hash both.
1453
+ // One `_shouldExtract` walk covers both checks (expose = extract ∪ inline).
1454
+ const extract = this._shouldExtract(updateHashContext.module);
1455
+ if (extract || this.options.extract === "inline") {
1456
+ hash.update("html-type");
1457
+ }
1458
+ if (extract) {
1459
+ hash.update("extract");
1460
+ }
1461
+ // The HMR shim emits additional self-accept / DOM-patch code that
1462
+ // isn't emitted in non-HMR builds, so the cached codegen must
1463
+ // invalidate when `module.hot` toggles.
1464
+ if (updateHashContext.module.hot) {
1465
+ hash.update("hot");
1466
+ }
1467
+ }
1468
+ }
1469
+
1470
+ module.exports = HtmlGenerator;