webpack 5.102.1 → 5.104.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 (220) hide show
  1. package/README.md +121 -134
  2. package/hot/dev-server.js +18 -3
  3. package/hot/emitter-event-target.js +7 -0
  4. package/hot/lazy-compilation-node.js +45 -29
  5. package/hot/lazy-compilation-universal.js +18 -0
  6. package/hot/lazy-compilation-web.js +15 -5
  7. package/hot/load-http.js +7 -0
  8. package/hot/only-dev-server.js +19 -4
  9. package/lib/APIPlugin.js +6 -0
  10. package/lib/Chunk.js +1 -1
  11. package/lib/ChunkGraph.js +9 -7
  12. package/lib/ChunkGroup.js +8 -5
  13. package/lib/CleanPlugin.js +6 -3
  14. package/lib/CodeGenerationResults.js +2 -1
  15. package/lib/CompatibilityPlugin.js +28 -2
  16. package/lib/Compilation.js +58 -21
  17. package/lib/Compiler.js +3 -3
  18. package/lib/ConcatenationScope.js +0 -15
  19. package/lib/ContextModule.js +6 -3
  20. package/lib/ContextModuleFactory.js +6 -4
  21. package/lib/CssModule.js +6 -1
  22. package/lib/DefinePlugin.js +45 -14
  23. package/lib/DelegatedModule.js +7 -4
  24. package/lib/Dependency.js +8 -1
  25. package/lib/DependencyTemplate.js +1 -0
  26. package/lib/DllModule.js +6 -3
  27. package/lib/DotenvPlugin.js +462 -0
  28. package/lib/EnvironmentPlugin.js +19 -16
  29. package/lib/EvalSourceMapDevToolPlugin.js +16 -0
  30. package/lib/ExportsInfo.js +6 -2
  31. package/lib/ExternalModule.js +28 -35
  32. package/lib/ExternalModuleFactoryPlugin.js +11 -9
  33. package/lib/ExternalsPlugin.js +2 -1
  34. package/lib/FileSystemInfo.js +1 -1
  35. package/lib/Generator.js +10 -7
  36. package/lib/HookWebpackError.js +33 -4
  37. package/lib/HotModuleReplacementPlugin.js +22 -0
  38. package/lib/ManifestPlugin.js +235 -0
  39. package/lib/Module.js +27 -15
  40. package/lib/ModuleBuildError.js +1 -1
  41. package/lib/ModuleError.js +1 -1
  42. package/lib/ModuleFilenameHelpers.js +1 -1
  43. package/lib/ModuleGraph.js +29 -13
  44. package/lib/ModuleGraphConnection.js +2 -2
  45. package/lib/ModuleSourceTypeConstants.js +189 -0
  46. package/lib/ModuleTypeConstants.js +1 -4
  47. package/lib/ModuleWarning.js +1 -1
  48. package/lib/MultiCompiler.js +1 -1
  49. package/lib/NodeStuffPlugin.js +424 -116
  50. package/lib/NormalModule.js +23 -20
  51. package/lib/NormalModuleFactory.js +7 -10
  52. package/lib/Parser.js +1 -1
  53. package/lib/RawModule.js +7 -4
  54. package/lib/RuntimeGlobals.js +22 -4
  55. package/lib/RuntimeModule.js +1 -1
  56. package/lib/RuntimePlugin.js +27 -6
  57. package/lib/RuntimeTemplate.js +120 -57
  58. package/lib/SourceMapDevToolPlugin.js +26 -1
  59. package/lib/Template.js +17 -6
  60. package/lib/TemplatedPathPlugin.js +5 -6
  61. package/lib/WebpackError.js +0 -1
  62. package/lib/WebpackOptionsApply.js +67 -15
  63. package/lib/asset/AssetBytesGenerator.js +16 -12
  64. package/lib/asset/AssetGenerator.js +31 -26
  65. package/lib/asset/AssetSourceGenerator.js +16 -12
  66. package/lib/asset/RawDataUrlModule.js +6 -3
  67. package/lib/buildChunkGraph.js +4 -2
  68. package/lib/cache/PackFileCacheStrategy.js +6 -5
  69. package/lib/cli.js +2 -43
  70. package/lib/config/browserslistTargetHandler.js +24 -0
  71. package/lib/config/defaults.js +226 -61
  72. package/lib/config/normalization.js +4 -3
  73. package/lib/config/target.js +11 -0
  74. package/lib/container/ContainerEntryModule.js +6 -3
  75. package/lib/container/FallbackModule.js +6 -3
  76. package/lib/container/RemoteModule.js +1 -3
  77. package/lib/css/CssGenerator.js +304 -76
  78. package/lib/css/CssLoadingRuntimeModule.js +14 -4
  79. package/lib/css/CssMergeStyleSheetsRuntimeModule.js +56 -0
  80. package/lib/css/CssModulesPlugin.js +72 -67
  81. package/lib/css/CssParser.js +1726 -732
  82. package/lib/css/walkCssTokens.js +128 -11
  83. package/lib/dependencies/CachedConstDependency.js +24 -10
  84. package/lib/dependencies/CommonJsImportsParserPlugin.js +0 -9
  85. package/lib/dependencies/CommonJsPlugin.js +12 -0
  86. package/lib/dependencies/CommonJsRequireContextDependency.js +1 -1
  87. package/lib/dependencies/ContextDependencyHelpers.js +2 -2
  88. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +3 -1
  89. package/lib/dependencies/CssIcssExportDependency.js +389 -12
  90. package/lib/dependencies/CssIcssImportDependency.js +114 -51
  91. package/lib/dependencies/CssIcssSymbolDependency.js +31 -33
  92. package/lib/dependencies/CssImportDependency.js +17 -6
  93. package/lib/dependencies/CssUrlDependency.js +3 -2
  94. package/lib/dependencies/DynamicExports.js +7 -7
  95. package/lib/dependencies/ExternalModuleDependency.js +7 -4
  96. package/lib/dependencies/ExternalModuleInitFragment.js +3 -2
  97. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +96 -0
  98. package/lib/dependencies/HarmonyAcceptDependency.js +6 -1
  99. package/lib/dependencies/HarmonyAcceptImportDependency.js +2 -1
  100. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +12 -1
  101. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +35 -23
  102. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +13 -9
  103. package/lib/dependencies/HarmonyExports.js +4 -4
  104. package/lib/dependencies/HarmonyImportDependency.js +28 -27
  105. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +28 -69
  106. package/lib/dependencies/HarmonyImportSideEffectDependency.js +4 -3
  107. package/lib/dependencies/HarmonyImportSpecifierDependency.js +10 -8
  108. package/lib/dependencies/ImportDependency.js +8 -2
  109. package/lib/dependencies/ImportEagerDependency.js +6 -3
  110. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +1 -1
  111. package/lib/dependencies/ImportMetaPlugin.js +154 -9
  112. package/lib/dependencies/ImportParserPlugin.js +21 -23
  113. package/lib/dependencies/ImportPhase.js +121 -0
  114. package/lib/dependencies/ImportWeakDependency.js +6 -3
  115. package/lib/dependencies/LocalModulesHelpers.js +3 -3
  116. package/lib/dependencies/ModuleDependency.js +5 -1
  117. package/lib/dependencies/ModuleHotAcceptDependency.js +1 -1
  118. package/lib/dependencies/WorkerPlugin.js +2 -2
  119. package/lib/dependencies/getFunctionExpression.js +1 -1
  120. package/lib/esm/ExportWebpackRequireRuntimeModule.js +1 -8
  121. package/lib/esm/ModuleChunkFormatPlugin.js +5 -4
  122. package/lib/hmr/HotModuleReplacement.runtime.js +2 -1
  123. package/lib/hmr/LazyCompilationPlugin.js +5 -3
  124. package/lib/ids/IdHelpers.js +20 -8
  125. package/lib/index.js +6 -0
  126. package/lib/javascript/ChunkHelpers.js +16 -5
  127. package/lib/javascript/JavascriptGenerator.js +105 -104
  128. package/lib/javascript/JavascriptModulesPlugin.js +80 -37
  129. package/lib/javascript/JavascriptParser.js +161 -44
  130. package/lib/json/JsonGenerator.js +5 -4
  131. package/lib/json/JsonParser.js +9 -2
  132. package/lib/library/AbstractLibraryPlugin.js +1 -1
  133. package/lib/library/AmdLibraryPlugin.js +4 -1
  134. package/lib/library/ExportPropertyLibraryPlugin.js +4 -1
  135. package/lib/library/ModuleLibraryPlugin.js +41 -23
  136. package/lib/library/SystemLibraryPlugin.js +8 -1
  137. package/lib/library/UmdLibraryPlugin.js +2 -2
  138. package/lib/logging/Logger.js +5 -4
  139. package/lib/logging/createConsoleLogger.js +2 -2
  140. package/lib/node/NodeTargetPlugin.js +9 -1
  141. package/lib/node/ReadFileCompileWasmPlugin.js +0 -2
  142. package/lib/optimize/ConcatenatedModule.js +208 -167
  143. package/lib/optimize/ModuleConcatenationPlugin.js +5 -4
  144. package/lib/optimize/SideEffectsFlagPlugin.js +3 -2
  145. package/lib/optimize/SplitChunksPlugin.js +60 -46
  146. package/lib/rules/RuleSetCompiler.js +1 -1
  147. package/lib/runtime/AsyncModuleRuntimeModule.js +28 -18
  148. package/lib/runtime/AutoPublicPathRuntimeModule.js +8 -3
  149. package/lib/runtime/GetChunkFilenameRuntimeModule.js +3 -2
  150. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +89 -55
  151. package/lib/schemes/HttpUriPlugin.js +78 -7
  152. package/lib/serialization/AggregateErrorSerializer.js +1 -2
  153. package/lib/serialization/ObjectMiddleware.js +0 -2
  154. package/lib/serialization/SingleItemMiddleware.js +1 -1
  155. package/lib/sharing/ConsumeSharedModule.js +1 -1
  156. package/lib/sharing/ConsumeSharedPlugin.js +5 -3
  157. package/lib/sharing/ProvideSharedModule.js +1 -1
  158. package/lib/sharing/resolveMatchedConfigs.js +15 -9
  159. package/lib/sharing/utils.js +1 -1
  160. package/lib/stats/DefaultStatsFactoryPlugin.js +8 -5
  161. package/lib/stats/DefaultStatsPresetPlugin.js +1 -1
  162. package/lib/stats/DefaultStatsPrinterPlugin.js +1 -1
  163. package/lib/util/StringXor.js +1 -1
  164. package/lib/util/URLAbsoluteSpecifier.js +2 -2
  165. package/lib/util/binarySearchBounds.js +2 -2
  166. package/lib/util/comparators.js +54 -76
  167. package/lib/util/compileBooleanMatcher.js +78 -6
  168. package/lib/util/createHash.js +20 -199
  169. package/lib/util/deprecation.js +1 -1
  170. package/lib/util/deterministicGrouping.js +6 -3
  171. package/lib/util/fs.js +75 -75
  172. package/lib/util/hash/BatchedHash.js +10 -9
  173. package/lib/util/hash/BulkUpdateHash.js +138 -0
  174. package/lib/util/hash/DebugHash.js +75 -0
  175. package/lib/util/hash/hash-digest.js +216 -0
  176. package/lib/util/identifier.js +82 -17
  177. package/lib/util/internalSerializables.js +2 -6
  178. package/lib/util/runtime.js +3 -3
  179. package/lib/util/source.js +2 -2
  180. package/lib/wasm/EnableWasmLoadingPlugin.js +10 -4
  181. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +3 -2
  182. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +11 -7
  183. package/lib/wasm-sync/WebAssemblyGenerator.js +9 -6
  184. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +11 -6
  185. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +6 -2
  186. package/lib/web/FetchCompileWasmPlugin.js +0 -2
  187. package/lib/webpack.js +85 -82
  188. package/module.d.ts +5 -0
  189. package/package.json +34 -28
  190. package/schemas/WebpackOptions.check.js +1 -1
  191. package/schemas/WebpackOptions.json +160 -101
  192. package/schemas/plugins/{css/CssAutoParserOptions.check.d.ts → ManifestPlugin.check.d.ts} +1 -1
  193. package/schemas/plugins/ManifestPlugin.check.js +6 -0
  194. package/schemas/plugins/ManifestPlugin.json +98 -0
  195. package/schemas/plugins/SourceMapDevToolPlugin.check.js +1 -1
  196. package/schemas/plugins/SourceMapDevToolPlugin.json +16 -3
  197. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  198. package/schemas/plugins/container/ContainerReferencePlugin.json +4 -1
  199. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  200. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  201. package/schemas/plugins/container/ModuleFederationPlugin.json +4 -1
  202. package/schemas/plugins/css/CssModuleGeneratorOptions.check.js +1 -1
  203. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  204. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  205. package/schemas/plugins/json/JsonModulesPluginParser.check.js +1 -1
  206. package/types.d.ts +771 -436
  207. package/lib/ModuleSourceTypesConstants.js +0 -123
  208. package/lib/dependencies/CssLocalIdentifierDependency.js +0 -250
  209. package/lib/dependencies/CssSelfLocalIdentifierDependency.js +0 -112
  210. package/schemas/plugins/css/CssAutoGeneratorOptions.check.d.ts +0 -7
  211. package/schemas/plugins/css/CssAutoGeneratorOptions.check.js +0 -6
  212. package/schemas/plugins/css/CssAutoGeneratorOptions.json +0 -3
  213. package/schemas/plugins/css/CssAutoParserOptions.check.js +0 -6
  214. package/schemas/plugins/css/CssAutoParserOptions.json +0 -3
  215. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.d.ts +0 -7
  216. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.js +0 -6
  217. package/schemas/plugins/css/CssGlobalGeneratorOptions.json +0 -3
  218. package/schemas/plugins/css/CssGlobalParserOptions.check.d.ts +0 -7
  219. package/schemas/plugins/css/CssGlobalParserOptions.check.js +0 -6
  220. package/schemas/plugins/css/CssGlobalParserOptions.json +0 -3
@@ -8,8 +8,12 @@ const RuntimeGlobals = require("../RuntimeGlobals");
8
8
  const Template = require("../Template");
9
9
  const HelperRuntimeModule = require("./HelperRuntimeModule");
10
10
 
11
+ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
12
+ /** @typedef {import("../Module").ExportsType} ExportsType */
13
+ /** @typedef {import("../ChunkGraph").ModuleId} ModuleId */
14
+
11
15
  /**
12
- * @param {import("../Module").ExportsType} exportsType exports type
16
+ * @param {ExportsType} exportsType exports type
13
17
  * @returns {string} mode
14
18
  */
15
19
  function getMakeDeferredNamespaceModeFromExportsType(exportsType) {
@@ -19,61 +23,81 @@ function getMakeDeferredNamespaceModeFromExportsType(exportsType) {
19
23
  if (exportsType === "dynamic") return `/* ${exportsType} */ 3`;
20
24
  return "";
21
25
  }
26
+
22
27
  /**
23
- * @param {import("../ModuleTemplate").RuntimeTemplate} _runtimeTemplate runtimeTemplate
24
- * @param {import("../Module").ExportsType} exportsType exportsType
25
28
  * @param {string} moduleId moduleId
26
- * @param {(import("../ChunkGraph").ModuleId | null)[]} asyncDepsIds asyncDepsIds
27
- * @returns {string} function
29
+ * @param {ExportsType} exportsType exportsType
30
+ * @param {(ModuleId | null)[]} asyncDepsIds asyncDepsIds
31
+ * @param {RuntimeRequirements} runtimeRequirements runtime requirements
32
+ * @returns {string} call make optimized deferred namespace object
28
33
  */
29
34
  function getOptimizedDeferredModule(
30
- _runtimeTemplate,
31
- exportsType,
32
35
  moduleId,
33
- asyncDepsIds
36
+ exportsType,
37
+ asyncDepsIds,
38
+ runtimeRequirements
34
39
  ) {
35
- const isAsync = asyncDepsIds && asyncDepsIds.length;
36
- const init = `${RuntimeGlobals.require}(${moduleId})${
37
- isAsync ? `[${RuntimeGlobals.asyncModuleExportSymbol}]` : ""
38
- }`;
39
- const props = [
40
- `/* ${exportsType} */ get a() {`,
41
- // if exportsType is "namespace" we can generate the most optimized code,
42
- // on the second access, we can avoid trigger the getter.
43
- // we can also do this if exportsType is "dynamic" and there is a "__esModule" property on it.
44
- exportsType === "namespace" || exportsType === "dynamic"
45
- ? Template.indent([
46
- `var exports = ${init};`,
47
- `${
48
- exportsType === "dynamic" ? "if (exports.__esModule) " : ""
49
- }Object.defineProperty(this, "a", { value: exports });`,
50
- "return exports;"
51
- ])
52
- : Template.indent([`return ${init};`]),
53
- isAsync ? "}," : "}",
54
- isAsync
55
- ? `[${
56
- RuntimeGlobals.makeDeferredNamespaceObjectSymbol
57
- }]: ${JSON.stringify(asyncDepsIds.filter((x) => x !== null))}`
40
+ runtimeRequirements.add(RuntimeGlobals.makeOptimizedDeferredNamespaceObject);
41
+ const mode = getMakeDeferredNamespaceModeFromExportsType(exportsType);
42
+ return `${RuntimeGlobals.makeOptimizedDeferredNamespaceObject}(${moduleId}, ${mode}${
43
+ asyncDepsIds.length > 0
44
+ ? `, ${JSON.stringify(asyncDepsIds.filter((x) => x !== null))}`
58
45
  : ""
59
- ];
60
- return Template.asString(["{", Template.indent(props), "}"]);
46
+ })`;
61
47
  }
62
48
 
63
- const strictModuleCache = [
64
- "if (cachedModule && cachedModule.error === undefined) {",
65
- Template.indent([
66
- "var exports = cachedModule.exports;",
67
- "if (mode == 0) return exports;",
68
- `if (mode == 1) return ${RuntimeGlobals.createFakeNamespaceObject}(exports);`,
69
- `if (mode == 2) return ${RuntimeGlobals.createFakeNamespaceObject}(exports, 2);`,
70
- `if (mode == 3) return ${RuntimeGlobals.createFakeNamespaceObject}(exports, 6);` // 2 | 4
71
- ]),
72
- "}"
73
- ];
74
- const nonStrictModuleCache = [
75
- "// optimization not applied when output.strictModuleErrorHandling is off"
76
- ];
49
+ class MakeOptimizedDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
50
+ /**
51
+ * @param {boolean} hasAsyncRuntime if async module is used.
52
+ */
53
+ constructor(hasAsyncRuntime) {
54
+ super("make optimized deferred namespace object");
55
+ this.hasAsyncRuntime = hasAsyncRuntime;
56
+ }
57
+
58
+ /**
59
+ * @returns {string | null} runtime code
60
+ */
61
+ generate() {
62
+ if (!this.compilation) return null;
63
+ const fn = RuntimeGlobals.makeOptimizedDeferredNamespaceObject;
64
+ const hasAsync = this.hasAsyncRuntime;
65
+ return Template.asString([
66
+ // Note: must be a function (not arrow), because this is used in body!
67
+ `${fn} = function(moduleId, mode${hasAsync ? ", asyncDeps" : ""}) {`,
68
+ Template.indent([
69
+ "// mode: 0 => namespace (esm)",
70
+ "// mode: 1 => default-only (esm strict cjs)",
71
+ "// mode: 2 => default-with-named (esm-cjs compat)",
72
+ "// mode: 3 => dynamic (if exports has __esModule, then esm, otherwise default-with-named)",
73
+ "var r = this;",
74
+ hasAsync ? "var isAsync = asyncDeps && asyncDeps.length;" : "",
75
+ "var obj = {",
76
+ Template.indent([
77
+ "get a() {",
78
+ Template.indent([
79
+ "var exports = r(moduleId);",
80
+ hasAsync
81
+ ? `if(isAsync) exports = exports[${RuntimeGlobals.asyncModuleExportSymbol}];`
82
+ : "",
83
+ // if exportsType is "namespace" we can generate the most optimized code,
84
+ // on the second access, we can avoid trigger the getter.
85
+ // we can also do this if exportsType is "dynamic" and there is a "__esModule" property on it.
86
+ 'if(mode == 0 || (mode == 3 && exports.__esModule)) Object.defineProperty(this, "a", { value: exports });',
87
+ "return exports;"
88
+ ]),
89
+ "}"
90
+ ]),
91
+ "};",
92
+ hasAsync
93
+ ? `if(isAsync) obj[${RuntimeGlobals.deferredModuleAsyncTransitiveDependenciesSymbol}] = asyncDeps;`
94
+ : "",
95
+ "return obj;"
96
+ ]),
97
+ "};"
98
+ ]);
99
+ }
100
+ }
77
101
 
78
102
  class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
79
103
  /**
@@ -92,8 +116,6 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
92
116
  const { runtimeTemplate } = this.compilation;
93
117
  const fn = RuntimeGlobals.makeDeferredNamespaceObject;
94
118
  const hasAsync = this.hasAsyncRuntime;
95
- const strictError =
96
- this.compilation.options.output.strictModuleErrorHandling;
97
119
  const init = runtimeTemplate.supportsOptionalChaining()
98
120
  ? "init?.();"
99
121
  : "if (init) init();";
@@ -104,7 +126,18 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
104
126
  "// mode: 3 => dynamic (if exports has __esModule, then esm, otherwise default-with-named)",
105
127
  "",
106
128
  "var cachedModule = __webpack_module_cache__[moduleId];",
107
- ...(strictError ? strictModuleCache : nonStrictModuleCache),
129
+ "if (cachedModule && cachedModule.error === undefined) {",
130
+ Template.indent([
131
+ "var exports = cachedModule.exports;",
132
+ hasAsync
133
+ ? `if (${RuntimeGlobals.asyncModuleExportSymbol} in exports) exports = exports[${RuntimeGlobals.asyncModuleExportSymbol}];`
134
+ : "",
135
+ "if (mode == 0) return exports;",
136
+ `if (mode == 1) return ${RuntimeGlobals.createFakeNamespaceObject}(exports);`,
137
+ `if (mode == 2) return ${RuntimeGlobals.createFakeNamespaceObject}(exports, 2);`,
138
+ `if (mode == 3) return ${RuntimeGlobals.createFakeNamespaceObject}(exports, 6);` // 2 | 4
139
+ ]),
140
+ "}",
108
141
  "",
109
142
  `var init = ${runtimeTemplate.basicFunction("", [
110
143
  `ns = ${RuntimeGlobals.require}(moduleId);`,
@@ -137,9 +170,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
137
170
  "}"
138
171
  ])};`,
139
172
  "",
140
- `var ns = ${
141
- strictError ? "" : "cachedModule && cachedModule.exports || "
142
- }__webpack_module_deferred_exports__[moduleId] || (__webpack_module_deferred_exports__[moduleId] = { __proto__: null });`,
173
+ "var ns = __webpack_module_deferred_exports__[moduleId] || (__webpack_module_deferred_exports__[moduleId] = { __proto__: null });",
143
174
  "var handler = {",
144
175
  Template.indent([
145
176
  "__proto__: null,",
@@ -161,7 +192,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
161
192
  'case "__esModule":',
162
193
  "case Symbol.toStringTag:",
163
194
  hasAsync
164
- ? `case ${RuntimeGlobals.makeDeferredNamespaceObjectSymbol}:`
195
+ ? `case ${RuntimeGlobals.deferredModuleAsyncTransitiveDependenciesSymbol}:`
165
196
  : "",
166
197
  Template.indent("return true;"),
167
198
  'case "then":',
@@ -208,7 +239,10 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
208
239
  }
209
240
  }
210
241
 
211
- module.exports = MakeDeferredNamespaceObjectRuntimeModule;
242
+ module.exports.MakeDeferredNamespaceObjectRuntimeModule =
243
+ MakeDeferredNamespaceObjectRuntimeModule;
244
+ module.exports.MakeOptimizedDeferredNamespaceObjectRuntimeModule =
245
+ MakeOptimizedDeferredNamespaceObjectRuntimeModule;
212
246
  module.exports.getMakeDeferredNamespaceModeFromExportsType =
213
247
  getMakeDeferredNamespaceModeFromExportsType;
214
248
  module.exports.getOptimizedDeferredModule = getOptimizedDeferredModule;
@@ -34,6 +34,8 @@ const memoize = require("../util/memoize");
34
34
  const getHttp = memoize(() => require("http"));
35
35
  const getHttps = memoize(() => require("https"));
36
36
 
37
+ const MAX_REDIRECTS = 5;
38
+
37
39
  /**
38
40
  * @param {typeof import("http") | typeof import("https")} request request
39
41
  * @param {string | URL | undefined} proxy proxy
@@ -200,6 +202,22 @@ const areLockfileEntriesEqual = (a, b) =>
200
202
  const entryToString = (entry) =>
201
203
  `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`;
202
204
 
205
+ /**
206
+ * Sanitize URL for inclusion in error messages
207
+ * @param {string} href URL string to sanitize
208
+ * @returns {string} sanitized URL text for logs/errors
209
+ */
210
+ const sanitizeUrlForError = (href) => {
211
+ try {
212
+ const u = new URL(href);
213
+ return `${u.protocol}//${u.host}`;
214
+ } catch (_err) {
215
+ return String(href)
216
+ .slice(0, 200)
217
+ .replace(/[\r\n]/g, "");
218
+ }
219
+ };
220
+
203
221
  class Lockfile {
204
222
  constructor() {
205
223
  this.version = 1;
@@ -317,7 +335,7 @@ const cachedWithoutKey = (fn) => {
317
335
  * @template R
318
336
  * @param {FnWithKey<T, R>} fn function
319
337
  * @param {FnWithKey<T, R>=} forceFn function for the second try
320
- * @returns {(FnWithKey<T, R>) & { force: FnWithKey<T, R> }} cached function
338
+ * @returns {FnWithKey<T, R> & { force: FnWithKey<T, R> }} cached function
321
339
  */
322
340
  const cachedWithKey = (fn, forceFn = fn) => {
323
341
  /**
@@ -636,12 +654,47 @@ class HttpUriPlugin {
636
654
  };
637
655
 
638
656
  for (const { scheme, fetch } of schemes) {
657
+ /**
658
+ * @param {string} location Location header value (relative or absolute)
659
+ * @param {string} base current absolute URL
660
+ * @returns {string} absolute, validated redirect target
661
+ */
662
+ const validateRedirectLocation = (location, base) => {
663
+ let nextUrl;
664
+ try {
665
+ nextUrl = new URL(location, base);
666
+ } catch (err) {
667
+ throw new Error(
668
+ `Invalid redirect URL: ${sanitizeUrlForError(location)}`,
669
+ { cause: err }
670
+ );
671
+ }
672
+ if (nextUrl.protocol !== "http:" && nextUrl.protocol !== "https:") {
673
+ throw new Error(
674
+ `Redirected URL uses disallowed protocol: ${sanitizeUrlForError(nextUrl.href)}`
675
+ );
676
+ }
677
+ if (!isAllowed(nextUrl.href)) {
678
+ throw new Error(
679
+ `${nextUrl.href} doesn't match the allowedUris policy after redirect. These URIs are allowed:\n${allowedUris
680
+ .map((uri) => ` - ${uri}`)
681
+ .join("\n")}`
682
+ );
683
+ }
684
+ return nextUrl.href;
685
+ };
639
686
  /**
640
687
  * @param {string} url URL
641
688
  * @param {string | null} integrity integrity
642
689
  * @param {(err: Error | null, resolveContentResult?: ResolveContentResult) => void} callback callback
690
+ * @param {number=} redirectCount number of followed redirects
643
691
  */
644
- const resolveContent = (url, integrity, callback) => {
692
+ const resolveContent = (
693
+ url,
694
+ integrity,
695
+ callback,
696
+ redirectCount = 0
697
+ ) => {
645
698
  /**
646
699
  * @param {Error | null} err error
647
700
  * @param {FetchResult=} _result fetch result
@@ -653,8 +706,18 @@ class HttpUriPlugin {
653
706
  const result = /** @type {FetchResult} */ (_result);
654
707
 
655
708
  if ("location" in result) {
709
+ // Validate redirect target before following
710
+ let absolute;
711
+ try {
712
+ absolute = validateRedirectLocation(result.location, url);
713
+ } catch (err_) {
714
+ return callback(/** @type {Error} */ (err_));
715
+ }
716
+ if (redirectCount >= MAX_REDIRECTS) {
717
+ return callback(new Error("Too many redirects"));
718
+ }
656
719
  return resolveContent(
657
- result.location,
720
+ absolute,
658
721
  integrity,
659
722
  (err, innerResult) => {
660
723
  if (err) return callback(err);
@@ -665,7 +728,8 @@ class HttpUriPlugin {
665
728
  content,
666
729
  storeLock: storeLock && result.storeLock
667
730
  });
668
- }
731
+ },
732
+ redirectCount + 1
669
733
  );
670
734
  }
671
735
 
@@ -781,9 +845,16 @@ class HttpUriPlugin {
781
845
  res.statusCode >= 301 &&
782
846
  res.statusCode <= 308
783
847
  ) {
784
- const result = {
785
- location: new URL(location, url).href
786
- };
848
+ let absolute;
849
+ try {
850
+ absolute = validateRedirectLocation(location, url);
851
+ } catch (err) {
852
+ logger.log(
853
+ `GET ${url} [${res.statusCode}] -> ${String(location)} (rejected: ${/** @type {Error} */ (err).message})`
854
+ );
855
+ return callback(/** @type {Error} */ (err));
856
+ }
857
+ const result = { location: absolute };
787
858
  if (
788
859
  !cachedResult ||
789
860
  !("location" in cachedResult) ||
@@ -7,7 +7,7 @@
7
7
  /** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
8
8
  /** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
9
9
 
10
- /** @typedef {Error & { cause: unknown, errors: EXPECTED_ANY[] }} AggregateError */
10
+ /** @typedef {Error & { cause?: unknown, errors: EXPECTED_ANY[] }} AggregateError */
11
11
 
12
12
  class AggregateErrorSerializer {
13
13
  /**
@@ -27,7 +27,6 @@ class AggregateErrorSerializer {
27
27
  */
28
28
  deserialize(context) {
29
29
  const errors = context.read();
30
- // @ts-expect-error ES2018 doesn't `AggregateError`, but it can be used by developers
31
30
  // eslint-disable-next-line n/no-unsupported-features/es-builtins, n/no-unsupported-features/es-syntax, unicorn/error-message
32
31
  const err = new AggregateError(errors);
33
32
 
@@ -157,11 +157,9 @@ jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError));
157
157
  jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError));
158
158
  jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError));
159
159
 
160
- // @ts-expect-error ES2018 doesn't `AggregateError`, but it can be used by developers
161
160
  // eslint-disable-next-line n/no-unsupported-features/es-builtins, n/no-unsupported-features/es-syntax
162
161
  if (typeof AggregateError !== "undefined") {
163
162
  jsTypes.set(
164
- // @ts-expect-error ES2018 doesn't `AggregateError`, but it can be used by developers
165
163
  // eslint-disable-next-line n/no-unsupported-features/es-builtins, n/no-unsupported-features/es-syntax
166
164
  AggregateError,
167
165
  new AggregateErrorSerializer()
@@ -8,7 +8,7 @@ const SerializerMiddleware = require("./SerializerMiddleware");
8
8
 
9
9
  /** @typedef {EXPECTED_ANY} DeserializedType */
10
10
  /** @typedef {EXPECTED_ANY[]} SerializedType */
11
- /** @typedef {{}} Context */
11
+ /** @typedef {EXPECTED_OBJECT} Context */
12
12
 
13
13
  /**
14
14
  * @extends {SerializerMiddleware<DeserializedType, SerializedType, Context>}
@@ -8,7 +8,7 @@
8
8
  const { RawSource } = require("webpack-sources");
9
9
  const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
10
10
  const Module = require("../Module");
11
- const { CONSUME_SHARED_TYPES } = require("../ModuleSourceTypesConstants");
11
+ const { CONSUME_SHARED_TYPES } = require("../ModuleSourceTypeConstants");
12
12
  const {
13
13
  WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE
14
14
  } = require("../ModuleTypeConstants");
@@ -119,11 +119,13 @@ class ConsumeSharedPlugin {
119
119
  normalModuleFactory
120
120
  );
121
121
 
122
- /** @type {Map<string, ConsumeOptions>} */
122
+ /** @typedef {Map<string, ConsumeOptions>} Consumes */
123
+
124
+ /** @type {Consumes} */
123
125
  let unresolvedConsumes;
124
- /** @type {Map<string, ConsumeOptions>} */
126
+ /** @type {Consumes} */
125
127
  let resolvedConsumes;
126
- /** @type {Map<string, ConsumeOptions>} */
128
+ /** @type {Consumes} */
127
129
  let prefixedConsumes;
128
130
  const promise = resolveMatchedConfigs(compilation, this._consumes).then(
129
131
  ({ resolved, unresolved, prefixed }) => {
@@ -7,7 +7,7 @@
7
7
 
8
8
  const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
9
9
  const Module = require("../Module");
10
- const { SHARED_INIT_TYPES } = require("../ModuleSourceTypesConstants");
10
+ const { SHARED_INIT_TYPES } = require("../ModuleSourceTypeConstants");
11
11
  const { WEBPACK_MODULE_TYPE_PROVIDE } = require("../ModuleTypeConstants");
12
12
  const RuntimeGlobals = require("../RuntimeGlobals");
13
13
  const makeSerializable = require("../util/makeSerializable");
@@ -10,14 +10,20 @@ const LazySet = require("../util/LazySet");
10
10
 
11
11
  /** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */
12
12
  /** @typedef {import("../Compilation")} Compilation */
13
+ /** @typedef {import("../Compilation").FileSystemDependencies} FileSystemDependencies */
13
14
  /** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */
14
15
 
16
+ /**
17
+ * @template T
18
+ * @typedef {Map<string, T>} MatchedConfigsItem
19
+ */
20
+
15
21
  /**
16
22
  * @template T
17
23
  * @typedef {object} MatchedConfigs
18
- * @property {Map<string, T>} resolved
19
- * @property {Map<string, T>} unresolved
20
- * @property {Map<string, T>} prefixed
24
+ * @property {MatchedConfigsItem<T>} resolved
25
+ * @property {MatchedConfigsItem<T>} unresolved
26
+ * @property {MatchedConfigsItem<T>} prefixed
21
27
  */
22
28
 
23
29
  /** @type {ResolveOptionsWithDependencyType} */
@@ -30,11 +36,11 @@ const RESOLVE_OPTIONS = { dependencyType: "esm" };
30
36
  * @returns {Promise<MatchedConfigs<T>>} resolved matchers
31
37
  */
32
38
  module.exports.resolveMatchedConfigs = (compilation, configs) => {
33
- /** @type {Map<string, T>} */
39
+ /** @type {MatchedConfigsItem<T>} */
34
40
  const resolved = new Map();
35
- /** @type {Map<string, T>} */
41
+ /** @type {MatchedConfigsItem<T>} */
36
42
  const unresolved = new Map();
37
- /** @type {Map<string, T>} */
43
+ /** @type {MatchedConfigsItem<T>} */
38
44
  const prefixed = new Map();
39
45
  /** @type {ResolveContext} */
40
46
  const resolveContext = {
@@ -84,15 +90,15 @@ module.exports.resolveMatchedConfigs = (compilation, configs) => {
84
90
  })
85
91
  ).then(() => {
86
92
  compilation.contextDependencies.addAll(
87
- /** @type {LazySet<string>} */
93
+ /** @type {FileSystemDependencies} */
88
94
  (resolveContext.contextDependencies)
89
95
  );
90
96
  compilation.fileDependencies.addAll(
91
- /** @type {LazySet<string>} */
97
+ /** @type {FileSystemDependencies} */
92
98
  (resolveContext.fileDependencies)
93
99
  );
94
100
  compilation.missingDependencies.addAll(
95
- /** @type {LazySet<string>} */
101
+ /** @type {FileSystemDependencies} */
96
102
  (resolveContext.missingDependencies)
97
103
  );
98
104
  return { resolved, unresolved, prefixed };
@@ -379,7 +379,7 @@ const getRequiredVersionFromDescriptionFile = (data, packageName) => {
379
379
  packageName in dependency
380
380
  ) {
381
381
  return normalizeVersion(
382
- /** @type {Exclude<JsonPrimitive, null | boolean| number>} */ (
382
+ /** @type {Exclude<JsonPrimitive, null | boolean | number>} */ (
383
383
  dependency[packageName]
384
384
  )
385
385
  );
@@ -49,6 +49,8 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
49
49
  /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
50
50
  /** @typedef {import("../ModuleProfile")} ModuleProfile */
51
51
  /** @typedef {import("../WebpackError")} WebpackError */
52
+ /** @typedef {import("../serialization/AggregateErrorSerializer").AggregateError} AggregateError */
53
+ /** @typedef {import("../serialization/ErrorObjectSerializer").ErrorWithCause} ErrorWithCause */
52
54
  /** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
53
55
 
54
56
  /**
@@ -370,13 +372,17 @@ const uniqueArray = (items, selector) => {
370
372
  const uniqueOrderedArray = (items, selector, comparator) =>
371
373
  uniqueArray(items, selector).sort(comparator);
372
374
 
373
- /** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues<T, R> */
375
+ /**
376
+ * @template T
377
+ * @template R
378
+ * @typedef {{ [P in keyof T]: R }} MappedValues<T, R>
379
+ */
374
380
 
375
381
  /**
376
382
  * @template {object} T
377
383
  * @template {object} R
378
384
  * @param {T} obj object to be mapped
379
- * @param {function(T[keyof T], keyof T): R} fn mapping function
385
+ * @param {(value: T[keyof T], key: keyof T) => R} fn mapping function
380
386
  * @returns {MappedValues<T, R>} mapped object
381
387
  */
382
388
  const mapObject = (obj, fn) => {
@@ -406,9 +412,6 @@ const countWithChildren = (compilation, getItems) => {
406
412
  return count;
407
413
  };
408
414
 
409
- /** @typedef {Error & { cause?: unknown }} ErrorWithCause */
410
- /** @typedef {Error & { errors: EXPECTED_ANY[] }} AggregateError */
411
-
412
415
  /** @type {ExtractorsByOption<string | ErrorWithCause | AggregateError | WebpackError, StatsError>} */
413
416
  const EXTRACT_ERROR = {
414
417
  _: (object, error, context, { requestShortener }) => {
@@ -30,7 +30,7 @@ const applyDefaults = (options, defaults) => {
30
30
  }
31
31
  };
32
32
 
33
- /** @typedef {{ [Key in Exclude<StatsValue, boolean | object | "normal">]: StatsOptions }} NamedPresets */
33
+ /** @typedef {{ [Key in Exclude<StatsValue, boolean | EXPECTED_OBJECT | "normal">]: StatsOptions }} NamedPresets */
34
34
 
35
35
  /** @type {NamedPresets} */
36
36
  const NAMED_PRESETS = {
@@ -76,7 +76,7 @@ const getResourceName = (resource) => {
76
76
 
77
77
  /**
78
78
  * @param {string} name module name
79
- * @returns {[string,string]} prefix and module name
79
+ * @returns {[string, string]} prefix and module name
80
80
  */
81
81
  const getModuleName = (name) => {
82
82
  const [, prefix, resource] =
@@ -36,7 +36,7 @@
36
36
  */
37
37
  class StringXor {
38
38
  constructor() {
39
- /** @type {Buffer|undefined} */
39
+ /** @type {Buffer | undefined} */
40
40
  this._value = undefined;
41
41
  }
42
42
 
@@ -5,7 +5,7 @@
5
5
 
6
6
  "use strict";
7
7
 
8
- /** @typedef {(error: Error|null, result?: Buffer) => void} ErrorFirstCallback */
8
+ /** @typedef {(error: Error | null, result?: Buffer) => void} ErrorFirstCallback */
9
9
 
10
10
  const backSlashCharCode = "\\".charCodeAt(0);
11
11
  const slashCharCode = "/".charCodeAt(0);
@@ -25,7 +25,7 @@ const queryCharCode = "?".charCodeAt(0);
25
25
  * e.g. Absolute specifiers like 'file:///user/webpack/index.js'
26
26
  * https://tools.ietf.org/html/rfc3986#section-3.1
27
27
  * @param {string} specifier specifier
28
- * @returns {string|undefined} scheme if absolute URL specifier provided
28
+ * @returns {string | undefined} scheme if absolute URL specifier provided
29
29
  */
30
30
  function getScheme(specifier) {
31
31
  const start = specifier.charCodeAt(0);
@@ -8,8 +8,8 @@
8
8
  /* cspell:disable-next-line */
9
9
  // Refactor: Peter Somogyvari @petermetz
10
10
 
11
- /** @typedef {">=" | "<=" | "<" | ">" | "-" } BinarySearchPredicate */
12
- /** @typedef {"GE" | "GT" | "LT" | "LE" | "EQ" } SearchPredicateSuffix */
11
+ /** @typedef {">=" | "<=" | "<" | ">" | "-"} BinarySearchPredicate */
12
+ /** @typedef {"GE" | "GT" | "LT" | "LE" | "EQ"} SearchPredicateSuffix */
13
13
 
14
14
  /**
15
15
  * Helper function for compiling binary search functions.