@depup/webpack 5.110.1-depup.0 → 5.111.1-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 (304) hide show
  1. package/README.md +7 -8
  2. package/changes.json +7 -11
  3. package/lib/APIPlugin.js +26 -11
  4. package/lib/AutomaticPrefetchPlugin.js +1 -1
  5. package/lib/Cache.js +8 -3
  6. package/lib/CacheFacade.js +1 -1
  7. package/lib/ChunkGraph.js +20 -18
  8. package/lib/CircularModulesPlugin.js +157 -55
  9. package/lib/CleanPlugin.js +2 -2
  10. package/lib/CompatibilityPlugin.js +3 -4
  11. package/lib/Compilation.js +337 -338
  12. package/lib/Compiler.js +213 -51
  13. package/lib/ConcatenationScope.js +25 -35
  14. package/lib/ConstPlugin.js +16 -132
  15. package/lib/CopyPlugin.js +1054 -0
  16. package/lib/DefinePlugin.js +24 -8
  17. package/lib/DependencyTemplate.js +2 -1
  18. package/lib/DotenvPlugin.js +64 -40
  19. package/lib/ErrorHelpers.js +113 -0
  20. package/lib/ExportsInfo.js +30 -16
  21. package/lib/ExternalModule.js +47 -22
  22. package/lib/FileSystemInfo.js +17 -14
  23. package/lib/FlagDependencyExportsPlugin.js +53 -34
  24. package/lib/FlagDependencyUsagePlugin.js +17 -15
  25. package/lib/Generator.js +24 -2
  26. package/lib/HotModuleReplacementPlugin.js +55 -7
  27. package/lib/IgnorePlugin.js +1 -1
  28. package/lib/JavascriptMetaInfoPlugin.js +5 -3
  29. package/lib/LoaderOptionsPlugin.js +1 -1
  30. package/lib/MainTemplate.js +5 -1
  31. package/lib/Module.js +19 -10
  32. package/lib/ModuleGraph.js +6 -9
  33. package/lib/MultiCompiler.js +7 -17
  34. package/lib/MultiWatching.js +1 -1
  35. package/lib/NormalModule.js +148 -70
  36. package/lib/NormalModuleFactory.js +1 -1
  37. package/lib/RuntimeGlobals.js +21 -7
  38. package/lib/RuntimeModule.js +28 -12
  39. package/lib/RuntimePlugin.js +33 -3
  40. package/lib/RuntimeTemplate.js +1147 -847
  41. package/lib/SourceMapDevToolPlugin.js +54 -104
  42. package/lib/TemplatedPathPlugin.js +16 -59
  43. package/lib/Watching.js +9 -0
  44. package/lib/WebpackOptionsApply.js +84 -91
  45. package/lib/asset/AssetBytesGenerator.js +7 -1
  46. package/lib/asset/AssetGenerator.js +50 -24
  47. package/lib/asset/AssetModule.js +3 -0
  48. package/lib/asset/AssetSourceGenerator.js +7 -1
  49. package/lib/asset/WebManifestParser.js +7 -5
  50. package/lib/async-modules/AsyncModuleHelpers.js +10 -4
  51. package/lib/buildChunkGraph.js +11 -15
  52. package/lib/cache/AddBuildDependenciesPlugin.js +33 -4
  53. package/lib/cache/IdleFileCachePlugin.js +2 -2
  54. package/lib/cache/MemoryCachePlugin.js +4 -4
  55. package/lib/cache/MemoryWithGcCachePlugin.js +7 -8
  56. package/lib/cache/PackFileCacheStrategy.js +17 -19
  57. package/lib/cache/getLazyHashedEtag.js +3 -5
  58. package/lib/config/browserslistTargetHandler.js +17 -4
  59. package/lib/config/defaults.js +162 -142
  60. package/lib/config/getClaimedAssetTypes.js +10 -11
  61. package/lib/config/normalization.js +100 -20
  62. package/lib/config/target.js +13 -4
  63. package/lib/container/ContainerReferencePlugin.js +6 -0
  64. package/lib/container/RemoteRuntimeModule.js +9 -0
  65. package/lib/container/declaredRemotes.js +39 -0
  66. package/lib/{ContextExclusionPlugin.js → context/ContextExclusionPlugin.js} +1 -1
  67. package/lib/{ContextModule.js → context/ContextModule.js} +54 -115
  68. package/lib/{ContextModuleFactory.js → context/ContextModuleFactory.js} +19 -21
  69. package/lib/{ContextReplacementPlugin.js → context/ContextReplacementPlugin.js} +4 -4
  70. package/lib/css/CssGenerator.js +27 -11
  71. package/lib/css/CssInjectStyleRuntimeModule.js +9 -0
  72. package/lib/css/CssLoadingRuntimeModule.js +92 -15
  73. package/lib/css/CssModule.js +1 -1
  74. package/lib/css/CssModulesPlugin.js +3 -10
  75. package/lib/css/CssParser.js +162 -31
  76. package/lib/css/CssServerStylesRuntimeModule.js +9 -0
  77. package/lib/css/cssMinify.js +43 -32
  78. package/lib/css/data.js +3526 -871
  79. package/lib/css/syntax.js +6455 -1237
  80. package/lib/debug/ProfilingPlugin.js +7 -4
  81. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +6 -3
  82. package/lib/dependencies/AMDRuntimeModules.js +18 -0
  83. package/lib/dependencies/CommonJsExportRequireDependency.js +13 -12
  84. package/lib/dependencies/CommonJsExportsParserPlugin.js +12 -13
  85. package/lib/dependencies/CommonJsImportsParserPlugin.js +5 -5
  86. package/lib/dependencies/CommonJsPlugin.js +19 -3
  87. package/lib/dependencies/CommonJsRequireDependency.js +32 -9
  88. package/lib/dependencies/CommonJsSelfReferenceDependency.js +2 -4
  89. package/lib/dependencies/ContextDependency.js +1 -1
  90. package/lib/dependencies/ContextDependencyHelpers.js +3 -9
  91. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +20 -7
  92. package/lib/dependencies/ContextElementDependency.js +1 -1
  93. package/lib/dependencies/CssIcssExportDependency.js +13 -9
  94. package/lib/dependencies/CssIcssImportDependency.js +3 -6
  95. package/lib/dependencies/CssUrlDependency.js +3 -5
  96. package/lib/dependencies/HarmonyCompatibilityDependency.js +67 -22
  97. package/lib/dependencies/HarmonyDetectionParserPlugin.js +3 -4
  98. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +10 -4
  99. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +12 -7
  100. package/lib/dependencies/HarmonyExportExpressionDependency.js +47 -33
  101. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +217 -34
  102. package/lib/dependencies/HarmonyExportInitFragment.js +110 -23
  103. package/lib/dependencies/HarmonyExportSpecifierDependency.js +25 -58
  104. package/lib/dependencies/HarmonyImportBareSideEffectDependency.js +59 -0
  105. package/lib/dependencies/HarmonyImportDependency.js +99 -41
  106. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +198 -25
  107. package/lib/dependencies/HarmonyImportSideEffectDependency.js +117 -4
  108. package/lib/dependencies/HarmonyImportSpecifierDependency.js +40 -3
  109. package/lib/dependencies/HarmonyModulesPlugin.js +20 -0
  110. package/lib/dependencies/HtmlEntryDependency.js +136 -104
  111. package/lib/dependencies/HtmlInlineScriptDependency.js +3 -4
  112. package/lib/dependencies/HtmlInlineStyleDependency.js +3 -4
  113. package/lib/dependencies/ImportContextDependency.js +43 -3
  114. package/lib/dependencies/ImportDependency.js +8 -29
  115. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +1 -1
  116. package/lib/dependencies/ImportMetaGlobHelpers.js +1 -1
  117. package/lib/dependencies/ImportMetaMainDependency.js +104 -0
  118. package/lib/dependencies/ImportMetaPlugin.js +67 -25
  119. package/lib/dependencies/ImportParserPlugin.js +25 -15
  120. package/lib/dependencies/LoaderPlugin.js +26 -1
  121. package/lib/dependencies/RequireContextDependencyParserPlugin.js +1 -1
  122. package/lib/dependencies/RequireHeaderDependency.js +20 -21
  123. package/lib/dependencies/SystemRuntimeModule.js +9 -0
  124. package/lib/dependencies/URLContextDependency.js +1 -1
  125. package/lib/dependencies/URLDependency.js +6 -5
  126. package/lib/dependencies/WorkerAndWorkletPlugin.js +16 -21
  127. package/lib/dependencies/WorkerDependency.js +12 -18
  128. package/lib/dependencies/WorkletDependency.js +12 -20
  129. package/lib/dependencies/importOptionsCheck.js +47 -0
  130. package/lib/dll/DelegatedModule.js +18 -1
  131. package/lib/dll/DllReferencePlugin.js +11 -8
  132. package/lib/dll/LibManifestPlugin.js +1 -1
  133. package/lib/errors/AnalyzableBailoutsWarning.js +41 -0
  134. package/lib/errors/DotenvFileError.js +29 -0
  135. package/lib/errors/DuplicateModulesWarning.js +12 -7
  136. package/lib/errors/EmptyCopyPatternWarning.js +26 -0
  137. package/lib/errors/ExternalStarReexportError.js +44 -0
  138. package/lib/errors/HookWebpackError.js +3 -2
  139. package/lib/errors/ImportedBindingAssignmentError.js +30 -0
  140. package/lib/errors/MissingSourceMapsWarning.js +36 -0
  141. package/lib/errors/ModuleParseError.js +2 -1
  142. package/lib/errors/UnusedAssetsWarning.js +36 -0
  143. package/lib/errors/UnusedFederationWarning.js +35 -0
  144. package/lib/errors/UnusedModulesWarning.js +38 -0
  145. package/lib/esm/ExportWebpackRequireRuntimeModule.js +9 -0
  146. package/lib/esm/ModuleChunkFormatPlugin.js +28 -3
  147. package/lib/esm/ModuleChunkLoadingPlugin.js +21 -5
  148. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +91 -53
  149. package/lib/hmr/HotModuleReplacement.runtime.js +8 -2
  150. package/lib/hmr/HotModuleReplacementRuntimeModule.js +9 -0
  151. package/lib/hmr/LazyCompilationPlugin.js +3 -5
  152. package/lib/html/HtmlGenerator.js +72 -87
  153. package/lib/html/HtmlModulesPlugin.js +479 -215
  154. package/lib/html/HtmlParser.js +110 -147
  155. package/lib/html/builtinEmbeddedRenderer.js +107 -0
  156. package/lib/html/data.js +142 -7
  157. package/lib/html/htmlMinify.js +92 -122
  158. package/lib/html/syntax.js +2031 -1556
  159. package/lib/ids/HashedModuleIdsPlugin.js +2 -1
  160. package/lib/index.js +49 -3
  161. package/lib/javascript/ChunkFormatHelpers.js +4 -3
  162. package/lib/javascript/JavascriptGenerator.js +8 -1
  163. package/lib/javascript/JavascriptModule.js +1 -0
  164. package/lib/javascript/JavascriptModulesPlugin.js +76 -80
  165. package/lib/javascript/JavascriptParser.js +1970 -900
  166. package/lib/javascript/StartupHelpers.js +27 -3
  167. package/lib/javascript/data.js +172 -0
  168. package/lib/javascript/grammar.js +5546 -0
  169. package/lib/javascript/parser.js +1500 -0
  170. package/lib/javascript/regexp.js +1762 -0
  171. package/lib/javascript/regexpData.js +51 -0
  172. package/lib/javascript/syntax.js +9061 -5262
  173. package/lib/json/JsonGenerator.js +7 -1
  174. package/lib/library/ModuleLibraryPlugin.js +171 -132
  175. package/lib/loaders/LoaderRunner.js +170 -14
  176. package/lib/node/NodeWatchFileSystem.js +3 -9
  177. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +22 -0
  178. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +8 -15
  179. package/lib/node/RequireChunkLoadingRuntimeModule.js +22 -0
  180. package/lib/optimize/AggressiveMergingPlugin.js +3 -5
  181. package/lib/optimize/ConcatenatedModule.js +222 -125
  182. package/lib/optimize/ConstExportsPlugin.js +50 -34
  183. package/lib/optimize/FlagIncludedChunksPlugin.js +3 -11
  184. package/lib/optimize/InlineExports.js +20 -2
  185. package/lib/optimize/InnerGraphPlugin.js +7 -13
  186. package/lib/optimize/LimitChunkCountPlugin.js +5 -8
  187. package/lib/optimize/MangleExportsPlugin.js +13 -4
  188. package/lib/optimize/ModuleConcatenationPlugin.js +27 -5
  189. package/lib/optimize/RealContentHashPlugin.js +179 -44
  190. package/lib/optimize/SideEffectsFlagPlugin.js +24 -28
  191. package/lib/optimize/SplitChunksPlugin.js +2 -4
  192. package/lib/performance/AnalyzableBailoutsPlugin.js +115 -0
  193. package/lib/performance/BroadContextsPlugin.js +1 -1
  194. package/lib/performance/CacheEffectivenessPlugin.js +7 -7
  195. package/lib/performance/DuplicateModulesPlugin.js +57 -13
  196. package/lib/performance/EvalUsagePlugin.js +5 -2
  197. package/lib/performance/MissingSourceMapsPlugin.js +115 -0
  198. package/lib/performance/PureAnnotationsPlugin.js +6 -3
  199. package/lib/performance/SizeLimitsPlugin.js +2 -4
  200. package/lib/performance/TopLevelThisPlugin.js +5 -4
  201. package/lib/performance/UnusedAssetsPlugin.js +109 -0
  202. package/lib/performance/UnusedFederationPlugin.js +147 -0
  203. package/lib/performance/UnusedModulesPlugin.js +141 -0
  204. package/lib/performance/UnusedReexportsPlugin.js +1 -55
  205. package/lib/performance/isOnlyReexported.js +65 -0
  206. package/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +25 -5
  207. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +8 -8
  208. package/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +9 -0
  209. package/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +9 -0
  210. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +9 -0
  211. package/lib/prefetch/ResourceHintPlugin.js +29 -35
  212. package/lib/prefetch/ResourceHintRuntimeModule.js +9 -0
  213. package/lib/prefetch/StartupAssetHintRuntimeModule.js +16 -10
  214. package/lib/rules/RuleSetCompiler.js +211 -4
  215. package/lib/runtime/AsyncModuleRuntimeModule.js +103 -67
  216. package/lib/runtime/AutoPublicPathRuntimeModule.js +9 -0
  217. package/lib/runtime/BaseUriRuntimeModule.js +9 -0
  218. package/lib/runtime/ChunkNameRuntimeModule.js +9 -0
  219. package/lib/runtime/EnsureChunkRuntimeModule.js +35 -16
  220. package/lib/runtime/GetChunkFilenameRuntimeModule.js +12 -4
  221. package/lib/runtime/GetFullHashRuntimeModule.js +9 -0
  222. package/lib/runtime/GetMainFilenameRuntimeModule.js +9 -0
  223. package/lib/runtime/GetWorkletBootstrapRuntimeModule.js +9 -0
  224. package/lib/runtime/GlobalRuntimeModule.js +11 -4
  225. package/lib/runtime/HasOwnPropertyRuntimeModule.js +9 -0
  226. package/lib/runtime/HelperRuntimeModule.js +10 -0
  227. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +313 -222
  228. package/lib/runtime/NonceRuntimeModule.js +9 -0
  229. package/lib/runtime/OnChunksLoadedRuntimeModule.js +67 -20
  230. package/lib/runtime/PublicPathRuntimeModule.js +9 -0
  231. package/lib/runtime/RuntimeIdRuntimeModule.js +9 -0
  232. package/lib/runtime/SpecNamespaceObjectRuntimeModule.js +90 -0
  233. package/lib/runtime/StartupChunkDependenciesRuntimeModule.js +9 -0
  234. package/lib/runtime/StartupEntrypointRuntimeModule.js +9 -0
  235. package/lib/runtime/SystemContextRuntimeModule.js +9 -0
  236. package/lib/runtime/ToBinaryRuntimeModule.js +9 -0
  237. package/lib/schemes/DataUriPlugin.js +3 -6
  238. package/lib/schemes/HttpUriPlugin.js +22 -5
  239. package/lib/schemes/VirtualUrlPlugin.js +1 -1
  240. package/lib/serialization/BinaryMiddleware.js +9 -9
  241. package/lib/serialization/FileMiddleware.js +31 -18
  242. package/lib/serialization/ObjectMiddleware.js +168 -139
  243. package/lib/sharing/ConsumeSharedPlugin.js +12 -0
  244. package/lib/sharing/ConsumeSharedRuntimeModule.js +11 -0
  245. package/lib/sharing/ShareRuntimeModule.js +9 -0
  246. package/lib/sharing/declaredShared.js +47 -0
  247. package/lib/stats/DefaultStatsFactoryPlugin.js +6 -5
  248. package/lib/stats/DefaultStatsPrinterPlugin.js +3 -0
  249. package/lib/typescript/TypeScriptPlugin.js +10 -13
  250. package/lib/url/URLParserPlugin.js +6 -8
  251. package/lib/util/ArrayQueue.js +3 -3
  252. package/lib/util/LocConverter.js +4 -7
  253. package/lib/util/SourceProcessor.js +115 -99
  254. package/lib/util/URLAbsoluteSpecifier.js +3 -1
  255. package/lib/util/async.js +292 -0
  256. package/lib/util/buildDiagnostics.js +69 -0
  257. package/lib/util/chainedImports.js +3 -4
  258. package/lib/util/concatenate.js +4 -4
  259. package/lib/util/conventions.js +5 -1
  260. package/lib/util/createHooksRegistry.js +1 -2
  261. package/lib/util/createMappings.js +25 -3
  262. package/lib/util/dataURL.js +2 -3
  263. package/lib/util/deterministicGrouping.js +8 -13
  264. package/lib/util/findGraphRoots.js +6 -13
  265. package/lib/util/fs.js +27 -1
  266. package/lib/util/globUtils.js +1 -1
  267. package/lib/util/handlerKeys.js +40 -0
  268. package/lib/util/hash/wasm-hash.js +3 -4
  269. package/lib/util/identifier.js +20 -0
  270. package/lib/util/internalSerializables.js +7 -1
  271. package/lib/util/registerExternalSerializer.js +6 -45
  272. package/lib/util/removeBOM.js +82 -1
  273. package/lib/util/semver.js +5 -3
  274. package/lib/wasm-async/AsyncWasmCompileRuntimeModule.js +14 -3
  275. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +14 -3
  276. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +6 -1
  277. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +5 -1
  278. package/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js +7 -12
  279. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +12 -4
  280. package/lib/wasm-sync/WebAssemblyGenerator.js +6 -1
  281. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +5 -1
  282. package/lib/wasm-sync/WebAssemblyUtils.js +2 -4
  283. package/lib/web/FetchCompileAsyncWasmPlugin.js +10 -6
  284. package/lib/web/FetchCompileWasmPlugin.js +4 -2
  285. package/lib/web/JsonpChunkLoadingRuntimeModule.js +36 -0
  286. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +19 -0
  287. package/package.json +55 -46
  288. package/schemas/WebpackOptions.check.js +1 -1
  289. package/schemas/WebpackOptions.json +388 -76
  290. package/schemas/plugins/LoaderOptionsPlugin.check.js +1 -1
  291. package/schemas/plugins/ManifestPlugin.check.js +1 -1
  292. package/schemas/plugins/SourceMapDevToolPlugin.check.js +1 -1
  293. package/schemas/plugins/asset/AssetGeneratorOptions.check.js +1 -1
  294. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js +1 -1
  295. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  296. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  297. package/schemas/plugins/debug/ProfilingPlugin.check.js +1 -1
  298. package/schemas/plugins/dll/DllReferencePlugin.check.js +1 -1
  299. package/schemas/plugins/ids/HashedModuleIdsPlugin.check.js +1 -1
  300. package/schemas/plugins/schemes/HttpUriPlugin.check.js +1 -1
  301. package/types.d.ts +1795 -608
  302. package/lib/dependencies/ExportBindingInitFragment.js +0 -191
  303. package/lib/errors/EntrypointOverlapWarning.js +0 -45
  304. package/lib/performance/EntrypointOverlapPlugin.js +0 -122
@@ -7,6 +7,7 @@
7
7
  const {
8
8
  CSS_IMPORT_TYPE,
9
9
  CSS_TYPE,
10
+ HTML_TYPE,
10
11
  JAVASCRIPT_TYPE
11
12
  } = require("../ModuleSourceTypeConstants");
12
13
  const ResourceHintPlugin = require("../prefetch/ResourceHintPlugin");
@@ -194,7 +195,12 @@ const getEntrypointChunksInLoadOrder = (entrypoint) => {
194
195
  const chunksLoadedByAncestorTags = new Set();
195
196
  /** @type {Set<import("../ChunkGroup")>} */
196
197
  const visitedGroups = new Set();
197
- const walk = (/** @type {import("../ChunkGroup")} */ group) => {
198
+ /**
199
+ * Collects the chunks an ancestor entry's own tags already load.
200
+ * @param {import("../ChunkGroup")} group chunk group to walk up from
201
+ * @returns {void}
202
+ */
203
+ const walk = (group) => {
198
204
  if (visitedGroups.has(group)) return;
199
205
  visitedGroups.add(group);
200
206
  for (const parent of group.parentsIterable) {
@@ -220,7 +226,12 @@ const getEntrypointChunksInLoadOrder = (entrypoint) => {
220
226
  const ordered = [];
221
227
  /** @type {Set<Chunk>} */
222
228
  const seen = new Set();
223
- const push = (/** @type {Chunk | null | undefined} */ chunk) => {
229
+ /**
230
+ * Appends a chunk once, skipping the ones an ancestor entry already loads.
231
+ * @param {Chunk | null | undefined} chunk chunk to append
232
+ * @returns {void}
233
+ */
234
+ const push = (chunk) => {
224
235
  if (!chunk || seen.has(chunk) || chunk === entryChunk) return;
225
236
  if (chunksLoadedByAncestorTags.has(chunk)) return;
226
237
  seen.add(chunk);
@@ -487,11 +498,12 @@ const cloneTagWithUrl = (
487
498
  return isLink ? body : `${body}</script>`;
488
499
  };
489
500
 
490
- // ES5 `<link rel="modulepreload">` polyfill (Safari <17, Firefox <115, …):
491
- // on browsers without native support, fetch each modulepreload target with the
492
- // tag's own credentials/integrity so the pending module import reuses it. The
493
- // `.ep` guard makes it idempotent, and the observer catches any later-inserted
494
- // links. Emitted only when the target environment lacks native support.
501
+ // WHY: an ES5 `<link rel="modulepreload">` polyfill (Safari <17, Firefox <115,
502
+ // …). On a browser without native support, each modulepreload target is fetched
503
+ // with the tag's own credentials and integrity, so the pending module import
504
+ // reuses it. The `.ep` guard makes that idempotent and the observer catches any
505
+ // later-inserted link. Emitted only where the target environment lacks native
506
+ // support.
495
507
  const MODULEPRELOAD_POLYFILL = [
496
508
  "(function(){",
497
509
  'var s=document.createElement("link").relList;',
@@ -577,6 +589,47 @@ const buildLinkTag = (rel, attrs) =>
577
589
  : ""
578
590
  }>`;
579
591
 
592
+ /**
593
+ * The chunks a hint means when it names a page: a page loads no JavaScript of
594
+ * its own, so the hint follows the entries the parser extracted from it.
595
+ * @param {import("../Compilation")} compilation compilation
596
+ * @param {Chunk} chunk chunk a hint resolved to
597
+ * @returns {Chunk[]} the chunks to hint at
598
+ */
599
+ const resolvePageChunk = (compilation, chunk) => {
600
+ const { chunkGraph } = compilation;
601
+ const modules = chunkGraph.getChunkModulesIterableBySourceType(
602
+ chunk,
603
+ HTML_TYPE
604
+ );
605
+ // A page with a JavaScript side of its own (an `output.library` entry) is
606
+ // hinted too — `chunkHasJs` can't say so, it holds for any runtime chunk.
607
+ const javascript = chunkGraph.getChunkModulesIterableBySourceType(
608
+ chunk,
609
+ JAVASCRIPT_TYPE
610
+ );
611
+ /** @type {Chunk[]} */
612
+ const chunks = javascript === undefined ? [] : [chunk];
613
+ // A chunk carrying no page stands for itself; a page stands for the entries
614
+ // extracted from it, so one that extracted nothing hints nothing.
615
+ if (modules === undefined) return chunks.length === 0 ? [chunk] : chunks;
616
+ for (const module of modules) {
617
+ const { htmlEntries } =
618
+ /** @type {import("../html/HtmlModule").HtmlModuleBuildInfo} */ (
619
+ module.buildInfo
620
+ ) || {};
621
+ if (!htmlEntries) continue;
622
+ for (const group of Object.values(htmlEntries)) {
623
+ for (const { entryName } of group) {
624
+ const entrypoint = compilation.entrypoints.get(entryName);
625
+ const entryChunk = entrypoint && entrypoint.getEntrypointChunk();
626
+ if (entryChunk) chunks.push(entryChunk);
627
+ }
628
+ }
629
+ }
630
+ return chunks;
631
+ };
632
+
580
633
  /**
581
634
  * Resolve one `output.html.resourceHints` descriptor to zero or more `<link>`
582
635
  * tags. A `chunk`/`entry` reference becomes the emitted chunk URL (a sentinel
@@ -623,6 +676,14 @@ const resolveResourceHint = (desc, ctx) => {
623
676
  } else {
624
677
  return [];
625
678
  }
679
+ /** @type {Chunk[]} */
680
+ const hinted = [];
681
+ for (const chunk of chunks) {
682
+ for (const resolved of resolvePageChunk(ctx.compilation, chunk)) {
683
+ hinted.push(resolved);
684
+ }
685
+ }
686
+ chunks = hinted;
626
687
  const kind = desc.as === "style" ? "css" : "javascript";
627
688
  const as = desc.as || (rel === "modulepreload" ? undefined : "script");
628
689
  // A hint targeting another chunk must match how that chunk is fetched, so
@@ -677,10 +738,9 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
677
738
  const dep = /** @type {HtmlEntryDependency} */ (dependency);
678
739
  const compilation = runtimeTemplate.compilation;
679
740
 
680
- // A `type: "html"` link points at another emitted page, not a JS/CSS
681
- // chunk: rewrite the attribute to that page's filename (resolved by
682
- // HtmlModulesPlugin once it's built) and emit no sibling tags — a page
683
- // link loads only itself.
741
+ // A `type: "html"` link points at another emitted page rather than a chunk,
742
+ // so rewrite the attribute to that page's filename and emit no siblings:
743
+ // a page link loads only itself.
684
744
  if (dep.elementKind === "html") {
685
745
  source.replace(
686
746
  dep.range[0],
@@ -704,21 +764,17 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
704
764
  const orderedChunks = getEntrypointChunksInLoadOrder(entrypoint);
705
765
  const entryChunk = orderedChunks[orderedChunks.length - 1];
706
766
 
707
- // `crossorigin` mirrors `output.crossOriginLoading` onto every injected
708
- // tag. Empty when the option is off or the originating tag already set
709
- // `crossorigin` (author value wins, flagged at parse time). Mirrors
710
- // webpack's runtime, which sets `crossOrigin` on chunk-loading scripts,
711
- // and matches Vite, which emits it on every injected script/stylesheet.
767
+ // Mirrors `output.crossOriginLoading` onto every injected tag, as webpack's
768
+ // runtime does for chunk-loading scripts. Empty when the option is off or
769
+ // the originating tag set `crossorigin` itself, since the author wins.
712
770
  const crossOrigin =
713
771
  crossOriginLoading && !dep.hasOwnCrossOrigin
714
772
  ? ` crossorigin="${crossOriginLoading}"`
715
773
  : "";
716
774
 
717
- // Per-chunk SRI: emit an `integrity` sentinel resolved late (after the
718
- // chunks' final bytes exist) by `resolveChunkIntegritySentinels`. Tags are
719
- // generated per HTML module, but one module can back pages with different
720
- // `integrity` options, so sentinels are emitted whenever any page wants SRI
721
- // and each page then resolves or strips them on emit.
775
+ // Per-chunk SRI emits an `integrity` sentinel resolved once the chunks'
776
+ // final bytes exist. One module can back pages with different `integrity`
777
+ // options, so every page emits them and strips its own on emit.
722
778
  const htmlOption = compilation.outputOptions.html;
723
779
  const integrityOn = getHtmlGenerator().hasIntegritySentinels(compilation);
724
780
  const inject =
@@ -888,11 +944,9 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
888
944
  ? ` integrity="${getHtmlGenerator().makeChunkIntegritySentinel(chunk, kind)}"`
889
945
  : "";
890
946
  if (kind === "css") {
891
- // A CSS chunk is always loaded via `<link rel="stylesheet">`.
892
- // Clone only when the entry tag is itself a native `<link
893
- // rel="stylesheet">` (so attributes like `media` carry over);
894
- // a `<script>` entry that imported CSS, or a custom element,
895
- // gets a freshly synthesized `<link>`.
947
+ // A CSS chunk always loads through `<link rel="stylesheet">`. Clone
948
+ // only when the entry tag is itself one, so `media` carries over;
949
+ // anything else gets a freshly synthesized `<link>`.
896
950
  if (isStylesheet && tagIsNative) {
897
951
  return cloneTagWithUrl(
898
952
  originalTag,
@@ -944,10 +998,9 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
944
998
  // Parser-derived anchor (a source text scan would match `</head>` inside
945
999
  // comments or raw text).
946
1000
  const headClose = inject === "head" ? dep.headAnchor : -1;
947
- // When the entry tag is already inside <head> (tagStart < headClose),
948
- // inserting siblings at headClose would place them after the entry,
949
- // reversing runtime-before-entry execution order for deferred scripts.
950
- // Insert before the entry tag instead so the load order is preserved.
1001
+ // With the entry tag already inside `<head>`, inserting at `headClose`
1002
+ // would place siblings after it and reverse runtime-before-entry order
1003
+ // for deferred scripts. Insert before the entry tag instead.
951
1004
  const headAt =
952
1005
  headClose < 0
953
1006
  ? -1
@@ -958,29 +1011,24 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
958
1011
  let cssHtml = "";
959
1012
  let cssAt = -1;
960
1013
  if (isStylesheet) {
961
- // `<link rel="stylesheet">` entries are CSS, but a shared/runtime
962
- // JS-only chunk (e.g. `optimization.runtimeChunk`) can still sit in
963
- // the entrypoint — only clone the `<link>` for siblings that actually
964
- // produce a `.css` asset (mirrors the JS branch below), otherwise the
965
- // link points at a non-existent `.css` file (a 404, or an empty
966
- // `<style>` when inlined). Attributes like `media` still carry over.
1014
+ // WHY: a `<link rel="stylesheet">` entry is CSS, but a shared or runtime
1015
+ // JS-only chunk — `optimization.runtimeChunk`, say — can still sit in the
1016
+ // entrypoint, so the `<link>` is cloned only for siblings that actually
1017
+ // produce a `.css` asset, mirroring the JS branch below. Otherwise it
1018
+ // points at a `.css` file that does not exist: a 404, or an empty
1019
+ // `<style>` when inlined. Attributes such as `media` still carry over.
967
1020
  for (let i = 0; i < orderedChunks.length - 1; i++) {
968
1021
  if (chunkHasCss(orderedChunks[i], chunkGraph)) {
969
1022
  siblings.push(buildSibling(orderedChunks[i], "css"));
970
1023
  }
971
1024
  }
972
1025
  } else {
973
- // CSS chunks are emitted before JS chunks so the cascade is set
974
- // up before any script runs. Within CSS the order needs to match
975
- // the source's import order — `entrypoint.chunks` alone doesn't
976
- // give us that for arbitrary splitChunks layouts (splitChunks
977
- // inserts each new chunk before the entry chunk via
978
- // `insertChunk(_, before)`, so split CSS siblings end up in
979
- // *reverse* of the order they were processed — exactly the
980
- // html-webpack-plugin#1838 / mini-css-extract#959 symptom). We
981
- // re-derive the order from the entrypoint's module post-order
982
- // index, which mirrors the dependency walk and so reflects the
983
- // import order.
1026
+ // WHY: splitChunks inserts each new chunk before the entry chunk, so
1027
+ // `entrypoint.chunks` hands back split CSS siblings in reverse of the
1028
+ // order they were processed — the html-webpack-plugin#1838 and
1029
+ // mini-css-extract#959 symptom. The order is re-derived from the
1030
+ // entrypoint's module post-order index, which follows the dependency
1031
+ // walk and so the source's import order.
984
1032
  /** @type {{ chunk: Chunk, index: number, key: string }[]} */
985
1033
  const cssChunkOrder = [];
986
1034
  /** @type {Chunk[]} */
@@ -1000,18 +1048,14 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1000
1048
  key: cssChunkSortKey(chunk)
1001
1049
  });
1002
1050
  }
1003
- // Anything that isn't CSS-only stays on the JS lane, in the
1004
- // `orderedChunks` order — that preserves the runtime-first /
1005
- // vendor-before-entry invariant of `getEntrypointChunksInLoadOrder`.
1006
- // Chunks that produce no `.js` and no `.css` (e.g. wasm-only
1007
- // or asset-only) still get a `<script>` clone here so we
1008
- // keep prior behavior for users who relied on it.
1051
+ // Anything not CSS-only stays on the JS lane in `orderedChunks` order,
1052
+ // preserving the runtime-first invariant. A chunk emitting neither
1053
+ // `.js` nor `.css` still gets a clone, as it always has.
1009
1054
  if (hasJs || !hasCss) jsChunks.push(chunk);
1010
1055
  }
1011
- // If the entry chunk itself contains CSS (entry JS imports CSS
1012
- // without splitChunks separating it), fold it into the same CSS
1013
- // ordering so the entry-chunk `<link>` lands in the correct
1014
- // cascade position relative to sibling CSS chunks.
1056
+ // When the entry chunk carries CSS itself, fold it into the same
1057
+ // ordering so its `<link>` lands in the right cascade position
1058
+ // relative to the sibling CSS chunks.
1015
1059
  if (chunkHasCss(entryChunk, chunkGraph)) {
1016
1060
  cssChunkOrder.push({
1017
1061
  chunk: entryChunk,
@@ -1024,13 +1068,9 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1024
1068
  });
1025
1069
  }
1026
1070
  cssChunkOrder.sort(compareCssChunkOrder);
1027
- // Stylesheets always land in <head> when the page has one. A
1028
- // classic blocking script pins them ahead of itself (`cssAnchor`)
1029
- // so its execution never awaits later CSS; when every script is
1030
- // `defer`/module they go to the *end* of head, after the script
1031
- // tags — Vite's and html-webpack-plugin's order: the scripts
1032
- // start fetching earlier yet still execute after parsing and
1033
- // after pending stylesheets.
1071
+ // Stylesheets land in `<head>`. A classic blocking script pins them
1072
+ // ahead of itself, so it never awaits later CSS; with only `defer` and
1073
+ // module scripts they go last, which starts the script fetches earlier.
1034
1074
  cssAt =
1035
1075
  dep.headAnchor >= 0
1036
1076
  ? dep.cssAnchor >= 0 && dep.cssAnchor < dep.headAnchor
@@ -1056,15 +1096,15 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1056
1096
  if (cssHtml !== "" && dep.cssAnchor < 0) source.insert(cssAt, cssHtml);
1057
1097
  }
1058
1098
 
1059
- // Resource hints are opt-in — webpack already loads the initial chunks
1060
- // via parallel `<script>` tags, so there is no waterfall to prevent by
1061
- // default. `output.resourceHints` requests them: `true` preloads the
1062
- // entry's initial dependency chunks (runtime, vendor, split); an array
1063
- // or function adds custom hints (a function may spread the auto
1064
- // `defaultHints`). Only for extracted pages — a JS-string HTML export
1065
- // would embed the sentinels in the JS chunk. URL-referenced assets
1066
- // (fonts, images) carrying `webpackPrefetch` / `webpackPreload`
1067
- // (magic-comment or `parser.<type>.urlHints` rule) also emit here.
1099
+ // WHY: resource hints are opt-in, the initial chunks already loading
1100
+ // through parallel `<script>` tags, so there is no default waterfall to
1101
+ // prevent. `output.resourceHints` requests them: `true` preloads the entry's
1102
+ // initial dependency chunks (runtime, vendor, split), while an array or a
1103
+ // function adds custom ones and a function may spread the auto
1104
+ // `defaultHints`. Extracted pages only — a JS-string HTML export would embed
1105
+ // the sentinels in the JS chunk. A URL-referenced asset carrying
1106
+ // `webpackPrefetch` / `webpackPreload`, by magic comment or a
1107
+ // `parser.<type>.urlHints` rule, emits here too.
1068
1108
  const resourceHintResolver =
1069
1109
  ResourceHintPlugin.getCompilationResolver(compilation);
1070
1110
  const resourceHints = resourceHintResolver.hints;
@@ -1092,15 +1132,16 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1092
1132
 
1093
1133
  // === chunks channel — the entry's own initial dependency graph ===
1094
1134
  if (resourceHints !== undefined && resourceHints !== false) {
1095
- // The auto initial-graph preload as descriptors carrying their exact
1096
- // tag, built only when needed (`true`/`"prefetch"` emits them, a
1097
- // function may spread them). The entry chunk is skipped — it's
1098
- // already the `<script src>`. ESM uses `modulepreload` (fetch +
1099
- // parse), classic output `preload as="script"`, and `"prefetch"`
1100
- // opts into `<link rel="prefetch">` (idle-time fetch, no `as` / no
1101
- // `integrity` — the spec doesn't list them). Async `import()` chunks
1102
- // aren't covered here; use `module.parser.javascript.dynamicImport*`
1103
- // which routes through webpack's on-demand chunk-load runtime.
1135
+ // WHY: descriptors for the auto initial-graph preload, carrying their
1136
+ // exact tag and built only when needed — `true` or `"prefetch"` emits
1137
+ // them, and a function may spread them. The entry chunk is skipped, being
1138
+ // the `<script src>` already. ESM uses `modulepreload`, which fetches and
1139
+ // parses; classic output `preload as="script"`; and `"prefetch"` opts into
1140
+ // `<link rel="prefetch">`, an idle-time fetch with no `as` and no
1141
+ // `integrity`, which the spec does not list. An async `import()` chunk is
1142
+ // not covered here: that is
1143
+ // `module.parser.javascript.dynamicImport*`, which routes through
1144
+ // webpack's on-demand chunk-load runtime.
1104
1145
  const prefetchMode = resourceHints === "prefetch";
1105
1146
  const preloadMode = resourceHints === true;
1106
1147
  /** @type {"modulepreload" | "preload" | "prefetch"} */
@@ -1135,10 +1176,9 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1135
1176
  "javascript"
1136
1177
  )}"`
1137
1178
  : "";
1138
- // Mirror the entry tag's `nonce`/`crossorigin`/`referrerpolicy`
1139
- // (and `output.crossOriginLoading`) so the request matches the
1140
- // sibling `<script>`'s and the browser reuses it instead of
1141
- // fetching twice.
1179
+ // Mirror the entry tag's `nonce`, `crossorigin` and `referrerpolicy`,
1180
+ // so the request matches the sibling `<script>`'s and the browser
1181
+ // reuses it rather than fetching twice.
1142
1182
  const attrs = `${dep.copyableAttrsText}${crossOrigin}${integrityAttr}`;
1143
1183
  const tag = prefetchMode
1144
1184
  ? `<link rel="prefetch" href="${href}"${attrs}>`
@@ -1216,14 +1256,10 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1216
1256
  }
1217
1257
 
1218
1258
  // === assets channel — URL-referenced assets carrying `prefetch`/`preload` ===
1219
- // The plugin has already scanned the entrypoint's chunks × modules
1220
- // once and cached the URL/CSS/HTML asset deps for this entry name;
1221
- // consume that list here so this template doesn't repeat the walk.
1222
- // Each unique asset emits one `<link rel="prefetch|preload">` into
1223
- // the HTML `<head>`; the JS chunk-startup runtime skips it (no
1224
- // double `<link>` in DOM). URLs are sentinels resolved from asset
1225
- // codegen data during `HtmlModulesPlugin` render — the asset
1226
- // module might not have been codegen'd yet at this point.
1259
+
1260
+ // The plugin already walked the entrypoint once and cached this entry's
1261
+ // asset deps, so consume that list rather than repeat it. URLs stay
1262
+ // sentinels here: the asset module may not be codegen'd yet.
1227
1263
  const outputCrossOriginAttr = crossOriginLoading
1228
1264
  ? ` crossorigin="${crossOriginLoading}"`
1229
1265
  : "";
@@ -1264,12 +1300,9 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1264
1300
  finalHints.push(h);
1265
1301
  }
1266
1302
  }
1267
- // When the target environment lacks native `modulepreload` (an
1268
- // `output.environment` capability, like the JS-feature checks), append
1269
- // a tiny polyfill once per page so the hints still warm the cache there.
1270
- // `resourceHints.modulePreloadPolyfill` defaults from the target's
1271
- // modulepreload support (`output.environment.modulePreload`); `false`
1272
- // opts out (strict CSP).
1303
+ // Without native `modulepreload` the hints warm no cache, so append the
1304
+ // polyfill once per page. It defaults from the target's support, and
1305
+ // `false` opts out, which a strict CSP needs.
1273
1306
  if (
1274
1307
  rhOptions &&
1275
1308
  rhOptions.modulePreloadPolyfill &&
@@ -1279,10 +1312,9 @@ HtmlEntryDependency.Template = class HtmlEntryDependencyTemplate extends (
1279
1312
  polyfilledSources.add(source);
1280
1313
  finalHints.push(`<script>${MODULEPRELOAD_POLYFILL}</script>`);
1281
1314
  }
1282
- // Insert right after the `<head>` open tag (parser-derived) so the
1283
- // hints are the document's first fetches; fall back to the first
1284
- // blocking script (else the entry tag) when the page has no
1285
- // written `<head>` (e.g. an HTML fragment).
1315
+ // Insert just after the `<head>` open tag, so the hints are the first
1316
+ // fetches. A page with no written `<head>` falls back to the first
1317
+ // blocking script, else the entry tag.
1286
1318
  const hintAt =
1287
1319
  dep.headOpenEnd >= 0
1288
1320
  ? dep.headOpenEnd
@@ -112,10 +112,9 @@ HtmlInlineScriptDependency.Template = class HtmlInlineScriptDependencyTemplate e
112
112
  url = getHtmlGenerator().makeChunkUrlSentinel(chunk, "javascript");
113
113
  }
114
114
 
115
- // Insert ` src="…"` right after `<script` so the inline body is
116
- // served from the emitted chunk instead. The browser ignores the
117
- // remaining inline body once `src` is present, but we still clear
118
- // it below so the unprocessed JS doesn't ride along.
115
+ // Insert ` src="…"` just after `<script`, serving the body from the emitted
116
+ // chunk. The browser ignores an inline body beside `src`, but it is cleared
117
+ // below so the unprocessed JS does not ride along.
119
118
  source.insert(dep.insertPos, ` src="${url}"`);
120
119
  source.replace(dep.contentRange[0], dep.contentRange[1] - 1, "");
121
120
  }
@@ -127,10 +127,9 @@ HtmlInlineStyleDependency.Template = class HtmlInlineStyleDependencyTemplate ext
127
127
  }
128
128
  }
129
129
 
130
- // An attribute value was entity-decoded before parsing, so re-escape
131
- // the processed CSS to keep the surrounding markup valid in any
132
- // quoting context, and drop the trailing newline the CSS generator
133
- // appends so the rewritten attribute stays on one line.
130
+ // An attribute value was entity-decoded before parsing, so the processed CSS
131
+ // is re-escaped to keep the markup valid in any quoting context, and the
132
+ // generator's trailing newline dropped to keep it on one line.
134
133
  if (dep.inAttribute) {
135
134
  cssText = cssText
136
135
  .replace(TRAILING_WHITESPACE_REGEXP, "")
@@ -8,11 +8,13 @@
8
8
  const makeSerializable = require("../util/makeSerializable");
9
9
  const ContextDependency = require("./ContextDependency");
10
10
  const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall");
11
+ const importOptionsCheck = require("./importOptionsCheck");
11
12
 
12
13
  /** @import { Range } from "../javascript/JavascriptParser" */
13
- /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext<[Range]>} ObjectDeserializerContext */
14
- /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext<[Range]>} ObjectSerializerContext */
14
+ /** @import { ObjectDeserializerContext, ObjectSerializerContext } from "../serialization/ObjectMiddleware" */
15
15
  /** @import { ContextDependencyOptions } from "./ContextDependency" */
16
+ /** @import { ReplaceSource } from "webpack-sources" */
17
+ /** @import { DependencyTemplateContext } from "../DependencyTemplate" */
16
18
 
17
19
  class ImportContextDependency extends ContextDependency {
18
20
  /**
@@ -26,6 +28,8 @@ class ImportContextDependency extends ContextDependency {
26
28
 
27
29
  this.range = range;
28
30
  this.valueRange = valueRange;
31
+ /** @type {Range | undefined} */
32
+ this.optionsRange = undefined;
29
33
  }
30
34
 
31
35
  get type() {
@@ -56,6 +60,7 @@ class ImportContextDependency extends ContextDependency {
56
60
  */
57
61
  serialize(context) {
58
62
  context.write(this.valueRange);
63
+ context.write(this.optionsRange);
59
64
 
60
65
  super.serialize(context);
61
66
  }
@@ -66,6 +71,7 @@ class ImportContextDependency extends ContextDependency {
66
71
  */
67
72
  deserialize(context) {
68
73
  this.valueRange = context.read();
74
+ this.optionsRange = context.read();
69
75
 
70
76
  super.deserialize(context.rest);
71
77
  }
@@ -76,6 +82,40 @@ makeSerializable(
76
82
  "webpack/lib/dependencies/ImportContextDependency"
77
83
  );
78
84
 
79
- ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall;
85
+ ImportContextDependency.Template = class ImportContextDependencyTemplate extends (
86
+ ContextDependencyTemplateAsRequireCall
87
+ ) {
88
+ /**
89
+ * Rewrites the call around its request, dropping anything the original one
90
+ * carried after it. Overridden where a later argument must be kept.
91
+ * @param {ContextDependency} dep the dependency
92
+ * @param {ReplaceSource} source the current replace source which can be modified
93
+ * @param {string} moduleExports the expression the request is passed to
94
+ * @param {DependencyTemplateContext} templateContext the context object
95
+ * @returns {void}
96
+ */
97
+ replaceCall(dep, source, moduleExports, templateContext) {
98
+ const optionsRange = /** @type {ImportContextDependency} */ (dep)
99
+ .optionsRange;
100
+ if (optionsRange === undefined) {
101
+ super.replaceCall(dep, source, moduleExports, templateContext);
102
+ return;
103
+ }
104
+ // Request then options, in that order; their own source is kept so
105
+ // nested dependencies in them still get their replacements.
106
+ const range = /** @type {Range} */ (dep.range);
107
+ const valueRange = /** @type {Range} */ (dep.valueRange);
108
+ const check = importOptionsCheck(
109
+ templateContext.runtimeTemplate,
110
+ ["r", "o"],
111
+ `${moduleExports}(r)`
112
+ );
113
+ source.replace(range[0], valueRange[0] - 1, `(${check})(`);
114
+ // The options range excludes any parentheses the source had, so a comma
115
+ // expression would otherwise split into arguments of its own.
116
+ source.replace(valueRange[1], optionsRange[0] - 1, ", (");
117
+ source.replace(optionsRange[1], range[1] - 1, "))");
118
+ }
119
+ };
80
120
 
81
121
  module.exports = ImportContextDependency;
@@ -6,11 +6,11 @@
6
6
  "use strict";
7
7
 
8
8
  const Dependency = require("../Dependency");
9
- const Template = require("../Template");
10
9
  const makeSerializable = require("../util/makeSerializable");
11
10
  const HarmonyImportGuard = require("./HarmonyImportGuard");
12
11
  const { ImportPhaseUtils } = require("./ImportPhase");
13
12
  const ModuleDependency = require("./ModuleDependency");
13
+ const importOptionsCheck = require("./importOptionsCheck");
14
14
 
15
15
  /** @import { ReplaceSource } from "webpack-sources" */
16
16
  /** @import AsyncDependenciesBlock from "../AsyncDependenciesBlock" */
@@ -226,35 +226,14 @@ ImportDependency.Template = class ImportDependencyTemplate extends (
226
226
  }
227
227
 
228
228
  // A non-static second argument must still be evaluated (for its side
229
- // effects and evaluation order) and validated per spec. Keep it in place
230
- // and wrap it in an inline validator that mirrors the runtime checks of
231
- // the spec's `import(specifier, options)` evaluation.
229
+ // effects and evaluation order) and checked per spec, so keep it in place
230
+ // and wrap it.
232
231
  if (dep.optionsRange) {
233
- const validator = runtimeTemplate.basicFunction("o", [
234
- "try {",
235
- Template.indent([
236
- "if (o !== undefined) {",
237
- Template.indent([
238
- 'if ((typeof o !== "object" && typeof o !== "function") || o === null) throw new TypeError("The second argument to import() must be an object");',
239
- 'var a = o["with"];',
240
- "if (a !== undefined) {",
241
- Template.indent([
242
- 'if ((typeof a !== "object" && typeof a !== "function") || a === null) throw new TypeError("The \'with\' option must be an object");',
243
- "for (var k = Object.keys(a), i = 0; i < k.length; i++) {",
244
- Template.indent([
245
- 'if (typeof a[k[i]] !== "string") throw new TypeError("Import attribute values must be strings");'
246
- ]),
247
- "}"
248
- ]),
249
- "}"
250
- ]),
251
- "}"
252
- ]),
253
- "} catch (e) { return Promise.reject(e); }",
254
- `return ${content};`
255
- ]);
256
- source.replace(dep.range[0], dep.optionsRange[0] - 1, `(${validator})(`);
257
- source.replace(dep.optionsRange[1], dep.range[1] - 1, ")");
232
+ const check = importOptionsCheck(runtimeTemplate, ["o"], content);
233
+ // The options range excludes any parentheses the source had, so a
234
+ // comma expression would otherwise split into arguments of its own.
235
+ source.replace(dep.range[0], dep.optionsRange[0] - 1, `(${check})((`);
236
+ source.replace(dep.optionsRange[1], dep.range[1] - 1, "))");
258
237
  return;
259
238
  }
260
239
 
@@ -20,7 +20,7 @@ const ImportMetaContextDependency = require("./ImportMetaContextDependency");
20
20
  * } from "estree"
21
21
  */
22
22
  /** @import JavascriptParser, { Range } from "../javascript/JavascriptParser" */
23
- /** @import { ContextModuleOptions, ContextMode } from "../ContextModule" */
23
+ /** @import { ContextModuleOptions, ContextMode } from "../context/ContextModule" */
24
24
  /** @import { ChunkName } from "../Chunk" */
25
25
  /** @import { RawChunkGroupOptions } from "../ChunkGroup" */
26
26
  /** @import { RawReferencedExports, DependencyLocation } from "../Dependency" */
@@ -27,7 +27,7 @@ const getUnsupportedFeatureWarning = memoize(() =>
27
27
  require("../errors/UnsupportedFeatureWarning")
28
28
  );
29
29
 
30
- /** @import { ContextModuleOptions } from "../ContextModule" */
30
+ /** @import { ContextModuleOptions } from "../context/ContextModule" */
31
31
  /** @import JavascriptParser, { Range } from "../javascript/JavascriptParser" */
32
32
  /** @import { RawReferencedExports, DependencyLocation } from "../Dependency" */
33
33
  /**