@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,1970 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ */
4
+
5
+ "use strict";
6
+
7
+ const Parser = require("../Parser");
8
+ const ConstDependency = require("../dependencies/ConstDependency");
9
+ const HtmlEntryDependency = require("../dependencies/HtmlEntryDependency");
10
+ const HtmlInlineHtmlDependency = require("../dependencies/HtmlInlineHtmlDependency");
11
+ const HtmlInlineScriptDependency = require("../dependencies/HtmlInlineScriptDependency");
12
+ const HtmlInlineStyleDependency = require("../dependencies/HtmlInlineStyleDependency");
13
+ const HtmlSourceDependency = require("../dependencies/HtmlSourceDependency");
14
+ const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
15
+ const CommentCompilationWarning = require("../errors/CommentCompilationWarning");
16
+ const ModuleDependencyError = require("../errors/ModuleDependencyError");
17
+ const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning");
18
+ const WebpackError = require("../errors/WebpackError");
19
+ const ResourceHintPlugin = require("../prefetch/ResourceHintPlugin");
20
+ const parseResourceHintOptions = require("../prefetch/parseResourceHintOptions");
21
+ const LazySet = require("../util/LazySet");
22
+ const LocConverter = require("../util/LocConverter");
23
+ const createHash = require("../util/createHash");
24
+ const { contextify } = require("../util/identifier");
25
+ const {
26
+ createMagicCommentContext,
27
+ parseMagicComment,
28
+ webpackCommentRegExp
29
+ } = require("../util/magicComment");
30
+ const {
31
+ NS_HTML,
32
+ NS_SVG,
33
+ NodeType,
34
+ SVG_TAG_ADJUST,
35
+ SourceProcessor,
36
+ decodeEntities,
37
+ escapeAttribute,
38
+ escapeText,
39
+ isAsciiWhitespace,
40
+ parseCssUrls,
41
+ parseMsapplicationTask,
42
+ parseSrc,
43
+ parseSrcset
44
+ } = require("./syntax");
45
+
46
+ /** @typedef {import("../../declarations/WebpackOptions").HtmlParserOptions} HtmlParserOptions */
47
+ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
48
+ /** @typedef {import("../Module")} Module */
49
+ /** @typedef {import("../Module").BuildInfo} BuildInfo */
50
+ /** @typedef {import("../Compilation").FileSystemDependencies} FileSystemDependencies */
51
+ /** @typedef {import("../Module").BuildMeta} BuildMeta */
52
+ /** @typedef {import("../NormalModule")} NormalModule */
53
+ /** @typedef {import("../Parser").ParserState} ParserState */
54
+ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
55
+ /** @typedef {import("./HtmlModule").HtmlModuleBuildInfo} HtmlModuleBuildInfo */
56
+
57
+ /**
58
+ * @typedef {object} HtmlTemplateContext
59
+ * @property {Module} module the html module being transformed
60
+ * @property {string} resource absolute path of the module's resource
61
+ * @property {(dependency: string) => void} addDependency register a file (e.g. a template partial) as a build dependency so editing it triggers a rebuild
62
+ * @property {(dependency: string) => void} addContextDependency register a directory as a build dependency
63
+ * @property {(dependency: string) => void} addMissingDependency register a not-yet-existing path as a build dependency so creating it triggers a rebuild
64
+ * @property {(dependency: string) => void} addBuildDependency register a build dependency (e.g. a template engine config) so changing it invalidates the cache
65
+ * @property {(warning: Error | string) => void} emitWarning report a non-fatal warning on the module
66
+ * @property {(error: Error | string) => void} emitError report an error on the module
67
+ */
68
+ /** @typedef {(source: string, context: HtmlTemplateContext) => string} HtmlTemplateFunction */
69
+
70
+ /** @typedef {import("./syntax").ParsedSource} ParsedSource */
71
+
72
+ // Cheap pre-filter for a `style="..."` attribute: only route it through the
73
+ // CSS pipeline when it can hold a URL-bearing function (`url()` / `src()` /
74
+ // `image()` / `image-set()`), otherwise the processed text equals the input.
75
+ const STYLE_ATTR_URL_REGEXP = /url\(|src\(|image\(|image-set\(/i;
76
+
77
+ // Cheap pre-filter for a `css-url` attribute value (an SVG presentation
78
+ // attribute such as `fill`, `clip-path`, …): only tokenize values that can
79
+ // hold a `url(...)` FuncIRI. Most are plain colors/keywords (`#fff`, `red`).
80
+ const FUNC_IRI_URL_REGEXP = /url\(/i;
81
+
82
+ // Cheap pre-filter for `<iframe srcdoc>` markup: only spin up a nested HTML
83
+ // module when the document can reference an asset — via any attribute (`src=`,
84
+ // `href=`, `style=`, …), a CSS `url(...)`, or a CSS `@import`. Pure
85
+ // formatting/text markup (`<p>hi</p>`) rewrites to itself, so skip it.
86
+ const SRCDOC_ASSET_REGEXP = /[=]|url\(|@import/i;
87
+
88
+ // A URL carrying its own scheme (`https:`, `data:`, …) ignores the document
89
+ // base per the URL spec, so `<base href>` never rewrites it.
90
+ const ABSOLUTE_URL_SCHEME_REGEXP = /^[a-zA-Z][a-zA-Z\d+\-.]*:/;
91
+
92
+ // a `charset=` declaration inside an `http-equiv="content-type"` content value
93
+ const CHARSET_DECLARATION_REGEXP = /charset\s*=/i;
94
+
95
+ /**
96
+ * @param {string} name meta name
97
+ * @param {string} content meta content
98
+ * @returns {string} meta tag
99
+ */
100
+ const metaTag = (name, content) => {
101
+ // og: uses property=; all others (including twitter:) use name=
102
+ const attr = name.startsWith("og:")
103
+ ? `property="${escapeAttribute(name)}"`
104
+ : `name="${escapeAttribute(name)}"`;
105
+ return `<meta ${attr} content="${escapeAttribute(content)}">`;
106
+ };
107
+
108
+ /**
109
+ * @param {string | { href: string, target?: string }} base base option
110
+ * @returns {string} base tag
111
+ */
112
+ const baseTag = (base) => {
113
+ const href = typeof base === "string" ? base : base.href;
114
+ const targetAttr =
115
+ typeof base === "object" && base.target
116
+ ? ` target="${escapeAttribute(base.target)}"`
117
+ : "";
118
+ return `<base href="${escapeAttribute(href)}"${targetAttr}>`;
119
+ };
120
+
121
+ /**
122
+ * Serializes every head tag an `output.html` options object asks for, in
123
+ * spec order: charset, base, meta tags, title. Used where a page is created
124
+ * from scratch (HtmlModulesPlugin's synthetic entry wrapper); authored pages
125
+ * instead merge the options against their existing tags during `parse` —
126
+ * existing tags win.
127
+ * @param {import("../../declarations/WebpackOptions").OutputHtmlOptions} opts html options
128
+ * @returns {string} head tags string
129
+ */
130
+ const buildHeadTags = (opts) => {
131
+ let out = "";
132
+ const meta = opts.meta;
133
+ if (meta && meta.charset) {
134
+ out += `<meta charset="${escapeAttribute(meta.charset)}">`;
135
+ }
136
+ if (opts.base) out += baseTag(opts.base);
137
+ if (meta) {
138
+ for (const [name, content] of Object.entries(meta)) {
139
+ if (name === "charset") continue;
140
+ out += metaTag(name, content);
141
+ }
142
+ }
143
+ if (opts.title) {
144
+ out += `<title>${escapeText(opts.title)}</title>`;
145
+ }
146
+ return out;
147
+ };
148
+
149
+ // CSP/fetch attributes copied verbatim onto a synthesized sibling `<link>` /
150
+ // `<script>` (`HtmlEntryDependency`). Fixed output order, independent of
151
+ // source order.
152
+ const COPYABLE_SIBLING_ATTRS = ["nonce", "crossorigin", "referrerpolicy"];
153
+
154
+ const CC_QUOTATION = '"'.charCodeAt(0);
155
+ const CC_APOSTROPHE = "'".charCodeAt(0);
156
+ const CC_SLASH = "/".charCodeAt(0);
157
+
158
+ /**
159
+ * Byte-exact source span of an attribute including the single leading
160
+ * whitespace (` name`, ` name=value`, ` name="value"`), mirroring the
161
+ * tokenizer's end-of-attribute rule (`valueEnd + 1` past the closing quote).
162
+ * @param {import("./syntax").HtmlPath} path walk path (used only for attribute-ref reads)
163
+ * @param {string} source HTML source
164
+ * @param {import("./syntax").HtmlAttributeRef} attr attribute ref
165
+ * @returns {string} the attribute's source slice
166
+ */
167
+ const attrSourceSpan = (path, source, attr) => {
168
+ const valueStart = path.attributeValueStart(attr);
169
+ const valueEnd = path.attributeValueEnd(attr);
170
+ const end =
171
+ valueStart === -1
172
+ ? path.attributeNameEnd(attr)
173
+ : source.charCodeAt(valueStart - 1) === CC_QUOTATION ||
174
+ source.charCodeAt(valueStart - 1) === CC_APOSTROPHE
175
+ ? valueEnd + 1
176
+ : valueEnd;
177
+ return source.slice(path.attributeNameStart(attr) - 1, end);
178
+ };
179
+
180
+ /**
181
+ * Source span of a tag's `integrity` attribute (offsets relative to
182
+ * `elementStart`, leading whitespace and quotes included), so the template can
183
+ * drop the content-specific author value without re-parsing. Null when absent.
184
+ * @param {import("./syntax").HtmlPath} path walk path (for attribute reads)
185
+ * @param {string} source HTML source
186
+ * @param {number} elementStart offset of the tag's opening `<`
187
+ * @returns {Range | null} the span, or null when there is no `integrity`
188
+ */
189
+ const captureIntegrityRange = (path, source, elementStart) => {
190
+ const integrityAttr = path.findAttribute("integrity");
191
+ if (integrityAttr === 0 || path.attributeNameStart(integrityAttr) < 0) {
192
+ return null;
193
+ }
194
+ let rs = path.attributeNameStart(integrityAttr);
195
+ while (rs > 0 && isAsciiWhitespace(source.charCodeAt(rs - 1))) {
196
+ rs--;
197
+ }
198
+ let re;
199
+ const ivs = path.attributeValueStart(integrityAttr);
200
+ if (ivs === -1) {
201
+ re = path.attributeNameEnd(integrityAttr);
202
+ } else {
203
+ const q = source.charCodeAt(ivs - 1);
204
+ const ive = path.attributeValueEnd(integrityAttr);
205
+ re = q === CC_QUOTATION || q === CC_APOSTROPHE ? ive + 1 : ive;
206
+ }
207
+ return [rs - elementStart, re - elementStart];
208
+ };
209
+
210
+ /**
211
+ * @param {Map<string, string>} attributes attributes
212
+ * @param {string} name name
213
+ * @returns {string | undefined} attribute value
214
+ */
215
+ const getAttributeValue = (attributes, name) => attributes.get(name);
216
+
217
+ /** @type {Map<string, Set<string>>} */
218
+ const META = new Map([
219
+ [
220
+ "name",
221
+ new Set([
222
+ // msapplication-TileImage
223
+ "msapplication-tileimage",
224
+ "msapplication-square70x70logo",
225
+ "msapplication-square150x150logo",
226
+ "msapplication-wide310x150logo",
227
+ "msapplication-square310x310logo",
228
+ "msapplication-config",
229
+ // Only the `icon-uri` part is an asset, see `parseMsapplicationTask`
230
+ "msapplication-task",
231
+ "twitter:image",
232
+ "twitter:image:src",
233
+ // Twitter player card: URL to the raw video/media stream
234
+ "twitter:player:stream",
235
+ // Legacy preview-image hint
236
+ "thumbnail"
237
+ ])
238
+ ],
239
+ [
240
+ "property",
241
+ new Set([
242
+ "og:image",
243
+ "og:image:url",
244
+ "og:image:secure_url",
245
+ "og:audio",
246
+ "og:audio:secure_url",
247
+ "og:video",
248
+ "og:video:secure_url",
249
+ "vk:image"
250
+ ])
251
+ ],
252
+ [
253
+ "itemprop",
254
+ new Set([
255
+ "image",
256
+ "logo",
257
+ "screenshot",
258
+ "thumbnailurl",
259
+ "contenturl",
260
+ "downloadurl",
261
+ "duringmedia",
262
+ "embedurl",
263
+ "installurl",
264
+ "layoutimage"
265
+ ])
266
+ ]
267
+ ]);
268
+
269
+ /**
270
+ * @param {Map<string, string>} attributes attributes
271
+ * @returns {boolean} true when need to parse, otherwise false
272
+ */
273
+ const filterLinkItemprop = (attributes) => {
274
+ const itemprop = getAttributeValue(attributes, "itemprop");
275
+ if (!itemprop) return false;
276
+ const allowedAttributes = META.get("itemprop");
277
+ if (!allowedAttributes) return false;
278
+
279
+ return allowedAttributes.has(itemprop.trim().toLowerCase());
280
+ };
281
+
282
+ // `<link rel>` values whose `href`/`imagesrcset` webpack treats as a reference.
283
+ const ALLOWED_LINK_RELS = new Set([
284
+ "stylesheet",
285
+ "icon",
286
+ "mask-icon",
287
+ "apple-touch-icon",
288
+ "apple-touch-icon-precomposed",
289
+ "apple-touch-startup-image",
290
+ // Routed to the `asset/webmanifest` module type, which parses its icon URLs.
291
+ "manifest",
292
+ "prefetch",
293
+ "preload",
294
+ "modulepreload",
295
+ // Legacy preview-image hint (`<link rel="image_src" href>`)
296
+ "image_src"
297
+ ]);
298
+
299
+ /**
300
+ * @param {Map<string, string>} attributes attributes
301
+ * @returns {boolean} true when need to parse, otherwise false
302
+ */
303
+ const filterLinkHref = (attributes) => {
304
+ const rel = getAttributeValue(attributes, "rel");
305
+ if (!rel) return false;
306
+ const usedRels = rel.trim().toLowerCase().split(/\s+/);
307
+ for (let i = 0; i < usedRels.length; i++) {
308
+ if (ALLOWED_LINK_RELS.has(usedRels[i])) return true;
309
+ }
310
+ return false;
311
+ };
312
+
313
+ /**
314
+ * @param {Map<string, string>} attributes attributes
315
+ * @returns {boolean} true when need to parse, otherwise false
316
+ */
317
+ const filterLinkUnion = (attributes) =>
318
+ filterLinkHref(attributes) || filterLinkItemprop(attributes);
319
+
320
+ /**
321
+ * @param {Map<string, string>} attributes attributes
322
+ * @returns {boolean} true when need to parse, otherwise false
323
+ */
324
+ const filterMetaContent = (attributes) => {
325
+ for (const item of META) {
326
+ const [key, allowedNames] = item;
327
+ const name = getAttributeValue(attributes, key);
328
+ if (!name) continue;
329
+ // Check every present attribute, not only the first one
330
+ if (allowedNames.has(name.trim().toLowerCase())) return true;
331
+ }
332
+
333
+ return false;
334
+ };
335
+
336
+ /**
337
+ * `<param value>` (obsolete `<object>`/`<applet>` child) is only a URL when
338
+ * `valuetype="ref"`; otherwise it's an opaque string.
339
+ * @param {Map<string, string>} attributes attributes
340
+ * @returns {boolean} true when `value` is a URL reference
341
+ */
342
+ const filterParamRef = (attributes) => {
343
+ const valuetype = getAttributeValue(attributes, "valuetype");
344
+ if (!valuetype) return false;
345
+ return valuetype.trim().toLowerCase() === "ref";
346
+ };
347
+
348
+ /**
349
+ * @param {Map<string, string>} attributes attributes
350
+ * @returns {boolean} true when the script element opts into ES module semantics
351
+ */
352
+ const isModuleScript = (attributes) => {
353
+ const type = getAttributeValue(attributes, "type");
354
+ if (!type) return false;
355
+ return type.trim().toLowerCase() === "module";
356
+ };
357
+
358
+ // HTML `<script>` `type` values that the browser treats as executable
359
+ // JavaScript. Anything outside this set (e.g. `application/ld+json`,
360
+ // `importmap`, `application/wasm`) is a data block — webpack must not
361
+ // try to bundle it as a JS entry; it should pass through as an asset URL.
362
+ const JS_SCRIPT_TYPES = new Set([
363
+ "",
364
+ "module",
365
+ "text/javascript",
366
+ "application/javascript",
367
+ "text/ecmascript",
368
+ "application/ecmascript"
369
+ ]);
370
+
371
+ /**
372
+ * @param {Map<string, string>} attributes attributes
373
+ * @returns {boolean} true when the script element's `type` is executable JS
374
+ */
375
+ const isExecutableJsScript = (attributes) => {
376
+ const type = getAttributeValue(attributes, "type");
377
+ if (type === undefined) return true;
378
+ return JS_SCRIPT_TYPES.has(type.trim().toLowerCase());
379
+ };
380
+
381
+ /**
382
+ * @param {Map<string, string>} attributes attributes
383
+ * @returns {boolean} true when the link points at an ES module that should be bundled as an entry chunk
384
+ */
385
+ const isLinkModulePreload = (attributes) => {
386
+ const rel = getAttributeValue(attributes, "rel");
387
+ if (!rel) return false;
388
+ return rel.trim().toLowerCase().split(/\s+/).includes("modulepreload");
389
+ };
390
+
391
+ /**
392
+ * @param {Map<string, string>} attributes attributes
393
+ * @returns {boolean} true when the link is a `<link rel="stylesheet">` that should be bundled as a CSS entry chunk
394
+ */
395
+ const isLinkStylesheet = (attributes) => {
396
+ const rel = getAttributeValue(attributes, "rel");
397
+ if (!rel) return false;
398
+ return rel.trim().toLowerCase().split(/\s+/).includes("stylesheet");
399
+ };
400
+
401
+ /** @typedef {"src" | "srcset" | "css-url" | "msapplication-task" | "script" | "script-module" | "modulepreload" | "stylesheet" | "html" | "preload" | "prefetch" | "stylesheet-style" | "stylesheet-style-attribute" | "srcdoc"} SourceType */
402
+ /** Entry types: a `type` whose value is loaded as its own compilation entry chunk. */
403
+ /** @typedef {"script" | "script-module" | "modulepreload" | "stylesheet" | "html" | "preload" | "prefetch"} EntrySourceType */
404
+ /** @typedef {SourceType | ((attrs: Map<string, string>, css: boolean) => SourceType)} SourceTypeOrResolver */
405
+ /** @typedef {(attributes: Map<string, string>, value: string) => boolean} SourceFilter */
406
+ /** @typedef {{ tag?: string, attribute: string, type: SourceType, filter?: SourceFilter }} SourceEntry */
407
+ /** A `type` plus optional gates: `filter` (the decoded attribute map + the decoded value; return false to skip — covers both cross-attribute checks and cheap value checks) and `namespace` (restrict to an element namespace, e.g. SVG). */
408
+ /** @typedef {{ type: SourceTypeOrResolver, filter?: SourceFilter, namespace?: number }} SourceItem */
409
+ /** A tag→attribute lookup; a `undefined` value marks a built-in source disabled via `sources` (`type: false`). */
410
+ /** @typedef {Record<string, SourceItem | undefined>} SourceBucket */
411
+ /** @typedef {Record<string, SourceBucket>} SourceTable */
412
+ /** A source whose value is the element's text content (a `<style>`/`<script>` body) rather than an attribute. */
413
+ /** @typedef {{ type: SourceTypeOrResolver, filter?: (attributes: Map<string, string>) => boolean }} ContentSourceItem */
414
+
415
+ /**
416
+ * Builds a null-prototype dictionary from the given property bags
417
+ * (later bags win; `undefined` bags are skipped). A null prototype is
418
+ * essential here: the tables are indexed by HTML tag and attribute
419
+ * names, so a plain object would let names like `__proto__`,
420
+ * `constructor`, or `toString` resolve to inherited values at lookup
421
+ * time — producing bogus dependencies and letting `sources: false` be
422
+ * bypassed.
423
+ * @param {...(Record<string, EXPECTED_ANY> | undefined)} bags property bags
424
+ * @returns {EXPECTED_ANY} null-prototype dictionary
425
+ */
426
+ const dict = (...bags) => Object.assign(Object.create(null), ...bags);
427
+
428
+ // Shared `SourceItem` singletons used by the built-in defaults —
429
+ // keeping one instance per kind stabilizes V8's hidden classes across
430
+ // lookups in the walk. `srcset` is its own type; the walk picks the
431
+ // `parseSrcset` parser for it and otherwise treats it like `src`.
432
+ /** @type {SourceItem} */
433
+ const PLAIN_SRC = { type: "src", filter: undefined };
434
+ /** @type {SourceItem} */
435
+ const PLAIN_SRCSET = { type: "srcset", filter: undefined };
436
+
437
+ /**
438
+ * `<link href>` is polymorphic: `rel="modulepreload"` → an ESM
439
+ * preload entry, `rel="stylesheet"` (with `experiments.css`) → a CSS
440
+ * entry, otherwise a plain asset URL.
441
+ * @type {SourceItem}
442
+ */
443
+ const LINK_HREF = {
444
+ type: (attrs, css) => {
445
+ if (isLinkModulePreload(attrs)) return "modulepreload";
446
+ if (css && isLinkStylesheet(attrs)) return "stylesheet";
447
+ // `rel="preload"/"prefetch"` with `as="script"` (or `as="style"` when
448
+ // `experiments.css` is on) becomes a bundled, non-executing entry whose
449
+ // `href` is rewritten to the built chunk; other `as` targets (image,
450
+ // font, fetch, …) stay plain asset URLs.
451
+ const rel = getAttributeValue(attrs, "rel");
452
+ if (rel) {
453
+ const rels = rel.trim().toLowerCase().split(/\s+/);
454
+ const kind = rels.includes("preload")
455
+ ? "preload"
456
+ : rels.includes("prefetch")
457
+ ? "prefetch"
458
+ : undefined;
459
+ if (kind) {
460
+ const as = getAttributeValue(attrs, "as");
461
+ const asLower = as ? as.trim().toLowerCase() : "";
462
+ if (asLower === "script" || (css && asLower === "style")) return kind;
463
+ }
464
+ }
465
+ return "src";
466
+ },
467
+ filter: filterLinkUnion
468
+ };
469
+
470
+ /**
471
+ * `<script src>`: non-JS types (e.g. `application/ld+json`,
472
+ * `importmap`) stay plain asset URLs so the browser keeps seeing them
473
+ * as data blocks; `type="module"` opts into the ESM entry chunk;
474
+ * everything else in `JS_SCRIPT_TYPES` is a classic script.
475
+ * @type {SourceItem}
476
+ */
477
+ const SCRIPT_SRC = {
478
+ type: (attrs) =>
479
+ isExecutableJsScript(attrs)
480
+ ? isModuleScript(attrs)
481
+ ? "script-module"
482
+ : "script"
483
+ : "src",
484
+ filter: undefined
485
+ };
486
+
487
+ /**
488
+ * `<meta content>`: most referenced names hold a single URL (`src`); the
489
+ * `msapplication-task` value is a `;`-delimited list whose `icon-uri` part
490
+ * is the only asset, so it selects the `msapplication-task` parser.
491
+ * @type {SourceItem}
492
+ */
493
+ const META_CONTENT = {
494
+ type: (attrs) => {
495
+ const name = attrs.get("name");
496
+ return name !== undefined &&
497
+ name.trim().toLowerCase() === "msapplication-task"
498
+ ? "msapplication-task"
499
+ : "src";
500
+ },
501
+ filter: filterMetaContent
502
+ };
503
+
504
+ // Built-in lookup table, written directly in its final resolved shape:
505
+ // `DEFAULT_SOURCES_BY_TAG[tag][attribute] = item`. No module-load
506
+ // loop, no separate array representation — every parser created with
507
+ // the default `sources` config just references this table and pays
508
+ // zero per-parser work.
509
+ /** @type {Record<string, Record<string, SourceItem>>} */
510
+ const DEFAULT_SOURCES_BY_TAG = dict({
511
+ // Obsolete Java-applet element; `code`/`object` are single class/object URLs.
512
+ applet: dict({ code: PLAIN_SRC, object: PLAIN_SRC }),
513
+ audio: dict({ src: PLAIN_SRC }),
514
+ // Deprecated presentational `background` attribute — an image URL.
515
+ body: dict({ background: PLAIN_SRC }),
516
+ embed: dict({ src: PLAIN_SRC }),
517
+ // `srcdoc` is an entity-encoded HTML document parsed and rewritten as a
518
+ // nested module — its handling lives in the generic source loop so the
519
+ // `sources` option can re-target it (or other tags/attributes) freely.
520
+ iframe: dict({ srcdoc: { type: "srcdoc", filter: undefined } }),
521
+ img: dict({ src: PLAIN_SRC, srcset: PLAIN_SRCSET }),
522
+ input: dict({ src: PLAIN_SRC }),
523
+ link: dict({
524
+ href: LINK_HREF,
525
+ imagesrcset: { type: "srcset", filter: filterLinkHref }
526
+ }),
527
+ meta: dict({ content: META_CONTENT }),
528
+ // MathML `<mglyph src>` references an image.
529
+ mglyph: dict({ src: PLAIN_SRC }),
530
+ // `classid` is a single object URI (`codebase`/`archive` are a base/list, skipped).
531
+ object: dict({ data: PLAIN_SRC, classid: PLAIN_SRC }),
532
+ // Obsolete `<param valuetype="ref" value="url">` child of `<object>`.
533
+ param: dict({ value: { type: "src", filter: filterParamRef } }),
534
+ // `href`/`xlink:href` reference the source of SVG `<script>` elements
535
+ script: dict({
536
+ src: SCRIPT_SRC,
537
+ href: SCRIPT_SRC,
538
+ "xlink:href": SCRIPT_SRC
539
+ }),
540
+ source: dict({ src: PLAIN_SRC, srcset: PLAIN_SRCSET }),
541
+ // Deprecated presentational `background` attribute — an image URL.
542
+ table: dict({ background: PLAIN_SRC }),
543
+ td: dict({ background: PLAIN_SRC }),
544
+ th: dict({ background: PLAIN_SRC }),
545
+ track: dict({ src: PLAIN_SRC }),
546
+ video: dict({ poster: PLAIN_SRC, src: PLAIN_SRC }),
547
+ // SVG. Tag names match the tree builder's adjusted camelCase
548
+ // (`feImage`/`textPath`/`linearGradient`/`radialGradient`). `href`/
549
+ // `xlink:href` reference another element/resource; fragment-only `#id`
550
+ // values are left untouched, so only external `file.svg#id` is rewritten.
551
+ // `color-profile`'s `xlink:href` points at an external ICC profile file.
552
+ // `cursor`/`font-face-uri` point at an external image/font file; `altGlyph`/
553
+ // `glyphRef`/`tref` are legacy element references (removed in SVG 2).
554
+ altGlyph: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
555
+ "color-profile": dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
556
+ cursor: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
557
+ feImage: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
558
+ filter: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
559
+ "font-face-uri": dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
560
+ glyphRef: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
561
+ image: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
562
+ linearGradient: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
563
+ mpath: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
564
+ pattern: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
565
+ radialGradient: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
566
+ textPath: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
567
+ tref: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC }),
568
+ use: dict({ "xlink:href": PLAIN_SRC, href: PLAIN_SRC })
569
+ // CSS `url(...)` references in SVG presentation attributes (fill, stroke,
570
+ // clip-path, …) are handled separately during the walk (`parseCssUrls`).
571
+ });
572
+
573
+ // SVG presentation attributes (`fill`, `stroke`, …) carry CSS `url(...)`
574
+ // FuncIRIs; `parseCssUrls` extracts external refs as assets (internal
575
+ // `url(#id)` is left untouched). They apply to every SVG-namespace element, so
576
+ // the item is `namespace`-gated rather than placed in a tag bucket. The filter
577
+ // is a cheap pre-check skipping the common plain values (`red`, `none`, `#fff`).
578
+ /** @type {SourceItem} */
579
+ const SVG_CSS_URL = {
580
+ type: "css-url",
581
+ filter: (attributes, value) => FUNC_IRI_URL_REGEXP.test(value),
582
+ namespace: NS_SVG
583
+ };
584
+
585
+ // The global `style=""` attribute (a CSS declaration list), available on every
586
+ // tag and even with `sources: false`. Like every `stylesheet-style*` source it
587
+ // only emits when `experiments.css` is on (checked where the dependency is
588
+ // created); the filter is a cheap pre-check skipping declarations without a
589
+ // `url()`/`src()`/… .
590
+ /** @type {SourceItem} */
591
+ const STYLE_ATTRIBUTE = {
592
+ type: "stylesheet-style-attribute",
593
+ filter: (attributes, value) => STYLE_ATTR_URL_REGEXP.test(value)
594
+ };
595
+
596
+ // Any-tag sources — applied to every element as a fallback and folded into
597
+ // each tag bucket, so the walk resolves one object per element and reads one
598
+ // property per attribute. `DEFAULT` (svg presentation + style) is active
599
+ // unless `sources: false`; only the always-on style attribute survives `false`.
600
+ /** @type {Record<string, SourceItem>} */
601
+ const DEFAULT_ANY_SOURCES = dict({ style: STYLE_ATTRIBUTE });
602
+ for (const name of [
603
+ "fill",
604
+ "stroke",
605
+ "clip-path",
606
+ "mask",
607
+ "filter",
608
+ "marker",
609
+ "marker-start",
610
+ "marker-mid",
611
+ "marker-end",
612
+ "cursor"
613
+ ]) {
614
+ DEFAULT_ANY_SOURCES[name] = SVG_CSS_URL;
615
+ }
616
+ /** @type {Record<string, SourceItem>} */
617
+ const ALWAYS_ANY_SOURCES = dict({ style: STYLE_ATTRIBUTE });
618
+
619
+ // Reserved key holding the any-tag sources inside the per-tag table — the
620
+ // schema forbids an empty `tag`, so it never collides with a real tag. The
621
+ // walk falls back to it for elements without their own bucket.
622
+ const ANY_TAG = "";
623
+
624
+ /**
625
+ * Folds the any-tag sources into every per-tag bucket (tag-specific entries
626
+ * win) and stores them under `ANY_TAG`, so the whole source model is one
627
+ * object and the walk's per-attribute lookup is a single property read.
628
+ * @param {SourceTable} byTag per-tag sources
629
+ * @param {SourceBucket} any any-tag sources
630
+ * @returns {SourceTable} folded table
631
+ */
632
+ const foldAnySources = (byTag, any) => {
633
+ for (const tag of Object.keys(byTag)) {
634
+ byTag[tag] = dict(any, byTag[tag]);
635
+ }
636
+ byTag[ANY_TAG] = any;
637
+ return byTag;
638
+ };
639
+
640
+ // Default table (per-tag defaults + any-tag sources folded in) and the
641
+ // `sources: false` table (only the always-on `style=""` attribute). Both are
642
+ // precomputed so the common cases reference them with zero per-parser work.
643
+ /** @type {SourceTable} */
644
+ const DEFAULT_SOURCES_FOLDED = foldAnySources(
645
+ dict(DEFAULT_SOURCES_BY_TAG),
646
+ DEFAULT_ANY_SOURCES
647
+ );
648
+ /** @type {SourceTable} */
649
+ const DISABLED_SOURCES_FOLDED = foldAnySources(dict(), ALWAYS_ANY_SOURCES);
650
+
651
+ /**
652
+ * Inline `<script>` body: classic JS unless `type="module"` opts into ESM.
653
+ * @param {Map<string, string>} attrs attributes
654
+ * @returns {SourceType} the entry type for the inline script
655
+ */
656
+ const scriptContentType = (attrs) =>
657
+ isModuleScript(attrs) ? "script-module" : "script";
658
+
659
+ /**
660
+ * Inline `<script>` body: only an executable JS block with no external source
661
+ * carries content webpack should bundle.
662
+ * @param {Map<string, string>} attrs attributes
663
+ * @returns {boolean} true when the inline body should be bundled
664
+ */
665
+ const scriptContentFilter = (attrs) =>
666
+ !attrs.has("src") &&
667
+ !attrs.has("href") &&
668
+ !attrs.has("xlink:href") &&
669
+ isExecutableJsScript(attrs);
670
+
671
+ /**
672
+ * `<style>` body is a stylesheet only when its `type` is empty or `text/css`.
673
+ * @param {Map<string, string>} attrs attributes
674
+ * @returns {boolean} true when the body is CSS
675
+ */
676
+ const styleContentFilter = (attrs) => {
677
+ const type = attrs.get("type");
678
+ if (type === undefined) return true;
679
+ const t = type.trim().toLowerCase();
680
+ return t === "" || t === "text/css";
681
+ };
682
+
683
+ // Element-body sources, independent of the `sources` option (even `sources:
684
+ // false`): inline `<script>` bodies are always processed; the `<style>` body
685
+ // only emits when `experiments.css` is on (checked where the dependency is
686
+ // created, like every `stylesheet-style*` source).
687
+ /** @type {Record<string, ContentSourceItem>} */
688
+ const CONTENT_SOURCES = dict({
689
+ script: { type: scriptContentType, filter: scriptContentFilter },
690
+ style: { type: "stylesheet-style", filter: styleContentFilter }
691
+ });
692
+
693
+ class HtmlParser extends Parser {
694
+ /**
695
+ * Creates an instance of HtmlParser.
696
+ * @param {HtmlParserOptions} options parser options (from `module.parser.html`; always passed by the `createParser` hook)
697
+ */
698
+ constructor(options) {
699
+ super();
700
+ this.magicCommentContext = createMagicCommentContext();
701
+ // Read by HtmlModulesPlugin's `processResult` hook, which transforms
702
+ // the module source before it is stored and parsed.
703
+ /** @type {HtmlTemplateFunction | undefined} */
704
+ this.template = options.template;
705
+ /** @type {import("../../declarations/WebpackOptions").UrlHintRule[] | undefined} */
706
+ this._urlHints = options.urlHints;
707
+ // `as` selects the parse mode — the HTML analog of the CSS parser's `as`.
708
+ // `"document"` (default) parses a full page; any other value is the
709
+ // context element whose inner HTML the source is parsed as (a fragment),
710
+ // so context-sensitive tags (`<tr>`, `<td>`, `<option>`, …) in a partial
711
+ // are kept, not dropped. `"template"` is the neutral generic fragment.
712
+ /** @type {string | undefined} */
713
+ this.fragmentContext =
714
+ options.as === undefined || options.as === "document"
715
+ ? undefined
716
+ : options.as;
717
+ // One source model: a per-tag table that also holds the any-tag sources
718
+ // under `ANY_TAG`. The common cases reference precomputed tables.
719
+ /** @type {SourceTable} */
720
+ this.sourcesByTag = DEFAULT_SOURCES_FOLDED;
721
+
722
+ const sources = options.sources;
723
+ if (sources === undefined || sources === true) return;
724
+ if (sources === false) {
725
+ // Only the always-on `style=""` attribute survives; nothing else is
726
+ // extracted (svg presentation, `<script src>`, `<link>` entries, …).
727
+ this.sourcesByTag = DISABLED_SOURCES_FOLDED;
728
+ return;
729
+ }
730
+
731
+ // User array — `"..."` anywhere opts the per-tag defaults in as the
732
+ // base; the built-in any-tag sources (svg presentation + style) are
733
+ // always present. A user entry with no `tag` is an any-tag source (e.g.
734
+ // `{ attribute: "data-style", type: "stylesheet-style-attribute" }`).
735
+ // User entries override regardless of position. `dict()` keeps every
736
+ // table null-prototype (see its doc), and per-tag writes rebuild the
737
+ // bucket so the aliased default buckets stay intact.
738
+ /** @type {SourceTable} */
739
+ const byTag = sources.includes("...")
740
+ ? dict(DEFAULT_SOURCES_BY_TAG)
741
+ : dict();
742
+ /** @type {SourceBucket} */
743
+ const any = dict(DEFAULT_ANY_SOURCES);
744
+ for (const entry of sources) {
745
+ if (entry === "...") continue;
746
+ // `type: false` disables a built-in source: writing `undefined` over the
747
+ // attribute makes the walk's `sources[name]` lookup skip it (see below).
748
+ /** @type {SourceItem | undefined} */
749
+ const item =
750
+ entry.type === false
751
+ ? undefined
752
+ : {
753
+ type: entry.type,
754
+ filter:
755
+ typeof entry.filter === "function" ? entry.filter : undefined
756
+ };
757
+ const attr = entry.attribute.toLowerCase();
758
+ if (entry.tag === undefined) {
759
+ any[attr] = item;
760
+ } else {
761
+ const tag = entry.tag.toLowerCase();
762
+ byTag[tag] = dict(byTag[tag], { [attr]: item });
763
+ // The AST carries adjusted camelCase names for foreign-content
764
+ // tags (e.g. `feImage`) — register the entry under both.
765
+ const adjusted = SVG_TAG_ADJUST[tag];
766
+ if (adjusted !== undefined) {
767
+ byTag[adjusted] = dict(byTag[adjusted], { [attr]: item });
768
+ }
769
+ }
770
+ }
771
+ /** @type {SourceTable} */
772
+ this.sourcesByTag = foldAnySources(byTag, any);
773
+ }
774
+
775
+ /**
776
+ * Runs the `template` option over the source and returns the transformed
777
+ * html. Called from HtmlModulesPlugin's `processResult`, where the return
778
+ * value becomes the module's stored source so the parser (which records
779
+ * dependency offsets against it) and the generator (which renders from
780
+ * `module.originalSource()`) stay in agreement.
781
+ * @param {string | Buffer} source the original source
782
+ * @param {NormalModule} module the html module
783
+ * @returns {string | Buffer} the transformed source
784
+ */
785
+ applyTemplate(source, module) {
786
+ if (!this.template) return source;
787
+ // `processResult` runs after `_doBuild` has initialized these
788
+ // dependency sets, so they are always present here.
789
+ const buildInfo = /** @type {BuildInfo} */ (module.buildInfo);
790
+ const fileDependencies = /** @type {FileSystemDependencies} */ (
791
+ buildInfo.fileDependencies
792
+ );
793
+ const contextDependencies = /** @type {FileSystemDependencies} */ (
794
+ buildInfo.contextDependencies
795
+ );
796
+ const missingDependencies = /** @type {FileSystemDependencies} */ (
797
+ buildInfo.missingDependencies
798
+ );
799
+ const transformed = this.template(
800
+ typeof source === "string" ? source : source.toString("utf8"),
801
+ {
802
+ module,
803
+ resource: module.resource,
804
+ addDependency: (dependency) => {
805
+ fileDependencies.add(dependency);
806
+ },
807
+ addContextDependency: (dependency) => {
808
+ contextDependencies.add(dependency);
809
+ },
810
+ addMissingDependency: (dependency) => {
811
+ missingDependencies.add(dependency);
812
+ },
813
+ addBuildDependency: (dependency) => {
814
+ if (buildInfo.buildDependencies === undefined) {
815
+ buildInfo.buildDependencies = new LazySet();
816
+ }
817
+ buildInfo.buildDependencies.add(dependency);
818
+ },
819
+ emitWarning: (warning) =>
820
+ module.addWarning(
821
+ warning instanceof Error ? warning : new WebpackError(warning)
822
+ ),
823
+ emitError: (error) =>
824
+ module.addError(
825
+ error instanceof Error ? error : new WebpackError(error)
826
+ )
827
+ }
828
+ );
829
+ if (typeof transformed !== "string") {
830
+ throw new Error(
831
+ "The `template` html parser option must return a string."
832
+ );
833
+ }
834
+ return transformed;
835
+ }
836
+
837
+ /**
838
+ * Parses the provided source and updates the parser state.
839
+ * @param {string | Buffer | PreparsedAst} source the source to parse
840
+ * @param {ParserState} state the parser state
841
+ * @returns {ParserState} the parser state
842
+ */
843
+ parse(source, state) {
844
+ if (Buffer.isBuffer(source)) {
845
+ source = source.toString("utf8");
846
+ } else if (typeof source === "object") {
847
+ throw new Error("webpackAst is unexpected for the HtmlParser");
848
+ }
849
+ if (source[0] === "\uFEFF") {
850
+ source = source.slice(1);
851
+ }
852
+
853
+ const locConverter = new LocConverter(source);
854
+
855
+ const module = state.module;
856
+ const compilation = state.compilation;
857
+ const { hashFunction, module: outputModule } = compilation.outputOptions;
858
+ const context = compilation.compiler.context;
859
+ const css = Boolean(compilation.options.experiments.css);
860
+ const urlHints = this._urlHints;
861
+
862
+ // Stable, per-HTML-module prefix used when generating entry names for
863
+ // script src / modulepreload references so they don't collide across
864
+ // HTML modules in the same compilation. We hash the module's resource
865
+ // path (a plain absolute path) — going through `contextify` against
866
+ // the compilation root keeps the hash machine-stable for the same
867
+ // project layout. Note: `module.identifier()` returns `html|<path>`
868
+ // for HTML modules, which doesn't start with `/`, so contextify would
869
+ // leave it absolute. `module.resource` is the bare path.
870
+ /** @type {string} */
871
+ const resource =
872
+ /** @type {EXPECTED_ANY} */ (module).resource || module.identifier();
873
+ const moduleHash = createHash(hashFunction || "md4")
874
+ .update(context ? contextify(context, resource) : resource)
875
+ .digest("hex")
876
+ .slice(0, 8);
877
+
878
+ // `output.html` head injection: facts are collected during the walk and
879
+ // become presentational dependencies afterwards — no later asset pass has
880
+ // to re-parse the page. `data:` documents are skipped: synthetic entry
881
+ // wrappers already carry the tags and iframe srcdoc pages must stay
882
+ // untouched.
883
+ const htmlOutputOptions =
884
+ compilation.options && compilation.options.output
885
+ ? compilation.options.output.html
886
+ : undefined;
887
+ const headOptions =
888
+ typeof htmlOutputOptions === "object" &&
889
+ (htmlOutputOptions.title !== undefined ||
890
+ htmlOutputOptions.meta !== undefined ||
891
+ htmlOutputOptions.base !== undefined) &&
892
+ !resource.startsWith("data:")
893
+ ? htmlOutputOptions
894
+ : undefined;
895
+ let doctypeEnd = -1;
896
+ let htmlTagEnd = -1;
897
+ // insertion offsets just inside the (possibly implicit) head
898
+ let headStart = 0;
899
+ let headLastEnd = 0;
900
+ let headSeen = false;
901
+ let inHead = false;
902
+ // `<template>` contents are inert
903
+ let headTemplateDepth = 0;
904
+ // Depth of open `<template>` elements anywhere in the tree. Template
905
+ // content is an inert, separate fragment per spec, so a `<base>` inside
906
+ // it must NOT set the document base (`headTemplateDepth` only covers
907
+ // templates seen while in `<head>`, so it can't guard body templates).
908
+ let templateDepth = 0;
909
+ let headHasTitle = false;
910
+ let headHasBase = false;
911
+ let headCharsetEnd = -1;
912
+ /** @type {Set<string> | undefined} */
913
+ let headMetaNames;
914
+
915
+ // Script src / modulepreload references are collected per-type
916
+ // during the walk; HtmlModulesPlugin later turns them into real
917
+ // entries. `script` and `script-module` entries are chained via a
918
+ // leader-only dependOn so they share a runtime.
919
+ // `<link rel="modulepreload">` entries are kept independent — they
920
+ // must preload without running, so they can never become a runtime
921
+ // leader that other entries would import.
922
+ /**
923
+ * @typedef {object} HtmlEntryInfo
924
+ * @property {string} request
925
+ * @property {string} entryName
926
+ * @property {"script" | "script-module" | "modulepreload" | "stylesheet" | "html" | "preload" | "prefetch"} type
927
+ * @property {boolean=} css entry emits a CSS chunk (`<link rel="preload" as="style">`), so it needs the CSS filename template
928
+ */
929
+ /** @type {HtmlEntryInfo[]} */
930
+ const scriptEntries = [];
931
+ /** @type {HtmlEntryInfo[]} */
932
+ const scriptModuleEntries = [];
933
+ /** @type {HtmlEntryInfo[]} */
934
+ const modulePreloadEntries = [];
935
+ /** @type {HtmlEntryInfo[]} */
936
+ const stylesheetEntries = [];
937
+ // `type: "html"` links — each referenced `.html` becomes its own page
938
+ // entry (`<a href="page.html">`), independent (no dependOn).
939
+ /** @type {HtmlEntryInfo[]} */
940
+ const htmlLinkEntries = [];
941
+ // `<link rel="preload"/"prefetch">` of a bundled resource: each becomes an
942
+ // independent, non-executing entry whose `href` is rewritten to the built
943
+ // chunk's URL (JS for `as="script"`, CSS for `as="style"`).
944
+ /** @type {HtmlEntryInfo[]} */
945
+ const preloadEntries = [];
946
+ /** @type {HtmlEntryInfo[]} */
947
+ const prefetchEntries = [];
948
+
949
+ // Offset of the first classic blocking script tag; injected stylesheet
950
+ // `<link>`s stay ahead of it. `defer`/`async`/module scripts don't
951
+ // anchor — they execute after parsing (and after pending stylesheets),
952
+ // so CSS may follow their tags (the order Vite emits).
953
+ let firstBlockingScriptStart = -1;
954
+
955
+ let nextEntryIndex = 0;
956
+
957
+ // `<base href>` resolves the relative URLs that follow it. A relative base
958
+ // (`./assets/`) rewrites them into a subdirectory — still bundled; a
959
+ // root-relative or absolute base (`/`, `https://cdn/`) points them outside
960
+ // the build, so those URLs are left untouched. Resolved in the walk below
961
+ // from the first `<base href>` seen (`documentBase` undefined until then).
962
+ /** @type {string | undefined} */
963
+ let documentBase;
964
+ /** @type {string | undefined} */
965
+ let baseDir;
966
+ let baseIsExternal = false;
967
+ // Prepended to the emitted URLs' auto-public-path undo path so the base
968
+ // doesn't misdirect them: the browser resolves rewritten (relative)
969
+ // output URLs against the base dir, so one `../` per base segment cancels
970
+ // it. Undefined for absolute publicPath (no undo path is emitted).
971
+ /** @type {string | undefined} */
972
+ let baseUrlPrefix;
973
+
974
+ /**
975
+ * Tracks the `webpackIgnore` value from the most recent comment that
976
+ * appears before the next tag. Reset whenever a tag is emitted or a
977
+ * comment without a `webpackIgnore` value is encountered.
978
+ * @type {boolean | undefined}
979
+ */
980
+ let pendingWebpackIgnore;
981
+ /** @type {boolean | undefined} */
982
+ let pendingWebpackInline;
983
+ /**
984
+ * Tracks the resource-hint values from the most recent `<!-- webpackPrefetch: … -->`
985
+ * (etc.) comment so the next asset URL attribute picks them up.
986
+ * @type {import("../prefetch/parseResourceHintOptions").ResourceHintOptions | undefined}
987
+ */
988
+ let pendingHints;
989
+
990
+ const magicCommentContext = this.magicCommentContext;
991
+
992
+ /**
993
+ * @param {import("./syntax").HtmlPath} path walk path (used only for attribute-ref reads)
994
+ * @param {import("./syntax").HtmlAttributeRef} typeAttr type attribute ref (0 = none)
995
+ * @param {number} nameEnd end offset of the tag name
996
+ * @param {string} type type of the script
997
+ * @param {string} input source string
998
+ */
999
+ const reconcileScriptTypeAttr = (path, typeAttr, nameEnd, type, input) => {
1000
+ const valueStart =
1001
+ typeAttr !== 0 ? path.attributeValueStart(typeAttr) : -1;
1002
+ const valueEnd = typeAttr !== 0 ? path.attributeValueEnd(typeAttr) : -1;
1003
+ if (outputModule && type === "script") {
1004
+ // Chunk is an ES module; upgrade the tag.
1005
+ if (typeAttr !== 0 && valueStart !== -1) {
1006
+ module.addPresentationalDependency(
1007
+ new ConstDependency("module", [valueStart, valueEnd])
1008
+ );
1009
+ } else {
1010
+ module.addPresentationalDependency(
1011
+ new ConstDependency(' type="module"', nameEnd)
1012
+ );
1013
+ }
1014
+ } else if (!outputModule && type === "script-module" && typeAttr !== 0) {
1015
+ // Chunk is a classic IIFE; drop `type="module"` so the
1016
+ // browser doesn't load it under module semantics.
1017
+ let attrEnd;
1018
+ if (valueStart === -1) {
1019
+ attrEnd = path.attributeNameEnd(typeAttr);
1020
+ } else if (input[valueEnd] === '"' || input[valueEnd] === "'") {
1021
+ attrEnd = valueEnd + 1;
1022
+ } else {
1023
+ attrEnd = valueEnd;
1024
+ }
1025
+ let attrStart = path.attributeNameStart(typeAttr);
1026
+ if (
1027
+ attrStart > 0 &&
1028
+ isAsciiWhitespace(input.charCodeAt(attrStart - 1))
1029
+ ) {
1030
+ attrStart -= 1;
1031
+ }
1032
+ module.addPresentationalDependency(
1033
+ new ConstDependency("", [attrStart, attrEnd])
1034
+ );
1035
+ }
1036
+ };
1037
+
1038
+ /**
1039
+ * @param {string} mime mime type
1040
+ * @param {string} text inline text
1041
+ * @returns {string} a `data:` request for the text
1042
+ */
1043
+ const dataUri = (mime, text) =>
1044
+ `data:${mime};base64,${Buffer.from(text, "utf8").toString("base64")}`;
1045
+
1046
+ /**
1047
+ * @param {ConstDependency | HtmlSourceDependency | HtmlEntryDependency | HtmlInlineStyleDependency | HtmlInlineScriptDependency | HtmlInlineHtmlDependency} dep dependency
1048
+ * @param {number} start raw start offset
1049
+ * @param {number} end raw end offset
1050
+ */
1051
+ const setLoc = (dep, start, end) => {
1052
+ const s = locConverter.get(start);
1053
+ const e = locConverter.get(end);
1054
+ dep.setLoc(s.line, s.column, e.line, e.column);
1055
+ };
1056
+
1057
+ /**
1058
+ * Classifies the first `<base href>` seen in the walk, setting
1059
+ * `documentBase`/`baseDir`/`baseIsExternal`/`baseUrlPrefix` for the URLs
1060
+ * that follow it.
1061
+ * @param {import("./syntax").HtmlPath} path walk path (for attribute reads)
1062
+ * @param {import("./syntax").HtmlAttributeRef} hrefAttr the base's href attribute
1063
+ */
1064
+ const resolveDocumentBase = (path, hrefAttr) => {
1065
+ documentBase = decodeEntities(path.attributeValue(hrefAttr), true).trim();
1066
+ if (!documentBase) return;
1067
+ if (
1068
+ ABSOLUTE_URL_SCHEME_REGEXP.test(documentBase) ||
1069
+ documentBase.charCodeAt(0) === CC_SLASH
1070
+ ) {
1071
+ baseIsExternal = true;
1072
+ return;
1073
+ }
1074
+ // Normalize the base path into its descending directory segments,
1075
+ // resolving `.`/`..` like the URL spec. The final segment is the
1076
+ // referenced file (dropped) unless the href ends with `/` or a
1077
+ // dot-segment; `up` counts `..`s that climb above the document dir.
1078
+ const parts = documentBase.split("/");
1079
+ /** @type {string[]} */
1080
+ const dirs = [];
1081
+ let up = 0;
1082
+ for (let i = 0; i < parts.length; i++) {
1083
+ const part = parts[i];
1084
+ if (part === "" || part === ".") continue;
1085
+ if (part === "..") {
1086
+ if (dirs.length > 0) dirs.pop();
1087
+ else up++;
1088
+ continue;
1089
+ }
1090
+ // A trailing plain segment (no following `/`) is the file, not a dir.
1091
+ if (i === parts.length - 1) continue;
1092
+ dirs.push(part);
1093
+ }
1094
+ baseDir = `${"../".repeat(up)}${dirs.length > 0 ? `${dirs.join("/")}/` : ""}`;
1095
+ // A base above the document dir can't be cancelled with `../` (the
1096
+ // document's own dir name is unknown) — leave the output URLs
1097
+ // un-prefixed; they still resolve under an absolute publicPath.
1098
+ if (up === 0 && dirs.length > 0) {
1099
+ baseUrlPrefix = "../".repeat(dirs.length);
1100
+ }
1101
+ };
1102
+
1103
+ // Lazy decoded-attribute map for the current element — parse-scoped
1104
+ // to avoid a closure and memo slot per element.
1105
+ /** @type {import("./syntax").HtmlPath | undefined} */
1106
+ let attrMapPath;
1107
+ let attrMapCount = 0;
1108
+ /** @type {Map<string, string> | undefined} */
1109
+ let currentAttributesMap;
1110
+ const getAttributesMap = () => {
1111
+ if (currentAttributesMap) return currentAttributesMap;
1112
+ currentAttributesMap = new Map();
1113
+ const path = /** @type {import("./syntax").HtmlPath} */ (attrMapPath);
1114
+ for (let i = 0; i < attrMapCount; i++) {
1115
+ const attr = path.attributeAt(i);
1116
+ // Decoded values — filters and type resolvers compare what
1117
+ // the browser sees (e.g. `rel="&#105;con"` means `icon`)
1118
+ currentAttributesMap.set(
1119
+ path.attributeName(attr),
1120
+ decodeEntities(path.attributeValue(attr), true)
1121
+ );
1122
+ }
1123
+ return currentAttributesMap;
1124
+ };
1125
+
1126
+ // TODO implement full HTML parser (WASM)
1127
+ // The walker descends into children (and `<template>` content) itself;
1128
+ // the Element `exit` clears a pending `webpackIgnore` once an element's
1129
+ // children are done (the old `walkChildren` behaviour).
1130
+ new SourceProcessor()
1131
+ .use({
1132
+ [NodeType.Comment]: (path) => {
1133
+ const start = path.start();
1134
+ const end = path.end();
1135
+ // comments count toward the head-end insertion anchor
1136
+ if (inHead && headTemplateDepth === 0 && end > headLastEnd) {
1137
+ headLastEnd = end;
1138
+ }
1139
+ // Only proper `<!-- ... -->` comments carry magic comments.
1140
+ if (
1141
+ end - start < 7 ||
1142
+ source.charCodeAt(start) !== 0x3c ||
1143
+ source.charCodeAt(start + 1) !== 0x21 ||
1144
+ source.charCodeAt(start + 2) !== 0x2d ||
1145
+ source.charCodeAt(start + 3) !== 0x2d ||
1146
+ source.charCodeAt(end - 1) !== 0x3e ||
1147
+ source.charCodeAt(end - 2) !== 0x2d ||
1148
+ source.charCodeAt(end - 3) !== 0x2d
1149
+ ) {
1150
+ pendingWebpackIgnore = undefined;
1151
+ pendingWebpackInline = undefined;
1152
+ pendingHints = undefined;
1153
+ return;
1154
+ }
1155
+ const value = path.data();
1156
+ if (!webpackCommentRegExp.test(value)) {
1157
+ pendingWebpackIgnore = undefined;
1158
+ pendingWebpackInline = undefined;
1159
+ pendingHints = undefined;
1160
+ return;
1161
+ }
1162
+ /** @type {Record<string, EXPECTED_ANY>} */
1163
+ let options;
1164
+ try {
1165
+ options = parseMagicComment(value, magicCommentContext);
1166
+ } catch (err) {
1167
+ const { line: sl, column: sc } = locConverter.get(start);
1168
+ const { line: el, column: ec } = locConverter.get(end);
1169
+ module.addWarning(
1170
+ new CommentCompilationWarning(
1171
+ `Compilation error while processing magic comment(-s): /*${value}*/: ${
1172
+ /** @type {Error} */ (err).message
1173
+ }`,
1174
+ {
1175
+ start: { line: sl, column: sc },
1176
+ end: { line: el, column: ec }
1177
+ }
1178
+ )
1179
+ );
1180
+ pendingWebpackIgnore = undefined;
1181
+ pendingWebpackInline = undefined;
1182
+ pendingHints = undefined;
1183
+ return;
1184
+ }
1185
+ if (
1186
+ options.webpackIgnore === undefined &&
1187
+ options.webpackInline === undefined &&
1188
+ options.webpackPrefetch === undefined &&
1189
+ options.webpackPreload === undefined &&
1190
+ options.webpackFetchPriority === undefined
1191
+ ) {
1192
+ pendingWebpackIgnore = undefined;
1193
+ pendingWebpackInline = undefined;
1194
+ pendingHints = undefined;
1195
+ return;
1196
+ }
1197
+ if (
1198
+ options.webpackIgnore !== undefined &&
1199
+ typeof options.webpackIgnore !== "boolean"
1200
+ ) {
1201
+ const { line: sl, column: sc } = locConverter.get(start);
1202
+ const { line: el, column: ec } = locConverter.get(end);
1203
+ module.addWarning(
1204
+ new UnsupportedFeatureWarning(
1205
+ `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`,
1206
+ {
1207
+ start: { line: sl, column: sc },
1208
+ end: { line: el, column: ec }
1209
+ }
1210
+ )
1211
+ );
1212
+ pendingWebpackIgnore = undefined;
1213
+ pendingWebpackInline = undefined;
1214
+ pendingHints = undefined;
1215
+ return;
1216
+ }
1217
+ if (
1218
+ options.webpackInline !== undefined &&
1219
+ typeof options.webpackInline !== "boolean"
1220
+ ) {
1221
+ const { line: sl, column: sc } = locConverter.get(start);
1222
+ const { line: el, column: ec } = locConverter.get(end);
1223
+ module.addWarning(
1224
+ new UnsupportedFeatureWarning(
1225
+ `\`webpackInline\` expected a boolean, but received: ${options.webpackInline}.`,
1226
+ {
1227
+ start: { line: sl, column: sc },
1228
+ end: { line: el, column: ec }
1229
+ }
1230
+ )
1231
+ );
1232
+ pendingWebpackIgnore = undefined;
1233
+ pendingWebpackInline = undefined;
1234
+ pendingHints = undefined;
1235
+ return;
1236
+ }
1237
+ pendingWebpackIgnore = options.webpackIgnore;
1238
+ pendingWebpackInline = options.webpackInline;
1239
+ if (
1240
+ options.webpackPrefetch !== undefined ||
1241
+ options.webpackPreload !== undefined ||
1242
+ options.webpackFetchPriority !== undefined
1243
+ ) {
1244
+ const s = locConverter.get(start);
1245
+ const e = locConverter.get(end);
1246
+ const parsedHints = parseResourceHintOptions(options, module, {
1247
+ start: { line: s.line, column: s.column },
1248
+ end: { line: e.line, column: e.column }
1249
+ });
1250
+ pendingHints =
1251
+ parsedHints.prefetch !== undefined ||
1252
+ parsedHints.preload !== undefined ||
1253
+ parsedHints.fetchPriority !== undefined
1254
+ ? parsedHints
1255
+ : undefined;
1256
+ } else {
1257
+ pendingHints = undefined;
1258
+ }
1259
+ },
1260
+ [NodeType.Doctype]: (path) => {
1261
+ // only visited when head injection is active (see `skip` below)
1262
+ if (doctypeEnd === -1) doctypeEnd = path.end();
1263
+ pendingWebpackIgnore = undefined;
1264
+ pendingWebpackInline = undefined;
1265
+ pendingHints = undefined;
1266
+ },
1267
+ [NodeType.Element]: {
1268
+ // Children (and `<template>` content) are walked by the
1269
+ // processor after `enter`; `exit` clears a pending
1270
+ // `webpackIgnore` once they're done.
1271
+ enter: (path) => {
1272
+ const ignore = pendingWebpackIgnore === true;
1273
+ const forceInline = pendingWebpackInline === true;
1274
+ pendingWebpackIgnore = undefined;
1275
+ pendingWebpackInline = undefined;
1276
+
1277
+ // `<head>` anchors are collected for every page — they place
1278
+ // `inject: "head"` siblings and resource hints; the
1279
+ // title/meta/base facts only when configured. Structural, so it
1280
+ // runs even for `webpackIgnore`d elements.
1281
+ {
1282
+ const name = path.tagName();
1283
+ if (name === "template" && path.namespace() === NS_HTML) {
1284
+ templateDepth++;
1285
+ }
1286
+ if (headTemplateDepth > 0) {
1287
+ if (name === "template" && path.namespace() === NS_HTML) {
1288
+ headTemplateDepth++;
1289
+ }
1290
+ } else if (inHead) {
1291
+ if (headOptions !== undefined && path.namespace() === NS_HTML) {
1292
+ switch (name) {
1293
+ case "title":
1294
+ headHasTitle = true;
1295
+ break;
1296
+ case "base":
1297
+ headHasBase = true;
1298
+ break;
1299
+ case "meta": {
1300
+ if (path.findAttribute("charset") !== 0) {
1301
+ headCharsetEnd = path.tagEnd();
1302
+ } else {
1303
+ const httpEquiv = path.findAttribute("http-equiv");
1304
+ const contentAttr =
1305
+ httpEquiv !== 0 &&
1306
+ decodeEntities(
1307
+ path.attributeValue(httpEquiv),
1308
+ true
1309
+ ).toLowerCase() === "content-type"
1310
+ ? path.findAttribute("content")
1311
+ : 0;
1312
+ if (
1313
+ contentAttr !== 0 &&
1314
+ CHARSET_DECLARATION_REGEXP.test(
1315
+ decodeEntities(
1316
+ path.attributeValue(contentAttr),
1317
+ true
1318
+ )
1319
+ )
1320
+ ) {
1321
+ headCharsetEnd = path.tagEnd();
1322
+ }
1323
+ }
1324
+ const nameAttr = path.findAttribute("name");
1325
+ const propertyAttr = path.findAttribute("property");
1326
+ if (nameAttr !== 0 || propertyAttr !== 0) {
1327
+ if (headMetaNames === undefined) {
1328
+ headMetaNames = new Set();
1329
+ }
1330
+ if (nameAttr !== 0) {
1331
+ headMetaNames.add(
1332
+ decodeEntities(
1333
+ path.attributeValue(nameAttr),
1334
+ true
1335
+ ).toLowerCase()
1336
+ );
1337
+ }
1338
+ if (propertyAttr !== 0) {
1339
+ headMetaNames.add(
1340
+ decodeEntities(
1341
+ path.attributeValue(propertyAttr),
1342
+ true
1343
+ ).toLowerCase()
1344
+ );
1345
+ }
1346
+ }
1347
+ break;
1348
+ }
1349
+ case "template":
1350
+ headTemplateDepth++;
1351
+ break;
1352
+ }
1353
+ } else if (
1354
+ name === "template" &&
1355
+ path.namespace() === NS_HTML
1356
+ ) {
1357
+ headTemplateDepth++;
1358
+ }
1359
+ if (path.end() > headLastEnd) headLastEnd = path.end();
1360
+ } else if (!headSeen && path.namespace() === NS_HTML) {
1361
+ if (name === "html") {
1362
+ htmlTagEnd = path.tagEnd();
1363
+ } else if (name === "head") {
1364
+ headSeen = true;
1365
+ inHead = true;
1366
+ // explicit head has real offsets; an implicit one (head
1367
+ // tags are optional in HTML5) anchors after `<html>`,
1368
+ // the doctype, or the document start
1369
+ const tagEnd = path.tagEnd();
1370
+ headStart =
1371
+ tagEnd > 0
1372
+ ? tagEnd
1373
+ : htmlTagEnd > 0
1374
+ ? htmlTagEnd
1375
+ : doctypeEnd > 0
1376
+ ? doctypeEnd
1377
+ : 0;
1378
+ headLastEnd = headStart;
1379
+ }
1380
+ }
1381
+ }
1382
+
1383
+ if (ignore) {
1384
+ return;
1385
+ }
1386
+
1387
+ const elementName = path.tagName();
1388
+ const attributeCount = path.attributeCount();
1389
+ const elementStart = path.start();
1390
+ const tagEnd = path.tagEnd();
1391
+ const nameEnd = path.nameEnd();
1392
+
1393
+ // The first `<base href>` freezes the base for later URLs — but
1394
+ // only one in the real document tree, not inside an inert
1395
+ // `<template>` (whose contents are a separate fragment).
1396
+ if (
1397
+ documentBase === undefined &&
1398
+ templateDepth === 0 &&
1399
+ elementName === "base" &&
1400
+ path.namespace() === NS_HTML
1401
+ ) {
1402
+ const hrefAttr = path.findAttribute("href");
1403
+ if (hrefAttr !== 0) resolveDocumentBase(path, hrefAttr);
1404
+ }
1405
+
1406
+ // Rebind the parse-scoped lazy attribute map to this element.
1407
+ attrMapPath = path;
1408
+ attrMapCount = attributeCount;
1409
+ currentAttributesMap = undefined;
1410
+
1411
+ // Each matched attribute is a source; the element body (inline
1412
+ // `<style>`/`<script>`) is one more — content rather than an attribute.
1413
+ // All are dispatched by the same `switch (type)`.
1414
+ const sources =
1415
+ this.sourcesByTag[elementName] || this.sourcesByTag[ANY_TAG];
1416
+ const bodyItem = CONTENT_SOURCES[elementName];
1417
+ // Iterate the attributes, then one extra step for the element
1418
+ // body (`i === attributeCount`); the attribute ref is only read on the
1419
+ // attribute steps, so it stays in bounds.
1420
+ for (let i = 0; i < attributeCount + 1; i++) {
1421
+ const content = i === attributeCount;
1422
+ /** @type {SourceType} */
1423
+ let type;
1424
+ /** @type {string} */
1425
+ let value;
1426
+ /** @type {number} */
1427
+ let start;
1428
+ /** @type {number} */
1429
+ let end;
1430
+ /** @type {import("./syntax").HtmlAttributeRef} */
1431
+ let attr = 0;
1432
+ if (content) {
1433
+ if (!bodyItem) continue;
1434
+ if (bodyItem.filter && !bodyItem.filter(getAttributesMap())) {
1435
+ continue;
1436
+ }
1437
+ // `skip.text` drops the body `Text` node; the raw content
1438
+ // span is [`tagEnd`, `contentEnd`] on the element.
1439
+ const bodyStart = tagEnd;
1440
+ const bodyEnd = path.contentEnd();
1441
+ if (bodyEnd <= bodyStart) continue;
1442
+ value = source.slice(bodyStart, bodyEnd);
1443
+ if (value.trim() === "") continue;
1444
+ start = bodyStart;
1445
+ end = bodyEnd;
1446
+ type =
1447
+ typeof bodyItem.type === "function"
1448
+ ? bodyItem.type(getAttributesMap(), css)
1449
+ : bodyItem.type;
1450
+ } else {
1451
+ attr = path.attributeAt(i);
1452
+ const item = sources[path.attributeName(attr)];
1453
+ if (!item) continue;
1454
+ if (
1455
+ item.namespace !== undefined &&
1456
+ path.namespace() !== item.namespace
1457
+ ) {
1458
+ continue;
1459
+ }
1460
+ // Adoption-agency clones carry no offsets; skip blank values.
1461
+ if (path.attributeValueStart(attr) === -1) {
1462
+ continue;
1463
+ }
1464
+ value = path.attributeValue(attr);
1465
+ if (!value || !/\S/.test(value)) continue;
1466
+ const filter = item.filter;
1467
+ if (filter) {
1468
+ // The filter also sees the decoded value (the browser tokenizes it
1469
+ // decoded, e.g. `&#117;rl(`), so a value-only check needn't re-read it.
1470
+ const decoded = value.includes("&")
1471
+ ? decodeEntities(value, true)
1472
+ : value;
1473
+ if (!filter(getAttributesMap(), decoded)) continue;
1474
+ }
1475
+ start = path.attributeValueStart(attr);
1476
+ end = path.attributeValueEnd(attr);
1477
+ type =
1478
+ typeof item.type === "function"
1479
+ ? item.type(getAttributesMap(), css)
1480
+ : item.type;
1481
+ }
1482
+ // A resolved `type` selects the parse algorithm and the dependency
1483
+ // kind — the only dispatch in the parser.
1484
+ switch (type) {
1485
+ // Inline CSS — a `<style>` body (raw, a full stylesheet) or an
1486
+ // attribute value (decoded, re-escaped on write-back; `*-attribute`
1487
+ // is a declaration list). Needs `experiments.css`.
1488
+ case "stylesheet-style":
1489
+ case "stylesheet-style-attribute": {
1490
+ if (!css) break;
1491
+ const cssText = content ? value : decodeEntities(value, true);
1492
+ if (cssText.trim() === "") break;
1493
+ const dep = new HtmlInlineStyleDependency(
1494
+ dataUri("text/css", cssText),
1495
+ [start, end],
1496
+ content ? false : type === "stylesheet-style-attribute",
1497
+ !content
1498
+ );
1499
+ setLoc(dep, start, end);
1500
+ module.addDependency(dep);
1501
+ module.addCodeGenerationDependency(dep);
1502
+ break;
1503
+ }
1504
+ // `<iframe srcdoc>`: an entity-encoded HTML document. Feed the
1505
+ // decoded markup back through the HTML pipeline as a nested
1506
+ // `data:text/html` module. Per spec the value is a full document
1507
+ // whose URL is `about:srcdoc`, so its base URL is inherited from
1508
+ // this document — asset URLs resolve against this file's context.
1509
+ case "srcdoc": {
1510
+ const htmlText = decodeEntities(value, true);
1511
+ // Only spin up a nested module when there is markup that can
1512
+ // reference an asset; text/formatting-only markup is identical
1513
+ // after rewriting (see `SRCDOC_ASSET_REGEXP`).
1514
+ if (
1515
+ !htmlText.includes("<") ||
1516
+ !SRCDOC_ASSET_REGEXP.test(htmlText)
1517
+ ) {
1518
+ break;
1519
+ }
1520
+ const dep = new HtmlInlineHtmlDependency(
1521
+ dataUri("text/html", htmlText),
1522
+ [start, end]
1523
+ );
1524
+ setLoc(dep, start, end);
1525
+ module.addDependency(dep);
1526
+ module.addCodeGenerationDependency(dep);
1527
+ break;
1528
+ }
1529
+ // Inline `<script>` body — bundled as its own entry chunk.
1530
+ case "script":
1531
+ case "script-module":
1532
+ if (content) {
1533
+ const scriptType =
1534
+ /** @type {"script" | "script-module"} */ (type);
1535
+ const request = dataUri("text/javascript", value);
1536
+ const entryName = `__html_${moduleHash}_${nextEntryIndex++}`;
1537
+ const dep = new HtmlInlineScriptDependency(
1538
+ request,
1539
+ nameEnd,
1540
+ [start, end],
1541
+ entryName,
1542
+ scriptType === "script-module" ? "esm" : "commonjs"
1543
+ );
1544
+ setLoc(dep, start, end);
1545
+ module.addPresentationalDependency(dep);
1546
+ reconcileScriptTypeAttr(
1547
+ path,
1548
+ path.findAttribute("type"),
1549
+ nameEnd,
1550
+ scriptType,
1551
+ source
1552
+ );
1553
+ (scriptType === "script"
1554
+ ? scriptEntries
1555
+ : scriptModuleEntries
1556
+ ).push({
1557
+ request,
1558
+ entryName,
1559
+ type: scriptType
1560
+ });
1561
+ break;
1562
+ }
1563
+ // falls through — external `<script src>` joins the URL-bearing types
1564
+ case "src":
1565
+ case "srcset":
1566
+ case "css-url":
1567
+ case "msapplication-task":
1568
+ case "modulepreload":
1569
+ case "stylesheet":
1570
+ case "html":
1571
+ case "preload":
1572
+ case "prefetch": {
1573
+ // Parse the value into one or more URLs (decoding character
1574
+ // references, mapping spans back to raw offsets), then emit a plain
1575
+ // asset reference or an entry chunk per URL.
1576
+ const parse =
1577
+ type === "srcset"
1578
+ ? parseSrcset
1579
+ : type === "css-url"
1580
+ ? parseCssUrls
1581
+ : type === "msapplication-task"
1582
+ ? parseMsapplicationTask
1583
+ : parseSrc;
1584
+ let text = value;
1585
+ /** @type {number[] | undefined} */
1586
+ let map;
1587
+ if (value.includes("&")) {
1588
+ ({ text, map } = decodeEntities(value, true, true));
1589
+ if (!/\S/.test(text)) break;
1590
+ }
1591
+ /** @type {ParsedSource[] | undefined} */
1592
+ let parsed;
1593
+ try {
1594
+ parsed = parse(text);
1595
+ } catch (err) {
1596
+ const ds = locConverter.get(start);
1597
+ const de = locConverter.get(end);
1598
+ module.addError(
1599
+ new ModuleDependencyError(
1600
+ module,
1601
+ new WebpackError(
1602
+ `Bad value for attribute "${path.attributeName(
1603
+ attr
1604
+ )}" on element "${elementName}": ${
1605
+ /** @type {Error} */ (err).message
1606
+ }`
1607
+ ),
1608
+ {
1609
+ start: { line: ds.line, column: ds.column },
1610
+ end: { line: de.line, column: de.column }
1611
+ }
1612
+ )
1613
+ );
1614
+ break;
1615
+ }
1616
+ if (!parsed) break;
1617
+ for (const [url, us, ue] of parsed) {
1618
+ // Internal `url(#id)` / fragment-only refs aren't assets.
1619
+ if (!url || url.startsWith("#")) continue;
1620
+ // Resolve the request against `<base href>`. Only relative
1621
+ // URLs are affected (scheme / `//` / `/` URLs ignore the
1622
+ // base); an external base drops them from the build.
1623
+ let request = url;
1624
+ if (
1625
+ documentBase &&
1626
+ url.charCodeAt(0) !== CC_SLASH &&
1627
+ !ABSOLUTE_URL_SCHEME_REGEXP.test(url)
1628
+ ) {
1629
+ if (baseIsExternal) continue;
1630
+ request = baseDir + url;
1631
+ }
1632
+ const s = start + (map ? map[us] : us);
1633
+ const e = start + (map ? map[ue] : ue);
1634
+ // `html` links the URL as its own emitted page: the same
1635
+ // `HtmlEntryDependency` as `<script src>` / `<link>`, but the `html`
1636
+ // kind rewrites to the page's filename and emits no sibling tags.
1637
+ // Recorded as an independent entry (no `dependOn`), like an entry point.
1638
+ if (type === "html") {
1639
+ const entryName = `__html_${moduleHash}_${nextEntryIndex++}`;
1640
+ const dep = new HtmlEntryDependency(
1641
+ request,
1642
+ [s, e],
1643
+ entryName,
1644
+ undefined,
1645
+ "html"
1646
+ );
1647
+ setLoc(dep, s, e);
1648
+ module.addPresentationalDependency(dep);
1649
+ htmlLinkEntries.push({ request, entryName, type });
1650
+ continue;
1651
+ }
1652
+ // `rel="preload"/"prefetch"` of a bundled resource: an
1653
+ // independent, non-executing entry whose `href` is rewritten to
1654
+ // the built chunk's URL (CSS for `as="style"`, JS otherwise). No
1655
+ // sibling tags — a resource hint references exactly one URL.
1656
+ if (type === "preload" || type === "prefetch") {
1657
+ const as = getAttributeValue(getAttributesMap(), "as");
1658
+ const asStyle = as
1659
+ ? as.trim().toLowerCase() === "style"
1660
+ : false;
1661
+ const entryName = `__html_${moduleHash}_${nextEntryIndex++}`;
1662
+ // Tag metadata so the template can mirror `crossorigin`/
1663
+ // `integrity` onto a native `preload` `<link>` (integrity-
1664
+ // eligible per the SRI spec). `prefetch` gets none — the spec
1665
+ // doesn't list it — so its `integrity` is left uncaptured.
1666
+ const isNativeLink = elementName === "link";
1667
+ const dep = new HtmlEntryDependency(
1668
+ request,
1669
+ [s, e],
1670
+ entryName,
1671
+ asStyle ? "css-import" : undefined,
1672
+ type,
1673
+ elementStart,
1674
+ tagEnd,
1675
+ isNativeLink,
1676
+ "",
1677
+ nameEnd,
1678
+ isNativeLink && path.findAttribute("crossorigin") !== 0,
1679
+ -1,
1680
+ type === "preload" && isNativeLink
1681
+ ? captureIntegrityRange(path, source, elementStart)
1682
+ : null,
1683
+ null
1684
+ );
1685
+ setLoc(dep, s, e);
1686
+ module.addPresentationalDependency(dep);
1687
+ (type === "preload"
1688
+ ? preloadEntries
1689
+ : prefetchEntries
1690
+ ).push({
1691
+ request,
1692
+ entryName,
1693
+ type,
1694
+ css: asStyle
1695
+ });
1696
+ continue;
1697
+ }
1698
+ // `src`/`srcset`/`css-url`/`msapplication-task` are plain assets;
1699
+ // the rest are narrowed to entry types here and share one
1700
+ // `HtmlEntryDependency`, recorded for HtmlModulesPlugin.
1701
+ if (
1702
+ type === "script" ||
1703
+ type === "script-module" ||
1704
+ type === "modulepreload" ||
1705
+ type === "stylesheet"
1706
+ ) {
1707
+ const entryName = `__html_${moduleHash}_${nextEntryIndex++}`;
1708
+ const willBeModuleScript =
1709
+ type === "script-module" ||
1710
+ (outputModule && type === "script");
1711
+ /** @type {EntrySourceType} */
1712
+ const elementKind =
1713
+ type === "modulepreload"
1714
+ ? "modulepreload"
1715
+ : type === "stylesheet"
1716
+ ? "stylesheet"
1717
+ : willBeModuleScript
1718
+ ? "script-module"
1719
+ : "script";
1720
+ const entryCategory =
1721
+ type === "stylesheet"
1722
+ ? "css-import"
1723
+ : type === "script-module" || type === "modulepreload"
1724
+ ? "esm"
1725
+ : undefined;
1726
+ // Native = the loading element is the tag the template clones
1727
+ // verbatim (`<script>` / `<link>`); a custom element is not.
1728
+ const nativeTag =
1729
+ elementKind === "stylesheet" ||
1730
+ elementKind === "modulepreload"
1731
+ ? "link"
1732
+ : "script";
1733
+ // CSP/fetch attributes the template copies onto siblings.
1734
+ let copyableAttrsText = "";
1735
+ let hasOwnCrossOrigin = false;
1736
+ if (elementStart >= 0) {
1737
+ for (const copyableName of COPYABLE_SIBLING_ATTRS) {
1738
+ const copyableAttr = path.findAttribute(copyableName);
1739
+ if (copyableAttr !== 0) {
1740
+ copyableAttrsText += attrSourceSpan(
1741
+ path,
1742
+ source,
1743
+ copyableAttr
1744
+ );
1745
+ if (copyableName === "crossorigin") {
1746
+ hasOwnCrossOrigin = true;
1747
+ }
1748
+ }
1749
+ }
1750
+ }
1751
+ // Blocking-ness of the tag as *emitted*:
1752
+ // `reconcileScriptTypeAttr` upgrades every script entry
1753
+ // to `type="module"` under `output.module` and strips an
1754
+ // authored `type="module"` otherwise — so only non-module
1755
+ // output without `defer`/`async` blocks. Non-native
1756
+ // elements anchor conservatively (their synthesized
1757
+ // siblings may be plain blocking `<script>`s).
1758
+ if (
1759
+ firstBlockingScriptStart === -1 &&
1760
+ (type === "script" || type === "script-module") &&
1761
+ !outputModule &&
1762
+ (elementName !== nativeTag ||
1763
+ (path.findAttribute("defer") === 0 &&
1764
+ path.findAttribute("async") === 0))
1765
+ ) {
1766
+ firstBlockingScriptStart = elementStart;
1767
+ }
1768
+ // Sibling-clone attribute edits, captured from the parsed
1769
+ // attributes (offsets relative to the tag) so the template
1770
+ // needn't re-parse the tag text: `integrity` is dropped
1771
+ // (content-specific) and `script-module` clones are forced
1772
+ // to `type="module"` (its value range, else inserted).
1773
+ const integrityRange =
1774
+ elementStart >= 0 && elementName === nativeTag
1775
+ ? captureIntegrityRange(path, source, elementStart)
1776
+ : null;
1777
+ /** @type {Range | null} */
1778
+ let typeValueRange = null;
1779
+ if (
1780
+ elementStart >= 0 &&
1781
+ elementName === nativeTag &&
1782
+ elementKind === "script-module"
1783
+ ) {
1784
+ const typeAttr = path.findAttribute("type");
1785
+ if (
1786
+ typeAttr !== 0 &&
1787
+ path.attributeValueStart(typeAttr) >= 0
1788
+ ) {
1789
+ typeValueRange = [
1790
+ path.attributeValueStart(typeAttr) - elementStart,
1791
+ path.attributeValueEnd(typeAttr) - elementStart
1792
+ ];
1793
+ }
1794
+ }
1795
+ const dep = new HtmlEntryDependency(
1796
+ request,
1797
+ [s, e],
1798
+ entryName,
1799
+ entryCategory,
1800
+ elementKind,
1801
+ elementStart,
1802
+ tagEnd,
1803
+ elementName === nativeTag,
1804
+ copyableAttrsText,
1805
+ nameEnd,
1806
+ hasOwnCrossOrigin,
1807
+ firstBlockingScriptStart,
1808
+ integrityRange,
1809
+ typeValueRange,
1810
+ forceInline,
1811
+ headSeen && headStart > 0 ? headStart : -1,
1812
+ headSeen && headLastEnd > 0 ? headLastEnd : -1
1813
+ );
1814
+ setLoc(dep, s, e);
1815
+ module.addPresentationalDependency(dep);
1816
+ if (
1817
+ elementName === "script" &&
1818
+ (type === "script" || type === "script-module")
1819
+ ) {
1820
+ reconcileScriptTypeAttr(
1821
+ path,
1822
+ path.findAttribute("type"),
1823
+ nameEnd,
1824
+ type,
1825
+ source
1826
+ );
1827
+ }
1828
+ (type === "script"
1829
+ ? scriptEntries
1830
+ : type === "script-module"
1831
+ ? scriptModuleEntries
1832
+ : type === "stylesheet"
1833
+ ? stylesheetEntries
1834
+ : modulePreloadEntries
1835
+ ).push({ request, entryName, type });
1836
+ } else {
1837
+ const dep = new HtmlSourceDependency(request, [s, e]);
1838
+ ResourceHintPlugin.applyDefaults(
1839
+ dep,
1840
+ ResourceHintPlugin.matchUrlHints(urlHints, request)
1841
+ );
1842
+ // `<!-- webpackPrefetch: true -->` (etc.) immediately
1843
+ // before this tag wins over the project-wide default.
1844
+ if (pendingHints) {
1845
+ ResourceHintPlugin.applyParsedHints(dep, pendingHints);
1846
+ pendingHints = undefined;
1847
+ }
1848
+ setLoc(dep, s, e);
1849
+ module.addDependency(dep);
1850
+ module.addCodeGenerationDependency(dep);
1851
+ }
1852
+ }
1853
+ break;
1854
+ }
1855
+ }
1856
+ }
1857
+ },
1858
+ exit: (path) => {
1859
+ if (path.namespace() === NS_HTML) {
1860
+ const name = path.tagName();
1861
+ if (name === "template") {
1862
+ if (templateDepth > 0) templateDepth--;
1863
+ if (headTemplateDepth > 0) headTemplateDepth--;
1864
+ } else if (name === "head") {
1865
+ inHead = false;
1866
+ }
1867
+ }
1868
+ pendingWebpackIgnore = undefined;
1869
+ pendingWebpackInline = undefined;
1870
+ pendingHints = undefined;
1871
+ }
1872
+ }
1873
+ })
1874
+ // Skip AST output this walk never reads: `text` (script/style bodies are
1875
+ // read by offset via `contentEnd`) and `doctype` — unless head injection
1876
+ // needs the doctype as an insertion anchor; keep `comments` for
1877
+ // magic comments (`webpackIgnore`).
1878
+ .process(source, {
1879
+ fragmentContext: this.fragmentContext,
1880
+ skip: { text: true, doctype: headOptions === undefined }
1881
+ });
1882
+
1883
+ // `output.html` head injection: existing tags win, injected values are
1884
+ // escaped, insertions at the same offset are merged to keep their order.
1885
+ if (headOptions !== undefined && headSeen) {
1886
+ const { title, meta, base } = headOptions;
1887
+ let startTags = "";
1888
+ if (meta && meta.charset && headCharsetEnd === -1) {
1889
+ startTags += `<meta charset="${escapeAttribute(meta.charset)}">`;
1890
+ }
1891
+ // <base> must follow the charset declaration per spec
1892
+ let baseAfterCharset = "";
1893
+ if (base && !headHasBase) {
1894
+ if (headCharsetEnd !== -1) baseAfterCharset = baseTag(base);
1895
+ else startTags += baseTag(base);
1896
+ }
1897
+ let endTags = "";
1898
+ if (meta) {
1899
+ for (const [name, value] of Object.entries(meta)) {
1900
+ if (
1901
+ name === "charset" ||
1902
+ (headMetaNames !== undefined &&
1903
+ headMetaNames.has(name.toLowerCase()))
1904
+ ) {
1905
+ continue;
1906
+ }
1907
+ endTags += metaTag(name, value);
1908
+ }
1909
+ }
1910
+ if (title && !headHasTitle) {
1911
+ endTags += `<title>${escapeText(title)}</title>`;
1912
+ }
1913
+ /** @type {[number, string][]} */
1914
+ const inserts = [];
1915
+ if (startTags) inserts.push([headStart, startTags]);
1916
+ if (baseAfterCharset) inserts.push([headCharsetEnd, baseAfterCharset]);
1917
+ if (endTags) inserts.push([headLastEnd, endTags]);
1918
+ inserts.sort((a, b) => a[0] - b[0]);
1919
+ for (let i = 0; i < inserts.length; i++) {
1920
+ const at = inserts[i][0];
1921
+ let tags = inserts[i][1];
1922
+ while (i + 1 < inserts.length && inserts[i + 1][0] === at) {
1923
+ tags += inserts[++i][1];
1924
+ }
1925
+ module.addPresentationalDependency(new ConstDependency(tags, at));
1926
+ }
1927
+ }
1928
+
1929
+ const buildInfo = /** @type {HtmlModuleBuildInfo} */ (module.buildInfo);
1930
+ buildInfo.strict = true;
1931
+ if (baseUrlPrefix !== undefined) buildInfo.baseUrlPrefix = baseUrlPrefix;
1932
+ // Hand off the collected entries to HtmlModulesPlugin; it creates the
1933
+ // real compilation entries during the finishMake hook. The `script`
1934
+ // and `script-module` groups are chained via a leader-only dependOn
1935
+ // so they share a runtime; `modulepreload` and `stylesheet` entries
1936
+ // are emitted as independent entries since `<link rel=modulepreload>`
1937
+ // must preload without running and stylesheets have no runtime. `html`
1938
+ // links are independent page entries too.
1939
+ if (
1940
+ scriptEntries.length > 0 ||
1941
+ scriptModuleEntries.length > 0 ||
1942
+ modulePreloadEntries.length > 0 ||
1943
+ stylesheetEntries.length > 0 ||
1944
+ htmlLinkEntries.length > 0 ||
1945
+ preloadEntries.length > 0 ||
1946
+ prefetchEntries.length > 0
1947
+ ) {
1948
+ buildInfo.htmlEntries = {
1949
+ script: scriptEntries,
1950
+ "script-module": scriptModuleEntries,
1951
+ modulepreload: modulePreloadEntries,
1952
+ stylesheet: stylesheetEntries,
1953
+ html: htmlLinkEntries,
1954
+ preload: preloadEntries,
1955
+ prefetch: prefetchEntries
1956
+ };
1957
+ }
1958
+
1959
+ const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta);
1960
+ buildMeta.exportsType = "default";
1961
+
1962
+ state.module.addDependency(new StaticExportsDependency(["default"], true));
1963
+
1964
+ return state;
1965
+ }
1966
+ }
1967
+
1968
+ HtmlParser.buildHeadTags = buildHeadTags;
1969
+
1970
+ module.exports = HtmlParser;