@depup/webpack 5.111.1-depup.2 → 5.112.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 (775) hide show
  1. package/README.md +4 -8
  2. package/changes.json +3 -19
  3. package/lib/Chunk.js +3 -966
  4. package/lib/Compilation.js +224 -106
  5. package/lib/Compiler.js +19 -19
  6. package/lib/Dependency.js +3 -551
  7. package/lib/DependencyTemplate.js +3 -70
  8. package/lib/EntryPlugin.js +3 -68
  9. package/lib/Entrypoint.js +3 -121
  10. package/lib/ExternalsPlugin.js +3 -92
  11. package/lib/FileSystemInfo.js +3 -4629
  12. package/lib/InitFragment.js +3 -204
  13. package/lib/LibraryTemplatePlugin.js +3 -46
  14. package/lib/ModuleFilenameHelpers.js +3 -400
  15. package/lib/ModuleNotFoundError.js +2 -2
  16. package/lib/MultiCompiler.js +37 -8
  17. package/lib/NormalModule.js +3 -2242
  18. package/lib/NullFactory.js +3 -22
  19. package/lib/ProgressPlugin.js +3 -908
  20. package/lib/RawModule.js +3 -197
  21. package/lib/RequestShortener.js +3 -37
  22. package/lib/SingleEntryPlugin.js +1 -1
  23. package/lib/WebpackError.js +2 -2
  24. package/lib/asset/AssetBytesGenerator.js +8 -8
  25. package/lib/asset/AssetBytesParser.js +3 -3
  26. package/lib/asset/AssetGenerator.js +36 -22
  27. package/lib/asset/AssetModule.js +2 -2
  28. package/lib/asset/AssetModulesPlugin.js +6 -9
  29. package/lib/asset/AssetParser.js +3 -3
  30. package/lib/asset/AssetSourceGenerator.js +8 -8
  31. package/lib/asset/AssetSourceParser.js +3 -3
  32. package/lib/asset/RawDataUrlModule.js +17 -10
  33. package/lib/asset/WebManifestGenerator.js +7 -7
  34. package/lib/asset/WebManifestParser.js +5 -5
  35. package/lib/async-modules/AsyncModuleHelpers.js +6 -5
  36. package/lib/async-modules/AwaitDependenciesInitFragment.js +4 -4
  37. package/lib/async-modules/InferAsyncModulesPlugin.js +4 -3
  38. package/lib/async-modules/isGeneratorLowered.js +3 -3
  39. package/lib/bun/BunTargetPlugin.js +1 -1
  40. package/lib/cache/AddBuildDependenciesPlugin.js +2 -19
  41. package/lib/{Cache.js → cache/Cache.js} +1 -1
  42. package/lib/{CacheFacade.js → cache/CacheFacade.js} +5 -5
  43. package/lib/cache/IdleFileCachePlugin.js +2 -2
  44. package/lib/cache/MemoryCachePlugin.js +2 -2
  45. package/lib/cache/MemoryWithGcCachePlugin.js +2 -2
  46. package/lib/cache/PackFileCacheStrategy.js +8 -10
  47. package/lib/cache/ResolverCachePlugin.js +8 -4
  48. package/lib/cache/mergeEtags.js +1 -1
  49. package/lib/{OptionsApply.js → config/OptionsApply.js} +3 -3
  50. package/lib/{PlatformPlugin.js → config/PlatformPlugin.js} +2 -2
  51. package/lib/{WebpackOptionsApply.js → config/WebpackOptionsApply.js} +217 -200
  52. package/lib/{WebpackOptionsDefaulter.js → config/WebpackOptionsDefaulter.js} +3 -3
  53. package/lib/config/browserslistTargetHandler.js +1 -1
  54. package/lib/{cli.js → config/cli.js} +5 -158
  55. package/lib/config/defaults.js +144 -48
  56. package/lib/config/getClaimedAssetTypes.js +21 -13
  57. package/lib/config/normalization.js +18 -7
  58. package/lib/config/target.js +10 -0
  59. package/lib/container/ContainerEntryDependency.js +1 -1
  60. package/lib/container/ContainerEntryModule.js +13 -11
  61. package/lib/container/ContainerEntryModuleFactory.js +2 -2
  62. package/lib/container/ContainerExposedDependency.js +1 -1
  63. package/lib/container/ContainerPlugin.js +178 -5
  64. package/lib/container/ContainerReferencePlugin.js +75 -14
  65. package/lib/container/FallbackDependency.js +1 -1
  66. package/lib/container/FallbackItemDependency.js +1 -1
  67. package/lib/container/FallbackModule.js +12 -10
  68. package/lib/container/FallbackModuleFactory.js +2 -2
  69. package/lib/container/HoistContainerReferencesPlugin.js +10 -11
  70. package/lib/container/ModuleFederationPlugin.js +306 -7
  71. package/lib/container/RemoteModule.js +14 -10
  72. package/lib/container/RemoteRuntimeModule.js +5 -5
  73. package/lib/container/RemoteToExternalDependency.js +1 -1
  74. package/lib/container/moduleFederationHooks.js +1 -1
  75. package/lib/context/ContextModule.js +36 -25
  76. package/lib/context/ContextModuleFactory.js +13 -10
  77. package/lib/context/ContextReplacementPlugin.js +3 -3
  78. package/lib/css/CssGenerator.js +38 -31
  79. package/lib/css/CssInjectStyleRuntimeModule.js +36 -30
  80. package/lib/css/CssLoadingRuntimeModule.js +77 -44
  81. package/lib/css/CssModule.js +27 -29
  82. package/lib/css/CssModulesPlugin.js +128 -44
  83. package/lib/css/CssParser.js +682 -291
  84. package/lib/css/CssServerStylesRuntimeModule.js +3 -3
  85. package/lib/css/cssMinify.js +110 -37
  86. package/lib/css/data.js +6985 -5125
  87. package/lib/css/syntax-parser.js +19873 -0
  88. package/lib/css/syntax-printer.js +6037 -0
  89. package/lib/css/syntax.js +37 -18686
  90. package/lib/debug/ProfilingPlugin.js +52 -19
  91. package/lib/{DefinePlugin.js → define/DefinePlugin.js} +407 -41
  92. package/lib/{DotenvPlugin.js → define/DotenvPlugin.js} +9 -9
  93. package/lib/{EnvironmentPlugin.js → define/EnvironmentPlugin.js} +2 -2
  94. package/lib/deno/DenoTargetPlugin.js +1 -1
  95. package/lib/dependencies/ConstDependency.js +3 -120
  96. package/lib/dependencies/ContextElementDependency.js +5 -172
  97. package/lib/dependencies/NullDependency.js +3 -37
  98. package/lib/dependencies/{AMDDefineDependency.js → amd/AMDDefineDependency.js} +12 -11
  99. package/lib/dependencies/{AMDDefineDependencyParserPlugin.js → amd/AMDDefineDependencyParserPlugin.js} +10 -10
  100. package/lib/dependencies/{AMDPlugin.js → amd/AMDPlugin.js} +11 -11
  101. package/lib/dependencies/{AMDRequireArrayDependency.js → amd/AMDRequireArrayDependency.js} +15 -13
  102. package/lib/dependencies/{AMDRequireContextDependency.js → amd/AMDRequireContextDependency.js} +11 -10
  103. package/lib/dependencies/{AMDRequireDependenciesBlock.js → amd/AMDRequireDependenciesBlock.js} +7 -6
  104. package/lib/dependencies/{AMDRequireDependenciesBlockParserPlugin.js → amd/AMDRequireDependenciesBlockParserPlugin.js} +10 -10
  105. package/lib/dependencies/{AMDRequireDependency.js → amd/AMDRequireDependency.js} +13 -12
  106. package/lib/dependencies/{AMDRequireItemDependency.js → amd/AMDRequireItemDependency.js} +8 -7
  107. package/lib/dependencies/{AMDRuntimeModules.js → amd/AMDRuntimeModules.js} +3 -3
  108. package/lib/dependencies/{LocalModule.js → amd/LocalModule.js} +8 -4
  109. package/lib/dependencies/{LocalModuleDependency.js → amd/LocalModuleDependency.js} +17 -10
  110. package/lib/dependencies/{LocalModulesHelpers.js → amd/LocalModulesHelpers.js} +1 -1
  111. package/lib/dependencies/{RequireJsStuffPlugin.js → amd/RequireJsStuffPlugin.js} +9 -9
  112. package/lib/dependencies/{UnsupportedDependency.js → amd/UnsupportedDependency.js} +11 -10
  113. package/lib/dependencies/{CommonJsDependencyHelpers.js → commonjs/CommonJsDependencyHelpers.js} +8 -9
  114. package/lib/dependencies/{CommonJsExportRequireDependency.js → commonjs/CommonJsExportRequireDependency.js} +166 -33
  115. package/lib/dependencies/{CommonJsExportsDependency.js → commonjs/CommonJsExportsDependency.js} +15 -14
  116. package/lib/dependencies/{CommonJsExportsParserPlugin.js → commonjs/CommonJsExportsParserPlugin.js} +138 -61
  117. package/lib/dependencies/{CommonJsFullRequireDependency.js → commonjs/CommonJsFullRequireDependency.js} +32 -24
  118. package/lib/dependencies/{CommonJsImportsParserPlugin.js → commonjs/CommonJsImportsParserPlugin.js} +35 -30
  119. package/lib/dependencies/{CommonJsObjectExportDependency.js → commonjs/CommonJsObjectExportDependency.js} +13 -12
  120. package/lib/dependencies/{CommonJsPlugin.js → commonjs/CommonJsPlugin.js} +47 -35
  121. package/lib/dependencies/{CommonJsRequireContextDependency.js → commonjs/CommonJsRequireContextDependency.js} +15 -14
  122. package/lib/dependencies/{CommonJsRequireDependency.js → commonjs/CommonJsRequireDependency.js} +33 -25
  123. package/lib/dependencies/{CommonJsSelfReferenceDependency.js → commonjs/CommonJsSelfReferenceDependency.js} +17 -16
  124. package/lib/dependencies/{ModuleDecoratorDependency.js → commonjs/ModuleDecoratorDependency.js} +16 -15
  125. package/lib/dependencies/{RequireEnsureDependenciesBlock.js → commonjs/RequireEnsureDependenciesBlock.js} +8 -7
  126. package/lib/dependencies/{RequireEnsureDependenciesBlockParserPlugin.js → commonjs/RequireEnsureDependenciesBlockParserPlugin.js} +5 -5
  127. package/lib/dependencies/{RequireEnsureDependency.js → commonjs/RequireEnsureDependency.js} +13 -12
  128. package/lib/dependencies/{RequireEnsureItemDependency.js → commonjs/RequireEnsureItemDependency.js} +7 -6
  129. package/lib/dependencies/{RequireEnsurePlugin.js → commonjs/RequireEnsurePlugin.js} +8 -8
  130. package/lib/dependencies/{RequireHeaderDependency.js → commonjs/RequireHeaderDependency.js} +14 -13
  131. package/lib/dependencies/{RequireIncludeDependency.js → commonjs/RequireIncludeDependency.js} +13 -12
  132. package/lib/dependencies/{RequireIncludeDependencyParserPlugin.js → commonjs/RequireIncludeDependencyParserPlugin.js} +3 -27
  133. package/lib/dependencies/{RequireIncludePlugin.js → commonjs/RequireIncludePlugin.js} +4 -4
  134. package/lib/dependencies/{RequireResolveContextDependency.js → commonjs/RequireResolveContextDependency.js} +11 -10
  135. package/lib/dependencies/{RequireResolveDependency.js → commonjs/RequireResolveDependency.js} +12 -11
  136. package/lib/dependencies/{RequireResolveHeaderDependency.js → commonjs/RequireResolveHeaderDependency.js} +13 -12
  137. package/lib/dependencies/commonjs/TopLevelThisParserPlugin.js +59 -0
  138. package/lib/dependencies/{ContextDependency.js → context/ContextDependency.js} +15 -14
  139. package/lib/dependencies/{ContextDependencyHelpers.js → context/ContextDependencyHelpers.js} +31 -9
  140. package/lib/dependencies/{ContextDependencyTemplateAsId.js → context/ContextDependencyTemplateAsId.js} +3 -3
  141. package/lib/dependencies/{ContextDependencyTemplateAsRequireCall.js → context/ContextDependencyTemplateAsRequireCall.js} +3 -3
  142. package/lib/dependencies/context/ContextElementDependency.js +198 -0
  143. package/lib/dependencies/{ImportMetaContextDependency.js → context/ImportMetaContextDependency.js} +7 -6
  144. package/lib/dependencies/{ImportMetaContextDependencyParserPlugin.js → context/ImportMetaContextDependencyParserPlugin.js} +9 -9
  145. package/lib/dependencies/{ImportMetaContextPlugin.js → context/ImportMetaContextPlugin.js} +5 -5
  146. package/lib/dependencies/{ImportMetaGlobDependency.js → context/ImportMetaGlobDependency.js} +7 -6
  147. package/lib/dependencies/{ImportMetaGlobDependencyParserPlugin.js → context/ImportMetaGlobDependencyParserPlugin.js} +4 -4
  148. package/lib/dependencies/{ImportMetaGlobHelpers.js → context/ImportMetaGlobHelpers.js} +9 -9
  149. package/lib/dependencies/{RequireContextDependency.js → context/RequireContextDependency.js} +7 -6
  150. package/lib/dependencies/{RequireContextDependencyParserPlugin.js → context/RequireContextDependencyParserPlugin.js} +2 -2
  151. package/lib/dependencies/{RequireContextPlugin.js → context/RequireContextPlugin.js} +5 -5
  152. package/lib/dependencies/{CachedConstDependency.js → core/CachedConstDependency.js} +12 -11
  153. package/lib/dependencies/core/ConstDependency.js +131 -0
  154. package/lib/dependencies/{ImportPhase.js → core/ImportPhase.js} +5 -4
  155. package/lib/dependencies/{ModuleDependency.js → core/ModuleDependency.js} +10 -7
  156. package/lib/dependencies/{ModuleDependencyTemplateAsId.js → core/ModuleDependencyTemplateAsId.js} +3 -3
  157. package/lib/dependencies/{ModuleDependencyTemplateAsRequireId.js → core/ModuleDependencyTemplateAsRequireId.js} +2 -2
  158. package/lib/dependencies/{ModuleInitFragmentDependency.js → core/ModuleInitFragmentDependency.js} +10 -9
  159. package/lib/dependencies/core/NullDependency.js +44 -0
  160. package/lib/dependencies/{RuntimeRequirementsDependency.js → core/RuntimeRequirementsDependency.js} +10 -9
  161. package/lib/dependencies/{StaticExportsDependency.js → core/StaticExportsDependency.js} +15 -8
  162. package/lib/dependencies/{CssIcssExportDependency.js → css/CssIcssExportDependency.js} +369 -92
  163. package/lib/dependencies/{CssIcssImportDependency.js → css/CssIcssImportDependency.js} +23 -16
  164. package/lib/dependencies/{CssIcssSymbolDependency.js → css/CssIcssSymbolDependency.js} +13 -12
  165. package/lib/dependencies/{CssImportDependency.js → css/CssImportDependency.js} +15 -11
  166. package/lib/dependencies/{CssUrlDependency.js → css/CssUrlDependency.js} +23 -16
  167. package/lib/dependencies/{CreateRequireParserPlugin.js → esm/CreateRequireParserPlugin.js} +9 -9
  168. package/lib/dependencies/{HarmonyAcceptDependency.js → esm/ESMAcceptDependency.js} +41 -38
  169. package/lib/dependencies/esm/ESMAcceptImportDependency.js +39 -0
  170. package/lib/dependencies/{HarmonyCompatibilityDependency.js → esm/ESMCompatibilityDependency.js} +29 -21
  171. package/lib/dependencies/{HarmonyDetectionParserPlugin.js → esm/ESMDetectionParserPlugin.js} +19 -17
  172. package/lib/dependencies/{HarmonyEvaluatedImportSpecifierDependency.js → esm/ESMEvaluatedImportSpecifierDependency.js} +33 -30
  173. package/lib/dependencies/{HarmonyExportDependencyParserPlugin.js → esm/ESMExportDependencyParserPlugin.js} +60 -89
  174. package/lib/dependencies/{HarmonyExportExpressionDependency.js → esm/ESMExportExpressionDependency.js} +80 -45
  175. package/lib/dependencies/{HarmonyExportHeaderDependency.js → esm/ESMExportHeaderDependency.js} +17 -15
  176. package/lib/dependencies/esm/ESMExportImportedSideEffectDependency.js +37 -0
  177. package/lib/dependencies/{HarmonyExportImportedSpecifierDependency.js → esm/ESMExportImportedSpecifierDependency.js} +133 -118
  178. package/lib/dependencies/{HarmonyExportInitFragment.js → esm/ESMExportInitFragment.js} +48 -30
  179. package/lib/dependencies/{HarmonyExportSpecifierDependency.js → esm/ESMExportSpecifierDependency.js} +60 -36
  180. package/lib/dependencies/{HarmonyExports.js → esm/ESMExports.js} +4 -4
  181. package/lib/dependencies/{HarmonyImportBareSideEffectDependency.js → esm/ESMImportBareSideEffectDependency.js} +21 -13
  182. package/lib/dependencies/{HarmonyImportDependency.js → esm/ESMImportDependency.js} +74 -71
  183. package/lib/dependencies/{HarmonyImportDependencyParserPlugin.js → esm/ESMImportDependencyParserPlugin.js} +99 -84
  184. package/lib/dependencies/{HarmonyImportGuard.js → esm/ESMImportGuard.js} +26 -29
  185. package/lib/dependencies/{HarmonyImportSideEffectDependency.js → esm/ESMImportSideEffectDependency.js} +83 -39
  186. package/lib/dependencies/{HarmonyImportSpecifierDependency.js → esm/ESMImportSpecifierDependency.js} +94 -59
  187. package/lib/dependencies/esm/ESMModulesPlugin.js +207 -0
  188. package/lib/dependencies/{HarmonyTopLevelThisParserPlugin.js → esm/ESMTopLevelThisParserPlugin.js} +7 -7
  189. package/lib/dependencies/{TopLevelAwaitDependency.js → esm/TopLevelAwaitDependency.js} +12 -11
  190. package/lib/dependencies/{DynamicExports.js → helpers/DynamicExports.js} +2 -2
  191. package/lib/{util → dependencies/helpers}/chainedImports.js +5 -5
  192. package/lib/dependencies/{processExportInfo.js → helpers/processExportInfo.js} +4 -4
  193. package/lib/{util → dependencies/helpers}/traverseDestructuringAssignmentProperties.js +1 -1
  194. package/lib/dependencies/{ImportMetaHotAcceptDependency.js → hmr/ImportMetaHotAcceptDependency.js} +8 -7
  195. package/lib/dependencies/{ImportMetaHotDeclineDependency.js → hmr/ImportMetaHotDeclineDependency.js} +8 -7
  196. package/lib/dependencies/{ModuleHotAcceptDependency.js → hmr/ModuleHotAcceptDependency.js} +8 -7
  197. package/lib/dependencies/{ModuleHotDeclineDependency.js → hmr/ModuleHotDeclineDependency.js} +8 -7
  198. package/lib/dependencies/{HtmlEntryDependency.js → html/HtmlEntryDependency.js} +51 -141
  199. package/lib/dependencies/{HtmlInlineHtmlDependency.js → html/HtmlInlineHtmlDependency.js} +13 -12
  200. package/lib/dependencies/{HtmlInlineScriptDependency.js → html/HtmlInlineScriptDependency.js} +69 -19
  201. package/lib/dependencies/{HtmlInlineStyleDependency.js → html/HtmlInlineStyleDependency.js} +50 -15
  202. package/lib/dependencies/{HtmlSourceDependency.js → html/HtmlSourceDependency.js} +23 -16
  203. package/lib/dependencies/{ImportContextDependency.js → import/ImportContextDependency.js} +24 -10
  204. package/lib/dependencies/{ImportDependency.js → import/ImportDependency.js} +26 -18
  205. package/lib/dependencies/{ImportEagerDependency.js → import/ImportEagerDependency.js} +18 -10
  206. package/lib/dependencies/{ImportParserPlugin.js → import/ImportParserPlugin.js} +20 -20
  207. package/lib/dependencies/{ImportPlugin.js → import/ImportPlugin.js} +4 -4
  208. package/lib/dependencies/{ImportWeakDependency.js → import/ImportWeakDependency.js} +18 -10
  209. package/lib/dependencies/{importOptionsCheck.js → import/importOptionsCheck.js} +2 -2
  210. package/lib/dependencies/{BuildTimeConstDependency.js → import-meta/BuildTimeConstDependency.js} +12 -11
  211. package/lib/dependencies/{ImportMetaMainDependency.js → import-meta/ImportMetaMainDependency.js} +12 -11
  212. package/lib/dependencies/{ImportMetaPlugin.js → import-meta/ImportMetaPlugin.js} +119 -98
  213. package/lib/dependencies/{SystemPlugin.js → system/SystemPlugin.js} +11 -38
  214. package/lib/dependencies/{SystemRuntimeModule.js → system/SystemRuntimeModule.js} +3 -3
  215. package/lib/dependencies/{ImportMetaResolveDependency.js → url/ImportMetaResolveDependency.js} +9 -8
  216. package/lib/dependencies/{URLContextDependency.js → url/URLContextDependency.js} +11 -10
  217. package/lib/dependencies/{URLDependency.js → url/URLDependency.js} +28 -20
  218. package/lib/{url → dependencies/url}/URLParserPlugin.js +16 -18
  219. package/lib/dependencies/{URLPlugin.js → url/URLPlugin.js} +6 -7
  220. package/lib/dependencies/{WebAssemblyExportImportedDependency.js → wasm/WebAssemblyExportImportedDependency.js} +18 -11
  221. package/lib/dependencies/{WebAssemblyImportDependency.js → wasm/WebAssemblyImportDependency.js} +19 -12
  222. package/lib/dependencies/{CreateScriptUrlDependency.js → worker/CreateScriptUrlDependency.js} +12 -11
  223. package/lib/dependencies/{WorkerAndWorkletPlugin.js → worker/WorkerAndWorkletPlugin.js} +31 -33
  224. package/lib/dependencies/{WorkerDependency.js → worker/WorkerDependency.js} +22 -15
  225. package/lib/dependencies/{WorkletDependency.js → worker/WorkletDependency.js} +19 -18
  226. package/lib/{EvalDevToolModulePlugin.js → devtool/EvalDevToolModulePlugin.js} +20 -6
  227. package/lib/{EvalSourceMapDevToolPlugin.js → devtool/EvalSourceMapDevToolPlugin.js} +32 -24
  228. package/lib/devtool/ModuleFilenameHelpers.js +413 -0
  229. package/lib/{SourceMapDevToolModuleOptionsPlugin.js → devtool/SourceMapDevToolModuleOptionsPlugin.js} +10 -3
  230. package/lib/{SourceMapDevToolPlugin.js → devtool/SourceMapDevToolPlugin.js} +154 -26
  231. package/lib/{util → devtool}/generateDebugId.js +1 -1
  232. package/lib/{IgnoreWarningsPlugin.js → diagnostics/IgnoreWarningsPlugin.js} +2 -2
  233. package/lib/{NoEmitOnErrorsPlugin.js → diagnostics/NoEmitOnErrorsPlugin.js} +1 -1
  234. package/lib/diagnostics/WarnCaseSensitiveModulesPlugin.js +64 -0
  235. package/lib/{WarnDeprecatedOptionPlugin.js → diagnostics/WarnDeprecatedOptionPlugin.js} +2 -22
  236. package/lib/diagnostics/WarnNoModeSetPlugin.js +27 -0
  237. package/lib/dll/DelegatedModule.js +20 -18
  238. package/lib/dll/DelegatedModuleFactoryPlugin.js +2 -2
  239. package/lib/dll/DelegatedPlugin.js +1 -1
  240. package/lib/{dependencies → dll}/DelegatedSourceDependency.js +5 -4
  241. package/lib/{dependencies → dll}/DllEntryDependency.js +6 -5
  242. package/lib/dll/DllEntryPlugin.js +3 -3
  243. package/lib/dll/DllModule.js +11 -9
  244. package/lib/dll/DllModuleFactory.js +3 -3
  245. package/lib/dll/DllPlugin.js +18 -6
  246. package/lib/dll/DllReferencePlugin.js +102 -26
  247. package/lib/dll/LibManifestPlugin.js +9 -7
  248. package/lib/electron/ElectronTargetPlugin.js +2 -2
  249. package/lib/{DynamicEntryPlugin.js → entry/DynamicEntryPlugin.js} +3 -3
  250. package/lib/{dependencies → entry}/EntryDependency.js +11 -2
  251. package/lib/{EntryOptionPlugin.js → entry/EntryOptionPlugin.js} +6 -6
  252. package/lib/entry/EntryPlugin.js +75 -0
  253. package/lib/{performance → errors}/AssetsOverSizeLimitWarning.js +2 -2
  254. package/lib/errors/AsyncDependencyToInitialChunkError.js +2 -2
  255. package/lib/errors/BuildCycleError.js +1 -1
  256. package/lib/{WarnCaseSensitiveModulesPlugin.js → errors/CaseSensitiveModulesWarning.js} +4 -56
  257. package/lib/errors/ChunkRenderError.js +1 -1
  258. package/lib/errors/CodeGenerationError.js +1 -1
  259. package/lib/errors/CommentCompilationWarning.js +1 -1
  260. package/lib/errors/ConflictingEntryExportsWarning.js +38 -0
  261. package/lib/{dependencies → errors}/CriticalDependencyWarning.js +4 -3
  262. package/lib/errors/DeprecatedOptionWarning.js +30 -0
  263. package/lib/errors/DllManifestError.js +26 -0
  264. package/lib/{performance → errors}/DuplicatePackagesWarning.js +6 -6
  265. package/lib/{dependencies/HarmonyLinkingError.js → errors/ESMLinkingError.js} +4 -4
  266. package/lib/{performance → errors}/EntrypointsOverSizeLimitWarning.js +2 -2
  267. package/lib/errors/EnvironmentNotSupportAsyncWarning.js +2 -2
  268. package/lib/{ErrorHelpers.js → errors/ErrorHelpers.js} +7 -5
  269. package/lib/errors/ExternalStarReexportError.js +2 -2
  270. package/lib/{library → errors}/FalseIIFEUmdWarning.js +1 -1
  271. package/lib/errors/HookWebpackError.js +4 -4
  272. package/lib/errors/IgnoreErrorModuleFactory.js +3 -3
  273. package/lib/errors/InvalidDependenciesModuleWarning.js +1 -1
  274. package/lib/{optimize → errors}/MinMaxSizeWarning.js +1 -1
  275. package/lib/errors/ModuleBuildError.js +1 -1
  276. package/lib/errors/ModuleDependencyError.js +2 -2
  277. package/lib/errors/ModuleDependencyWarning.js +2 -2
  278. package/lib/errors/ModuleError.js +1 -1
  279. package/lib/errors/ModuleHashingError.js +1 -1
  280. package/lib/errors/ModuleNotFoundError.js +3 -3
  281. package/lib/errors/ModuleParseError.js +1 -1
  282. package/lib/errors/ModuleRestoreError.js +1 -1
  283. package/lib/errors/ModuleStoreError.js +1 -1
  284. package/lib/errors/ModuleWarning.js +1 -1
  285. package/lib/{performance → errors}/NoAsyncChunksWarning.js +1 -1
  286. package/lib/{WarnNoModeSetPlugin.js → errors/NoModeWarning.js} +2 -19
  287. package/lib/errors/NodeStuffInWebError.js +7 -2
  288. package/lib/errors/PathVariableError.js +31 -0
  289. package/lib/errors/RequireIncludeDeprecationWarning.js +40 -0
  290. package/lib/{performance → errors}/RuntimeInLargeChunkWarning.js +1 -1
  291. package/lib/errors/RuntimeModuleGenerationError.js +51 -0
  292. package/lib/errors/SSRManifestAutoPublicPathWarning.js +24 -0
  293. package/lib/errors/SystemImportDeprecationWarning.js +43 -0
  294. package/lib/errors/UnmergeableEntryExportsError.js +34 -0
  295. package/lib/errors/UnsupportedFeatureWarning.js +1 -1
  296. package/lib/{wasm-sync → errors}/UnsupportedWebAssemblyFeatureError.js +1 -1
  297. package/lib/{wasm-sync → errors}/WebAssemblyInInitialChunkError.js +7 -5
  298. package/lib/errors/WebpackError.js +12 -3
  299. package/lib/esm/ExportWebpackRequireRuntimeModule.js +2 -2
  300. package/lib/esm/ModuleChunkFormatPlugin.js +19 -19
  301. package/lib/esm/ModuleChunkLoadingPlugin.js +3 -3
  302. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +8 -8
  303. package/lib/{ExternalModule.js → externals/ExternalModule.js} +79 -55
  304. package/lib/{ExternalModuleFactoryPlugin.js → externals/ExternalModuleFactoryPlugin.js} +41 -39
  305. package/lib/externals/ExternalsPlugin.js +99 -0
  306. package/lib/fs/FileSystemInfo.js +4642 -0
  307. package/lib/{util → fs}/fs.js +22 -9
  308. package/lib/{AsyncDependenciesBlock.js → graph/AsyncDependenciesBlock.js} +27 -4
  309. package/lib/graph/Chunk.js +985 -0
  310. package/lib/{ChunkGraph.js → graph/ChunkGraph.js} +187 -80
  311. package/lib/{ChunkGroup.js → graph/ChunkGroup.js} +11 -3
  312. package/lib/{DependenciesBlock.js → graph/DependenciesBlock.js} +16 -4
  313. package/lib/graph/Dependency.js +628 -0
  314. package/lib/graph/Entrypoint.js +136 -0
  315. package/lib/{ExportsInfo.js → graph/ExportsInfo.js} +130 -82
  316. package/lib/{HotUpdateChunk.js → graph/HotUpdateChunk.js} +8 -0
  317. package/lib/{ModuleGraph.js → graph/ModuleGraph.js} +30 -30
  318. package/lib/{ModuleGraphConnection.js → graph/ModuleGraphConnection.js} +2 -2
  319. package/lib/{buildChunkGraph.js → graph/buildChunkGraph.js} +152 -57
  320. package/lib/{util → graph}/findGraphRoots.js +14 -8
  321. package/lib/graph/isDependencyKind.js +23 -0
  322. package/lib/hmr/HotModuleReplacement.runtime.js +2 -2
  323. package/lib/{HotModuleReplacementPlugin.js → hmr/HotModuleReplacementPlugin.js} +47 -47
  324. package/lib/hmr/HotModuleReplacementRuntimeModule.js +3 -3
  325. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +10 -8
  326. package/lib/hmr/JavascriptHotModuleReplacementHelper.js +2 -2
  327. package/lib/hmr/LazyCompilationPlugin.js +31 -21
  328. package/lib/html/HtmlGenerator.js +107 -43
  329. package/lib/html/HtmlModule.js +6 -2
  330. package/lib/html/HtmlModulesPlugin.js +172 -76
  331. package/lib/html/HtmlParser.js +503 -153
  332. package/lib/html/builtinEmbeddedRenderer.js +60 -13
  333. package/lib/html/data.js +2 -1
  334. package/lib/html/htmlMinify.js +111 -41
  335. package/lib/html/syntax-parser.js +15796 -0
  336. package/lib/html/syntax-printer.js +1034 -0
  337. package/lib/html/syntax.js +37 -13952
  338. package/lib/html/xmlMinify.js +67 -0
  339. package/lib/ids/ChunkModuleIdRangePlugin.js +2 -2
  340. package/lib/ids/DeterministicModuleIdsPlugin.js +1 -1
  341. package/lib/ids/HashedModuleIdsPlugin.js +31 -4
  342. package/lib/ids/IdHelpers.js +4 -4
  343. package/lib/ids/NaturalChunkIdsPlugin.js +1 -1
  344. package/lib/ids/OccurrenceChunkIdsPlugin.js +6 -5
  345. package/lib/ids/OccurrenceModuleIdsPlugin.js +6 -5
  346. package/lib/{RecordIdsPlugin.js → ids/RecordIdsPlugin.js} +5 -5
  347. package/lib/ids/SyncModuleIdsPlugin.js +3 -3
  348. package/lib/{util → ids}/numberHash.js +1 -1
  349. package/lib/index.js +303 -97
  350. package/lib/{APIPlugin.js → javascript/APIPlugin.js} +25 -25
  351. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +4 -5
  352. package/lib/javascript/BasicEvaluatedExpression.js +4 -4
  353. package/lib/javascript/ChunkHelpers.js +64 -4
  354. package/lib/javascript/CommonJsChunkFormatPlugin.js +4 -7
  355. package/lib/{CompatibilityPlugin.js → javascript/CompatibilityPlugin.js} +7 -7
  356. package/lib/{ConstPlugin.js → javascript/ConstPlugin.js} +74 -7
  357. package/lib/{ExportsInfoApiPlugin.js → javascript/ExportsInfoApiPlugin.js} +5 -5
  358. package/lib/{dependencies → javascript}/ExportsInfoDependency.js +10 -9
  359. package/lib/javascript/JavascriptGenerator.js +17 -17
  360. package/lib/{JavascriptMetaInfoPlugin.js → javascript/JavascriptMetaInfoPlugin.js} +7 -7
  361. package/lib/javascript/JavascriptModule.js +4 -3
  362. package/lib/javascript/JavascriptModulesPlugin.js +440 -211
  363. package/lib/javascript/JavascriptParser.js +220 -134
  364. package/lib/javascript/JavascriptParserHelpers.js +1 -1
  365. package/lib/javascript/MergedEntryExports.js +196 -0
  366. package/lib/javascript/ScopeAnalyzer.js +3840 -5
  367. package/lib/javascript/StartupHelpers.js +6 -6
  368. package/lib/{UseStrictPlugin.js → javascript/UseStrictPlugin.js} +12 -15
  369. package/lib/{dependencies → javascript}/WebpackIsIncludedDependency.js +10 -9
  370. package/lib/{WebpackIsIncludedPlugin.js → javascript/WebpackIsIncludedPlugin.js} +8 -8
  371. package/lib/javascript/data.js +533 -122
  372. package/lib/javascript/jsMinify.js +272 -0
  373. package/lib/javascript/regexp.js +67 -32
  374. package/lib/javascript/syntax-parser.js +18561 -0
  375. package/lib/javascript/syntax-printer-data.js +933 -0
  376. package/lib/javascript/syntax-printer.js +47106 -0
  377. package/lib/javascript/syntax.js +20 -11274
  378. package/lib/json/JsonData.js +1 -1
  379. package/lib/{dependencies → json}/JsonExportsDependency.js +8 -7
  380. package/lib/json/JsonGenerator.js +10 -10
  381. package/lib/json/JsonModule.js +2 -2
  382. package/lib/json/JsonModulesPlugin.js +1 -1
  383. package/lib/json/JsonParser.js +5 -5
  384. package/lib/json/jsonMinify.js +69 -0
  385. package/lib/library/AbstractLibraryPlugin.js +28 -15
  386. package/lib/library/AmdLibraryPlugin.js +4 -4
  387. package/lib/library/AssignLibraryPlugin.js +27 -11
  388. package/lib/library/EnableLibraryPlugin.js +1 -1
  389. package/lib/library/ExportPropertyLibraryPlugin.js +4 -4
  390. package/lib/library/JsonpLibraryPlugin.js +1 -1
  391. package/lib/library/LibraryTemplatePlugin.js +53 -0
  392. package/lib/library/ModuleLibraryPlugin.js +160 -166
  393. package/lib/library/SystemLibraryPlugin.js +6 -8
  394. package/lib/library/UmdLibraryPlugin.js +3 -4
  395. package/lib/{dependencies → loaders}/LoaderDependency.js +3 -3
  396. package/lib/{dependencies → loaders}/LoaderImportDependency.js +9 -3
  397. package/lib/{LoaderOptionsPlugin.js → loaders/LoaderOptionsPlugin.js} +30 -12
  398. package/lib/{dependencies → loaders}/LoaderPlugin.js +2 -2
  399. package/lib/loaders/LoaderRunner.js +31 -21
  400. package/lib/{LoaderTargetPlugin.js → loaders/LoaderTargetPlugin.js} +2 -2
  401. package/lib/logging/Logger.js +7 -9
  402. package/lib/logging/ProgressPlugin.js +957 -0
  403. package/lib/{CodeGenerationResults.js → module/CodeGenerationResults.js} +7 -7
  404. package/lib/{Generator.js → module/Generator.js} +16 -14
  405. package/lib/{Module.js → module/Module.js} +119 -51
  406. package/lib/{ModuleFactory.js → module/ModuleFactory.js} +3 -3
  407. package/lib/module/NormalModule.js +2348 -0
  408. package/lib/{NormalModuleFactory.js → module/NormalModuleFactory.js} +53 -54
  409. package/lib/module/NullFactory.js +29 -0
  410. package/lib/{Parser.js → module/Parser.js} +3 -3
  411. package/lib/module/RawModule.js +208 -0
  412. package/lib/{SelfModuleFactory.js → module/SelfModuleFactory.js} +1 -1
  413. package/lib/{util → module}/extractSourceMap.js +2 -2
  414. package/lib/{util → module}/findCaseMismatch.js +2 -2
  415. package/lib/node/CommonJsChunkLoadingPlugin.js +3 -3
  416. package/lib/{dependencies → node}/ExternalModuleDependency.js +8 -7
  417. package/lib/{dependencies → node}/ExternalModuleInitFragment.js +6 -5
  418. package/lib/{dependencies → node}/ExternalModuleInitFragmentDependency.js +14 -9
  419. package/lib/node/NodeEnvironmentPlugin.js +11 -1
  420. package/lib/{NodeStuffPlugin.js → node/NodeStuffPlugin.js} +17 -17
  421. package/lib/node/NodeTargetPlugin.js +1 -1
  422. package/lib/node/NodeWatchFileSystem.js +58 -6
  423. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +7 -7
  424. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +9 -7
  425. package/lib/node/ReadFileCompileWasmPlugin.js +7 -5
  426. package/lib/node/RequireChunkLoadingRuntimeModule.js +7 -7
  427. package/lib/node/nodeConsole.js +2 -4
  428. package/lib/optimize/AggressiveMergingPlugin.js +2 -2
  429. package/lib/optimize/AggressiveSplittingPlugin.js +12 -8
  430. package/lib/{CircularModulesPlugin.js → optimize/CircularModulesPlugin.js} +13 -13
  431. package/lib/optimize/ConcatenatedModule.js +229 -214
  432. package/lib/{ConcatenationScope.js → optimize/ConcatenationScope.js} +39 -6
  433. package/lib/optimize/ConstExportsPlugin.js +7 -7
  434. package/lib/optimize/EnsureChunkConditionsPlugin.js +3 -3
  435. package/lib/{FlagAllModulesAsUsedPlugin.js → optimize/FlagAllModulesAsUsedPlugin.js} +3 -3
  436. package/lib/{FlagDependencyExportsPlugin.js → optimize/FlagDependencyExportsPlugin.js} +17 -17
  437. package/lib/{FlagDependencyUsagePlugin.js → optimize/FlagDependencyUsagePlugin.js} +17 -17
  438. package/lib/{FlagEntryExportAsUsedPlugin.js → optimize/FlagEntryExportAsUsedPlugin.js} +2 -2
  439. package/lib/optimize/FlagIncludedChunksPlugin.js +2 -2
  440. package/lib/optimize/InlineExports.js +11 -3
  441. package/lib/optimize/InnerGraph.js +5 -13
  442. package/lib/optimize/InnerGraphPlugin.js +10 -10
  443. package/lib/optimize/LazyBarrels.js +584 -0
  444. package/lib/{util → optimize}/LazyBucketSortedSet.js +2 -2
  445. package/lib/optimize/LimitChunkCountPlugin.js +16 -7
  446. package/lib/optimize/MangleExportsPlugin.js +5 -5
  447. package/lib/optimize/MergeDuplicateChunksPlugin.js +7 -6
  448. package/lib/optimize/MinChunkSizePlugin.js +9 -6
  449. package/lib/optimize/ModuleConcatenationPlugin.js +20 -12
  450. package/lib/{dependencies → optimize}/PureExpressionDependency.js +11 -10
  451. package/lib/optimize/RealContentHashPlugin.js +16 -7
  452. package/lib/optimize/RemoveEmptyChunksPlugin.js +2 -2
  453. package/lib/optimize/RemoveParentModulesPlugin.js +4 -4
  454. package/lib/optimize/SideEffectsFlagPlugin.js +18 -18
  455. package/lib/optimize/SplitChunksPlugin.js +713 -155
  456. package/lib/{util → optimize}/TupleQueue.js +9 -9
  457. package/lib/optimize/chunkSetIntersections.js +437 -0
  458. package/lib/{util → optimize}/deterministicGrouping.js +17 -17
  459. package/lib/{BannerPlugin.js → output/BannerPlugin.js} +82 -14
  460. package/lib/{CleanPlugin.js → output/CleanPlugin.js} +66 -24
  461. package/lib/{CopyPlugin.js → output/CopyPlugin.js} +142 -67
  462. package/lib/{ManifestPlugin.js → output/ManifestPlugin.js} +91 -17
  463. package/lib/output/SSRManifestPlugin.js +349 -0
  464. package/lib/performance/AnalyzableBailoutsPlugin.js +1 -1
  465. package/lib/performance/AsyncChunkWaterfallsPlugin.js +1 -1
  466. package/lib/performance/BroadContextsPlugin.js +4 -4
  467. package/lib/performance/CacheEffectivenessPlugin.js +2 -3
  468. package/lib/performance/ConflictingResourceHintsPlugin.js +1 -1
  469. package/lib/performance/DuplicateModulesPlugin.js +3 -4
  470. package/lib/performance/DuplicatePackagesPlugin.js +3 -3
  471. package/lib/performance/DynamicExportsPlugin.js +2 -2
  472. package/lib/performance/EvalUsagePlugin.js +3 -3
  473. package/lib/performance/HotspotsPlugin.js +11 -10
  474. package/lib/performance/LargeModulesPlugin.js +2 -3
  475. package/lib/performance/LegacyJavascriptPlugin.js +1 -2
  476. package/lib/performance/MissingSideEffectsPlugin.js +2 -3
  477. package/lib/performance/MissingSourceMapsPlugin.js +5 -6
  478. package/lib/performance/PureAnnotationsPlugin.js +3 -3
  479. package/lib/performance/RedundantDynamicImportsPlugin.js +6 -8
  480. package/lib/performance/ScopeHoistingBailoutsPlugin.js +2 -2
  481. package/lib/performance/SizeLimitsPlugin.js +11 -12
  482. package/lib/performance/TopLevelThisPlugin.js +8 -7
  483. package/lib/performance/UnsplitVendorsPlugin.js +1 -2
  484. package/lib/performance/UnusedAliasesPlugin.js +6 -7
  485. package/lib/performance/UnusedAssetsPlugin.js +5 -5
  486. package/lib/performance/UnusedDefinesPlugin.js +2 -2
  487. package/lib/performance/UnusedExternalsPlugin.js +3 -4
  488. package/lib/performance/UnusedFederationPlugin.js +2 -4
  489. package/lib/performance/UnusedModulesPlugin.js +5 -4
  490. package/lib/performance/getModuleSize.js +1 -1
  491. package/lib/performance/hasOnlyUnusedExports.js +4 -4
  492. package/lib/performance/isOnlyReexported.js +7 -6
  493. package/lib/{AutomaticPrefetchPlugin.js → prefetch/AutomaticPrefetchPlugin.js} +4 -5
  494. package/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +2 -2
  495. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +1 -1
  496. package/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +4 -4
  497. package/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +4 -4
  498. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +4 -4
  499. package/lib/{dependencies → prefetch}/PrefetchDependency.js +1 -1
  500. package/lib/{PrefetchPlugin.js → prefetch/PrefetchPlugin.js} +2 -2
  501. package/lib/prefetch/ResourceHintPlugin.js +65 -44
  502. package/lib/prefetch/ResourceHintRuntimeModule.js +3 -3
  503. package/lib/prefetch/StartupAssetHintRuntimeModule.js +3 -3
  504. package/lib/prefetch/parseResourceHintOptions.js +4 -3
  505. package/lib/{ProvidePlugin.js → provide/ProvidePlugin.js} +7 -7
  506. package/lib/{dependencies → provide}/ProvidedDependency.js +14 -13
  507. package/lib/{IgnorePlugin.js → resolve/IgnorePlugin.js} +30 -13
  508. package/lib/{NormalModuleReplacementPlugin.js → resolve/NormalModuleReplacementPlugin.js} +4 -4
  509. package/lib/{ResolverFactory.js → resolve/ResolverFactory.js} +18 -5
  510. package/lib/resolve/getResolveOptionsKey.js +59 -0
  511. package/lib/rules/RuleSetCompiler.js +27 -46
  512. package/lib/runtime/AsyncModuleGeneratorRuntimeModule.js +2 -2
  513. package/lib/runtime/AsyncModuleRuntimeModule.js +7 -4
  514. package/lib/runtime/AutoPublicPathRuntimeModule.js +5 -5
  515. package/lib/runtime/BaseUriRuntimeModule.js +3 -3
  516. package/lib/runtime/ChunkNameRuntimeModule.js +2 -2
  517. package/lib/runtime/CompatGetDefaultExportRuntimeModule.js +2 -2
  518. package/lib/runtime/CompatRuntimeModule.js +4 -4
  519. package/lib/runtime/ConcatenationWrapRuntimeModule.js +2 -2
  520. package/lib/runtime/ConstructRequireRuntimeModule.js +2 -2
  521. package/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +2 -2
  522. package/lib/runtime/CreateScriptRuntimeModule.js +2 -2
  523. package/lib/runtime/CreateScriptUrlRuntimeModule.js +2 -2
  524. package/lib/runtime/DefinePropertyGettersRuntimeModule.js +6 -6
  525. package/lib/runtime/EnsureChunkRuntimeModule.js +4 -4
  526. package/lib/runtime/GetChunkFilenameRuntimeModule.js +6 -6
  527. package/lib/runtime/GetFullHashRuntimeModule.js +2 -2
  528. package/lib/runtime/GetMainFilenameRuntimeModule.js +4 -4
  529. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +3 -3
  530. package/lib/runtime/GetWorkletBootstrapRuntimeModule.js +3 -3
  531. package/lib/runtime/GlobalRuntimeModule.js +3 -3
  532. package/lib/runtime/HasOwnPropertyRuntimeModule.js +3 -3
  533. package/lib/runtime/HelperRuntimeModule.js +16 -1
  534. package/lib/runtime/LoadScriptRuntimeModule.js +3 -3
  535. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +80 -17
  536. package/lib/runtime/MakeNamespaceObjectRuntimeModule.js +2 -2
  537. package/lib/runtime/NonceRuntimeModule.js +2 -2
  538. package/lib/runtime/OnChunksLoadedRuntimeModule.js +4 -4
  539. package/lib/runtime/PublicPathRuntimeModule.js +2 -2
  540. package/lib/runtime/RelativeUrlRuntimeModule.js +2 -2
  541. package/lib/{RuntimeGlobals.js → runtime/RuntimeGlobals.js} +18 -1
  542. package/lib/runtime/RuntimeIdRuntimeModule.js +4 -4
  543. package/lib/{RuntimeModule.js → runtime/RuntimeModule.js} +36 -21
  544. package/lib/{RuntimePlugin.js → runtime/RuntimePlugin.js} +48 -50
  545. package/lib/runtime/SetAnonymousDefaultNameRuntimeModule.js +2 -2
  546. package/lib/runtime/SpecNamespaceObjectRuntimeModule.js +2 -2
  547. package/lib/runtime/StartupChunkDependenciesPlugin.js +2 -2
  548. package/lib/runtime/StartupChunkDependenciesRuntimeModule.js +5 -5
  549. package/lib/runtime/StartupEntrypointRuntimeModule.js +3 -3
  550. package/lib/runtime/SystemContextRuntimeModule.js +2 -2
  551. package/lib/runtime/ToBinaryRuntimeModule.js +3 -3
  552. package/lib/runtime/WorkerRuntimeModule.js +1 -1
  553. package/lib/runtime/baseUri.js +1 -1
  554. package/lib/schemes/DataUriPlugin.js +1 -1
  555. package/lib/schemes/HttpUriPlugin.js +67 -11
  556. package/lib/schemes/VirtualUrlPlugin.js +50 -16
  557. package/lib/serialization/AggregateErrorSerializer.js +2 -2
  558. package/lib/serialization/FileMiddleware.js +3 -3
  559. package/lib/serialization/ObjectMiddleware.js +47 -16
  560. package/lib/serialization/SerializerMiddleware.js +2 -2
  561. package/lib/serialization/SingleItemMiddleware.js +4 -2
  562. package/lib/sharing/ConsumeSharedFallbackDependency.js +9 -1
  563. package/lib/sharing/ConsumeSharedModule.js +18 -14
  564. package/lib/sharing/ConsumeSharedPlugin.js +148 -42
  565. package/lib/sharing/ConsumeSharedRuntimeModule.js +8 -8
  566. package/lib/sharing/ProvideForSharedDependency.js +9 -1
  567. package/lib/sharing/ProvideSharedDependency.js +1 -1
  568. package/lib/sharing/ProvideSharedModule.js +11 -9
  569. package/lib/sharing/ProvideSharedModuleFactory.js +2 -2
  570. package/lib/sharing/ProvideSharedPlugin.js +111 -20
  571. package/lib/sharing/SharePlugin.js +102 -9
  572. package/lib/sharing/ShareRuntimeModule.js +6 -6
  573. package/lib/sharing/resolveMatchedConfigs.js +1 -1
  574. package/lib/{util → sharing}/semver.js +14 -16
  575. package/lib/sharing/utils.js +59 -2
  576. package/lib/stats/DefaultStatsFactoryPlugin.js +22 -19
  577. package/lib/stats/DefaultStatsPresetPlugin.js +1 -1
  578. package/lib/stats/DefaultStatsPrinterPlugin.js +3 -3
  579. package/lib/{MultiStats.js → stats/MultiStats.js} +4 -4
  580. package/lib/{Stats.js → stats/Stats.js} +4 -4
  581. package/lib/stats/StatsFactory.js +14 -13
  582. package/lib/{ChunkTemplate.js → template/ChunkTemplate.js} +7 -7
  583. package/lib/{ConditionalInitFragment.js → template/ConditionalInitFragment.js} +3 -3
  584. package/lib/template/DependencyTemplate.js +77 -0
  585. package/lib/{DependencyTemplates.js → template/DependencyTemplates.js} +9 -4
  586. package/lib/template/InitFragment.js +223 -0
  587. package/lib/{MainTemplate.js → template/MainTemplate.js} +11 -11
  588. package/lib/{ModuleInfoHeaderPlugin.js → template/ModuleInfoHeaderPlugin.js} +30 -8
  589. package/lib/{ModuleTemplate.js → template/ModuleTemplate.js} +6 -6
  590. package/lib/{RuntimeTemplate.js → template/RuntimeTemplate.js} +145 -63
  591. package/lib/{Template.js → template/Template.js} +13 -11
  592. package/lib/{TemplatedPathPlugin.js → template/TemplatedPathPlugin.js} +19 -23
  593. package/lib/typescript/TypeScriptPlugin.js +3 -3
  594. package/lib/util/RequestShortener.js +44 -0
  595. package/lib/util/SortableSet.js +87 -22
  596. package/lib/util/SourceProcessor.js +349 -44
  597. package/lib/util/TupleSet.js +27 -27
  598. package/lib/util/WeakTupleMap.js +10 -12
  599. package/lib/util/buildDiagnostics.js +2 -2
  600. package/lib/util/comparators.js +10 -10
  601. package/lib/util/concatenate.js +28 -147
  602. package/lib/util/createMappings.js +111 -0
  603. package/lib/util/dataURL.js +94 -15
  604. package/lib/util/deprecation.js +1 -1
  605. package/lib/util/extractComments.js +118 -0
  606. package/lib/util/formatLocation.js +1 -1
  607. package/lib/util/globUtils.js +197 -16
  608. package/lib/util/haltVisitors.js +51 -0
  609. package/lib/util/handlerKeys.js +2 -2
  610. package/lib/util/identifier.js +117 -1
  611. package/lib/util/implicitTypeLoaderFallback.js +6 -4
  612. package/lib/util/internalSerializables.js +294 -102
  613. package/lib/util/magicComment.js +12 -7
  614. package/lib/util/makeSerializable.js +23 -4
  615. package/lib/util/parseJson.js +1 -1
  616. package/lib/util/preloadModuleType.js +5 -2
  617. package/lib/util/registerExternalSerializer.js +2 -2
  618. package/lib/util/removeBOM.js +1 -1
  619. package/lib/util/runtime.js +1 -1
  620. package/lib/util/serialization.js +4 -1
  621. package/lib/util/source.js +2 -2
  622. package/lib/util/terminalColors.js +161 -0
  623. package/lib/{wasm-async → wasm}/AsyncWasmCompileRuntimeModule.js +5 -5
  624. package/lib/{wasm-async → wasm}/AsyncWasmLoadingRuntimeModule.js +5 -5
  625. package/lib/{wasm-async → wasm}/AsyncWasmModule.js +9 -5
  626. package/lib/{wasm-async → wasm}/AsyncWebAssemblyGenerator.js +5 -5
  627. package/lib/{wasm-async → wasm}/AsyncWebAssemblyJavascriptGenerator.js +11 -10
  628. package/lib/{wasm-async → wasm}/AsyncWebAssemblyModulesPlugin.js +26 -10
  629. package/lib/{wasm-async → wasm}/AsyncWebAssemblyParser.js +8 -8
  630. package/lib/wasm/EnableWasmLoadingPlugin.js +1 -1
  631. package/lib/{wasm-async → wasm}/UniversalCompileAsyncWasmPlugin.js +9 -7
  632. package/lib/wasm/wasmModuleFilename.js +2 -2
  633. package/lib/wasm-sync/SyncWasmModule.js +3 -3
  634. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +8 -8
  635. package/lib/wasm-sync/WasmFinalizeExportsPlugin.js +3 -3
  636. package/lib/wasm-sync/WebAssemblyGenerator.js +9 -8
  637. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +14 -15
  638. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +9 -7
  639. package/lib/wasm-sync/WebAssemblyParser.js +6 -6
  640. package/lib/wasm-sync/WebAssemblyUtils.js +6 -5
  641. package/lib/{MultiWatching.js → watch/MultiWatching.js} +3 -3
  642. package/lib/{WatchIgnorePlugin.js → watch/WatchIgnorePlugin.js} +43 -9
  643. package/lib/{Watching.js → watch/Watching.js} +8 -8
  644. package/lib/web/FetchCompileAsyncWasmPlugin.js +8 -6
  645. package/lib/web/FetchCompileWasmPlugin.js +6 -4
  646. package/lib/web/JsonpChunkLoadingPlugin.js +3 -3
  647. package/lib/web/JsonpChunkLoadingRuntimeModule.js +6 -6
  648. package/lib/web/JsonpTemplatePlugin.js +1 -1
  649. package/lib/webpack.js +27 -17
  650. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +3 -3
  651. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +6 -6
  652. package/package.json +48 -41
  653. package/schemas/WebpackOptions.check.js +2 -1
  654. package/schemas/WebpackOptions.d.json.ts +2 -0
  655. package/schemas/WebpackOptions.json +294 -74
  656. package/schemas/plugins/BannerPlugin.check.js +2 -1
  657. package/schemas/plugins/BannerPlugin.json +29 -2
  658. package/schemas/plugins/HtmlGeneratorOptions.check.js +1 -0
  659. package/schemas/plugins/HtmlParserOptions.check.js +2 -1
  660. package/schemas/plugins/IgnorePlugin.check.js +1 -0
  661. package/schemas/plugins/IgnorePlugin.d.json.ts +2 -0
  662. package/schemas/plugins/IgnorePlugin.json +1 -1
  663. package/schemas/plugins/LoaderOptionsPlugin.check.js +1 -0
  664. package/schemas/plugins/ManifestPlugin.check.js +1 -0
  665. package/schemas/plugins/ManifestPlugin.json +3 -3
  666. package/schemas/plugins/ProgressPlugin.check.js +2 -1
  667. package/schemas/plugins/ProgressPlugin.json +2 -7
  668. package/schemas/plugins/SSRManifestPlugin.check.js +7 -0
  669. package/schemas/plugins/SSRManifestPlugin.json +20 -0
  670. package/schemas/plugins/SourceMapDevToolPlugin.check.js +2 -1
  671. package/schemas/plugins/SourceMapDevToolPlugin.json +44 -12
  672. package/schemas/plugins/WatchIgnorePlugin.check.js +2 -1
  673. package/schemas/plugins/WatchIgnorePlugin.json +12 -3
  674. package/schemas/plugins/asset/AssetGeneratorOptions.check.js +1 -0
  675. package/schemas/plugins/asset/AssetInlineGeneratorOptions.check.js +1 -0
  676. package/schemas/plugins/asset/AssetParserOptions.check.js +1 -0
  677. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js +1 -0
  678. package/schemas/plugins/container/ContainerPlugin.check.js +2 -1
  679. package/schemas/plugins/container/ContainerPlugin.json +8 -0
  680. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -0
  681. package/schemas/plugins/container/ExternalsType.check.js +1 -0
  682. package/schemas/plugins/container/ModuleFederationPlugin.check.js +2 -1
  683. package/schemas/plugins/container/ModuleFederationPlugin.json +40 -0
  684. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.js +1 -0
  685. package/schemas/plugins/css/CssGeneratorOptions.check.js +1 -0
  686. package/schemas/plugins/css/CssModuleGeneratorOptions.check.js +1 -0
  687. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -0
  688. package/schemas/plugins/css/CssParserOptions.check.js +1 -0
  689. package/schemas/plugins/debug/ProfilingPlugin.check.js +1 -0
  690. package/schemas/plugins/dll/DllPlugin.check.js +1 -0
  691. package/schemas/plugins/dll/DllReferencePlugin.check.js +2 -1
  692. package/schemas/plugins/dll/DllReferencePlugin.json +3 -18
  693. package/schemas/plugins/ids/HashedModuleIdsPlugin.check.js +1 -0
  694. package/schemas/plugins/ids/OccurrenceChunkIdsPlugin.check.js +1 -0
  695. package/schemas/plugins/ids/OccurrenceModuleIdsPlugin.check.js +1 -0
  696. package/schemas/plugins/json/JsonModulesPluginGenerator.check.js +1 -0
  697. package/schemas/plugins/json/JsonModulesPluginParser.check.js +1 -0
  698. package/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js +1 -0
  699. package/schemas/plugins/optimize/LimitChunkCountPlugin.check.js +1 -0
  700. package/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.js +1 -0
  701. package/schemas/plugins/optimize/MinChunkSizePlugin.check.js +1 -0
  702. package/schemas/plugins/schemes/HttpUriPlugin.check.js +1 -0
  703. package/schemas/plugins/schemes/VirtualUrlPlugin.check.js +1 -0
  704. package/schemas/plugins/sharing/ConsumeSharedPlugin.check.js +2 -1
  705. package/schemas/plugins/sharing/ConsumeSharedPlugin.json +32 -0
  706. package/schemas/plugins/sharing/ProvideSharedPlugin.check.js +2 -1
  707. package/schemas/plugins/sharing/ProvideSharedPlugin.json +32 -0
  708. package/schemas/plugins/sharing/SharePlugin.check.js +2 -1
  709. package/schemas/plugins/sharing/SharePlugin.json +32 -0
  710. package/types.d.ts +19355 -13873
  711. package/lib/LazyBarrel.js +0 -388
  712. package/lib/dependencies/HarmonyAcceptImportDependency.js +0 -39
  713. package/lib/dependencies/HarmonyModulesPlugin.js +0 -192
  714. package/lib/javascript/ChunkFormatHelpers.js +0 -72
  715. package/lib/javascript/grammar.js +0 -5546
  716. package/lib/javascript/parser.js +0 -1500
  717. package/lib/javascript/regexpData.js +0 -51
  718. package/lib/performance/getSourceModules.js +0 -22
  719. package/lib/util/Semaphore.js +0 -65
  720. package/lib/util/objectToMap.js +0 -15
  721. package/schemas/WebpackOptions.check.d.ts +0 -7
  722. package/schemas/_container.json +0 -155
  723. package/schemas/_sharing.json +0 -118
  724. package/schemas/plugins/BannerPlugin.check.d.ts +0 -7
  725. package/schemas/plugins/HtmlGeneratorOptions.check.d.ts +0 -7
  726. package/schemas/plugins/HtmlParserOptions.check.d.ts +0 -7
  727. package/schemas/plugins/IgnorePlugin.check.d.ts +0 -7
  728. package/schemas/plugins/LoaderOptionsPlugin.check.d.ts +0 -7
  729. package/schemas/plugins/ManifestPlugin.check.d.ts +0 -7
  730. package/schemas/plugins/ProgressPlugin.check.d.ts +0 -7
  731. package/schemas/plugins/SourceMapDevToolPlugin.check.d.ts +0 -7
  732. package/schemas/plugins/WatchIgnorePlugin.check.d.ts +0 -7
  733. package/schemas/plugins/asset/AssetGeneratorOptions.check.d.ts +0 -7
  734. package/schemas/plugins/asset/AssetInlineGeneratorOptions.check.d.ts +0 -7
  735. package/schemas/plugins/asset/AssetParserOptions.check.d.ts +0 -7
  736. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.d.ts +0 -7
  737. package/schemas/plugins/container/ContainerPlugin.check.d.ts +0 -7
  738. package/schemas/plugins/container/ContainerReferencePlugin.check.d.ts +0 -7
  739. package/schemas/plugins/container/ExternalsType.check.d.ts +0 -7
  740. package/schemas/plugins/container/ModuleFederationPlugin.check.d.ts +0 -7
  741. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.d.ts +0 -7
  742. package/schemas/plugins/css/CssGeneratorOptions.check.d.ts +0 -7
  743. package/schemas/plugins/css/CssModuleGeneratorOptions.check.d.ts +0 -7
  744. package/schemas/plugins/css/CssModuleParserOptions.check.d.ts +0 -7
  745. package/schemas/plugins/css/CssParserOptions.check.d.ts +0 -7
  746. package/schemas/plugins/debug/ProfilingPlugin.check.d.ts +0 -7
  747. package/schemas/plugins/dll/DllPlugin.check.d.ts +0 -7
  748. package/schemas/plugins/dll/DllReferencePlugin.check.d.ts +0 -7
  749. package/schemas/plugins/ids/HashedModuleIdsPlugin.check.d.ts +0 -7
  750. package/schemas/plugins/ids/OccurrenceChunkIdsPlugin.check.d.ts +0 -7
  751. package/schemas/plugins/ids/OccurrenceModuleIdsPlugin.check.d.ts +0 -7
  752. package/schemas/plugins/json/JsonModulesPluginGenerator.check.d.ts +0 -7
  753. package/schemas/plugins/json/JsonModulesPluginParser.check.d.ts +0 -7
  754. package/schemas/plugins/optimize/AggressiveSplittingPlugin.check.d.ts +0 -7
  755. package/schemas/plugins/optimize/LimitChunkCountPlugin.check.d.ts +0 -7
  756. package/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.d.ts +0 -7
  757. package/schemas/plugins/optimize/MinChunkSizePlugin.check.d.ts +0 -7
  758. package/schemas/plugins/schemes/HttpUriPlugin.check.d.ts +0 -7
  759. package/schemas/plugins/schemes/VirtualUrlPlugin.check.d.ts +0 -7
  760. package/schemas/plugins/sharing/ConsumeSharedPlugin.check.d.ts +0 -7
  761. package/schemas/plugins/sharing/ProvideSharedPlugin.check.d.ts +0 -7
  762. package/schemas/plugins/sharing/SharePlugin.check.d.ts +0 -7
  763. /package/lib/{validateSchema.js → config/validateSchema.js} +0 -0
  764. /package/lib/{util → css}/conventions.js +0 -0
  765. /package/lib/{util → css}/topologicalSort.js +0 -0
  766. /package/lib/dependencies/{getFunctionExpression.js → helpers/getFunctionExpression.js} +0 -0
  767. /package/lib/{util → externals}/extractUrlAndGlobal.js +0 -0
  768. /package/lib/{util → fs}/StackedCacheMap.js +0 -0
  769. /package/lib/{util → javascript}/StackedMap.js +0 -0
  770. /package/lib/{ModuleProfile.js → module/ModuleProfile.js} +0 -0
  771. /package/lib/{ModuleSourceTypeConstants.js → module/ModuleSourceTypeConstants.js} +0 -0
  772. /package/lib/{ModuleTypeConstants.js → module/ModuleTypeConstants.js} +0 -0
  773. /package/lib/{OptimizationStages.js → optimize/OptimizationStages.js} +0 -0
  774. /package/lib/{util → optimize}/Queue.js +0 -0
  775. /package/lib/{util → stats}/smartGrouping.js +0 -0
@@ -5,4632 +5,6 @@
5
5
 
6
6
  "use strict";
7
7
 
8
- const nodeModule = require("module");
9
- const { isAbsolute } = require("path");
10
- const { create: createResolver } = require("enhanced-resolve");
11
- const { DEFAULTS } = require("./config/defaults");
12
- const { collectCjsRequireSpecifiers } = require("./javascript/syntax");
13
- const AsyncQueue = require("./util/AsyncQueue");
14
- const StackedCacheMap = require("./util/StackedCacheMap");
15
- const asyncLib = require("./util/async");
16
- const createHash = require("./util/createHash");
17
- const { dirname, join, lstatReadlinkAbsolute, relative } = require("./util/fs");
18
- const makeSerializable = require("./util/makeSerializable");
19
- const memoize = require("./util/memoize");
20
- const processAsyncTree = require("./util/processAsyncTree");
21
-
22
- // only the mjs build-dependency walk needs it
23
- const getEsModuleLexer = memoize(() => require("es-module-lexer"));
24
-
25
- /** @import { ResolveRequest, ResolveFunctionAsync } from "enhanced-resolve" */
26
- /** @import { HashFunction } from "../declarations/WebpackOptions" */
27
- /** @import { Logger } from "./logging/Logger" */
28
- /** @import WebpackError from "./errors/WebpackError" */
29
- /** @import { JsonObject, IStats, InputFileSystem } from "./util/fs" */
30
- /**
31
- * @import {
32
- * ObjectDeserializerContext,
33
- * ObjectSerializerContext
34
- * } from "./serialization/ObjectMiddleware"
35
- */
36
- /**
37
- * Defines the processor callback type used by this module.
38
- * @template T
39
- * @typedef {import("./util/AsyncQueue").Callback<T>} ProcessorCallback
40
- */
41
- /**
42
- * Defines the processor type used by this module.
43
- * @template T, R
44
- * @typedef {import("./util/AsyncQueue").Processor<T, R>} Processor
45
- */
46
-
47
- const supportsEsm = Number(process.versions.modules) >= 83;
48
-
49
- /** @type {Set<string>} */
50
- const builtinModules = new Set(nodeModule.builtinModules);
51
-
52
- let FS_ACCURACY = 2000;
53
-
54
- /** @type {Set<string>} */
55
- const EMPTY_SET = new Set();
56
-
57
- const RBDT_RESOLVE_INITIAL = 0;
58
- const RBDT_RESOLVE_FILE = 1;
59
- const RBDT_RESOLVE_DIRECTORY = 2;
60
- const RBDT_RESOLVE_CJS_FILE = 3;
61
- const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4;
62
- const RBDT_RESOLVE_ESM_FILE = 5;
63
- const RBDT_DIRECTORY = 6;
64
- const RBDT_FILE = 7;
65
- const RBDT_DIRECTORY_DEPENDENCIES = 8;
66
- const RBDT_FILE_DEPENDENCIES = 9;
67
-
68
- /** @typedef {RBDT_RESOLVE_INITIAL | RBDT_RESOLVE_FILE | RBDT_RESOLVE_DIRECTORY | RBDT_RESOLVE_CJS_FILE | RBDT_RESOLVE_CJS_FILE_AS_CHILD | RBDT_RESOLVE_ESM_FILE | RBDT_DIRECTORY | RBDT_FILE | RBDT_DIRECTORY_DEPENDENCIES | RBDT_FILE_DEPENDENCIES} JobType */
69
-
70
- const INVALID = Symbol("invalid");
71
-
72
- // eslint-disable-next-line jsdoc/ts-no-empty-object-type
73
- /** @typedef {{ }} ExistenceOnlyTimeEntry */
74
-
75
- /**
76
- * Defines the file system info entry type used by this module.
77
- * @typedef {object} FileSystemInfoEntry
78
- * @property {number} safeTime
79
- * @property {number=} timestamp
80
- */
81
-
82
- /**
83
- * Defines the resolved context file system info entry type used by this module.
84
- * @typedef {object} ResolvedContextFileSystemInfoEntry
85
- * @property {number} safeTime
86
- * @property {string=} timestampHash
87
- */
88
-
89
- /** @typedef {Set<string>} Symlinks */
90
-
91
- /**
92
- * Defines the context file system info entry type used by this module.
93
- * @typedef {object} ContextFileSystemInfoEntry
94
- * @property {number} safeTime
95
- * @property {string=} timestampHash
96
- * @property {ResolvedContextFileSystemInfoEntry=} resolved
97
- * @property {Symlinks=} symlinks
98
- */
99
-
100
- /**
101
- * Defines the timestamp and hash type used by this module.
102
- * @typedef {object} TimestampAndHash
103
- * @property {number} safeTime
104
- * @property {number=} timestamp
105
- * @property {string} hash
106
- */
107
-
108
- /**
109
- * Defines the resolved context timestamp and hash type used by this module.
110
- * @typedef {object} ResolvedContextTimestampAndHash
111
- * @property {number} safeTime
112
- * @property {string=} timestampHash
113
- * @property {string} hash
114
- */
115
-
116
- /**
117
- * Defines the context timestamp and hash type used by this module.
118
- * @typedef {object} ContextTimestampAndHash
119
- * @property {number} safeTime
120
- * @property {string=} timestampHash
121
- * @property {string} hash
122
- * @property {ResolvedContextTimestampAndHash=} resolved
123
- * @property {Symlinks=} symlinks
124
- */
125
-
126
- /**
127
- * Defines the context hash type used by this module.
128
- * @typedef {object} ContextHash
129
- * @property {string} hash
130
- * @property {string=} resolved
131
- * @property {Symlinks=} symlinks
132
- */
133
-
134
- /** @typedef {Set<string>} SnapshotContent */
135
-
136
- /**
137
- * Defines the snapshot optimization entry type used by this module.
138
- * @typedef {object} SnapshotOptimizationEntry
139
- * @property {Snapshot} snapshot
140
- * @property {number} shared
141
- * @property {SnapshotContent | undefined} snapshotContent
142
- * @property {Set<SnapshotOptimizationEntry> | undefined} children
143
- */
144
-
145
- /** @typedef {Map<string, string | false | undefined>} ResolveResults */
146
-
147
- /** @typedef {Set<string>} Files */
148
- /** @typedef {Set<string>} Directories */
149
- /** @typedef {Set<string>} Missing */
150
-
151
- /**
152
- * Defines the resolve dependencies type used by this module.
153
- * @typedef {object} ResolveDependencies
154
- * @property {Files} files list of files
155
- * @property {Directories} directories list of directories
156
- * @property {Missing} missing list of missing entries
157
- */
158
-
159
- /**
160
- * Defines the resolve build dependencies result type used by this module.
161
- * @typedef {object} ResolveBuildDependenciesResult
162
- * @property {Files} files list of files
163
- * @property {Directories} directories list of directories
164
- * @property {Missing} missing list of missing entries
165
- * @property {ResolveResults} resolveResults stored resolve results
166
- * @property {ResolveDependencies} resolveDependencies dependencies of the resolving
167
- */
168
-
169
- /**
170
- * Defines the snapshot options type used by this module.
171
- * @typedef {object} SnapshotOptions
172
- * @property {boolean=} hash should use hash to snapshot
173
- * @property {boolean=} timestamp should use timestamp to snapshot
174
- */
175
-
176
- const DONE_ITERATOR_RESULT = new Set().keys().next();
177
-
178
- // cspell:word tshs
179
- // Tsh = Timestamp + Hash
180
- // Tshs = Timestamp + Hash combinations
181
-
182
- class SnapshotIterator {
183
- /**
184
- * Creates an instance of SnapshotIterator.
185
- * @param {() => IteratorResult<string>} next next
186
- */
187
- constructor(next) {
188
- this.next = next;
189
- }
190
- }
191
-
192
- /**
193
- * Defines the get maps function type used by this module.
194
- * @template T
195
- * @typedef {(snapshot: Snapshot) => T[]} GetMapsFunction
196
- */
197
-
198
- /**
199
- * Represents SnapshotIterable.
200
- * @template T
201
- */
202
- class SnapshotIterable {
203
- /**
204
- * Creates an instance of SnapshotIterable.
205
- * @param {Snapshot} snapshot snapshot
206
- * @param {GetMapsFunction<T>} getMaps get maps function
207
- */
208
- constructor(snapshot, getMaps) {
209
- /** @type {Snapshot} */
210
- this.snapshot = snapshot;
211
- /** @type {GetMapsFunction<T>} */
212
- this.getMaps = getMaps;
213
- }
214
-
215
- [Symbol.iterator]() {
216
- let state = 0;
217
- /** @type {IterableIterator<string>} */
218
- let it;
219
- /** @type {GetMapsFunction<T>} */
220
- let getMaps;
221
- /** @type {T[]} */
222
- let maps;
223
- /** @type {Snapshot} */
224
- let snapshot;
225
- /** @type {Snapshot[] | undefined} */
226
- let queue;
227
- return new SnapshotIterator(() => {
228
- for (;;) {
229
- switch (state) {
230
- case 0:
231
- snapshot = this.snapshot;
232
- getMaps = this.getMaps;
233
- maps = getMaps(snapshot);
234
- state = 1;
235
- /* falls through */
236
- case 1:
237
- if (maps.length > 0) {
238
- const map = maps.pop();
239
- if (map !== undefined) {
240
- it =
241
- /** @type {Set<string> | Map<string, EXPECTED_ANY>} */
242
- (map).keys();
243
- state = 2;
244
- } else {
245
- break;
246
- }
247
- } else {
248
- state = 3;
249
- break;
250
- }
251
- /* falls through */
252
- case 2: {
253
- const result = it.next();
254
- if (!result.done) return result;
255
- state = 1;
256
- break;
257
- }
258
- case 3: {
259
- const children = snapshot.children;
260
- if (children !== undefined) {
261
- if (children.size === 1) {
262
- // shortcut for a single child
263
- // avoids allocation of queue
264
- for (const child of children) snapshot = child;
265
- maps = getMaps(snapshot);
266
- state = 1;
267
- break;
268
- }
269
- if (queue === undefined) queue = [];
270
- for (const child of children) {
271
- queue.push(child);
272
- }
273
- }
274
- if (queue !== undefined && queue.length > 0) {
275
- snapshot = /** @type {Snapshot} */ (queue.pop());
276
- maps = getMaps(snapshot);
277
- state = 1;
278
- break;
279
- } else {
280
- state = 4;
281
- }
282
- }
283
- /* falls through */
284
- case 4:
285
- return DONE_ITERATOR_RESULT;
286
- }
287
- }
288
- });
289
- }
290
- }
291
-
292
- /** @typedef {Map<string, FileSystemInfoEntry | null>} FileTimestamps */
293
- /** @typedef {Map<string, string | null>} FileHashes */
294
- /** @typedef {Map<string, TimestampAndHash | string | null>} FileTshs */
295
- /** @typedef {Map<string, ResolvedContextFileSystemInfoEntry | null>} ContextTimestamps */
296
- /** @typedef {Map<string, string | null>} ContextHashes */
297
- /** @typedef {Map<string, ResolvedContextTimestampAndHash | null>} ContextTshs */
298
- /** @typedef {Map<string, boolean>} MissingExistence */
299
- /** @typedef {Map<string, string>} ManagedItemInfo */
300
- /** @typedef {Set<string>} ManagedFiles */
301
- /** @typedef {Set<string>} ManagedContexts */
302
- /** @typedef {Set<string>} ManagedMissing */
303
- /** @typedef {Set<Snapshot>} Children */
304
-
305
- // `Snapshot._flags` bit for each optional field. Serialized as a whole integer,
306
- // so these values are a persisted-cache format contract — never renumber them.
307
- const SNAPSHOT_FLAG_START_TIME = 1;
308
- const SNAPSHOT_FLAG_FILE_TIMESTAMPS = 2;
309
- const SNAPSHOT_FLAG_FILE_HASHES = 4;
310
- const SNAPSHOT_FLAG_FILE_TSHS = 8;
311
- const SNAPSHOT_FLAG_CONTEXT_TIMESTAMPS = 0x10;
312
- const SNAPSHOT_FLAG_CONTEXT_HASHES = 0x20;
313
- const SNAPSHOT_FLAG_CONTEXT_TSHS = 0x40;
314
- const SNAPSHOT_FLAG_MISSING_EXISTENCE = 0x80;
315
- const SNAPSHOT_FLAG_MANAGED_ITEM_INFO = 0x100;
316
- const SNAPSHOT_FLAG_MANAGED_FILES = 0x200;
317
- const SNAPSHOT_FLAG_MANAGED_CONTEXTS = 0x400;
318
- const SNAPSHOT_FLAG_MANAGED_MISSING = 0x800;
319
- const SNAPSHOT_FLAG_CHILDREN = 0x1000;
320
-
321
- class Snapshot {
322
- constructor() {
323
- /** @type {number} */
324
- this._flags = 0;
325
- /** @type {Iterable<string> | undefined} */
326
- this._cachedFileIterable = undefined;
327
- /** @type {Iterable<string> | undefined} */
328
- this._cachedContextIterable = undefined;
329
- /** @type {Iterable<string> | undefined} */
330
- this._cachedMissingIterable = undefined;
331
- /** @type {number | undefined} */
332
- this.startTime = undefined;
333
- /** @type {FileTimestamps | undefined} */
334
- this.fileTimestamps = undefined;
335
- /** @type {FileHashes | undefined} */
336
- this.fileHashes = undefined;
337
- /** @type {FileTshs | undefined} */
338
- this.fileTshs = undefined;
339
- /** @type {ContextTimestamps | undefined} */
340
- this.contextTimestamps = undefined;
341
- /** @type {ContextHashes | undefined} */
342
- this.contextHashes = undefined;
343
- /** @type {ContextTshs | undefined} */
344
- this.contextTshs = undefined;
345
- /** @type {MissingExistence | undefined} */
346
- this.missingExistence = undefined;
347
- /** @type {ManagedItemInfo | undefined} */
348
- this.managedItemInfo = undefined;
349
- /** @type {ManagedFiles | undefined} */
350
- this.managedFiles = undefined;
351
- /** @type {ManagedContexts | undefined} */
352
- this.managedContexts = undefined;
353
- /** @type {ManagedMissing | undefined} */
354
- this.managedMissing = undefined;
355
- /** @type {Children | undefined} */
356
- this.children = undefined;
357
- }
358
-
359
- hasStartTime() {
360
- return (this._flags & SNAPSHOT_FLAG_START_TIME) !== 0;
361
- }
362
-
363
- /**
364
- * Updates start time using the provided value.
365
- * @param {number} value start value
366
- */
367
- setStartTime(value) {
368
- this._flags |= SNAPSHOT_FLAG_START_TIME;
369
- this.startTime = value;
370
- }
371
-
372
- /**
373
- * Sets merged start time.
374
- * @param {number | undefined} value value
375
- * @param {Snapshot} snapshot snapshot
376
- */
377
- setMergedStartTime(value, snapshot) {
378
- if (value) {
379
- if (snapshot.hasStartTime()) {
380
- this.setStartTime(
381
- Math.min(
382
- value,
383
- /** @type {NonNullable<Snapshot["startTime"]>} */
384
- (snapshot.startTime)
385
- )
386
- );
387
- } else {
388
- this.setStartTime(value);
389
- }
390
- } else if (snapshot.hasStartTime()) {
391
- this.setStartTime(
392
- /** @type {NonNullable<Snapshot["startTime"]>} */
393
- (snapshot.startTime)
394
- );
395
- }
396
- }
397
-
398
- hasFileTimestamps() {
399
- return (this._flags & SNAPSHOT_FLAG_FILE_TIMESTAMPS) !== 0;
400
- }
401
-
402
- /**
403
- * Sets file timestamps.
404
- * @param {FileTimestamps} value file timestamps
405
- */
406
- setFileTimestamps(value) {
407
- this._flags |= SNAPSHOT_FLAG_FILE_TIMESTAMPS;
408
- this.fileTimestamps = value;
409
- }
410
-
411
- hasFileHashes() {
412
- return (this._flags & SNAPSHOT_FLAG_FILE_HASHES) !== 0;
413
- }
414
-
415
- /**
416
- * Updates file hashes using the provided value.
417
- * @param {FileHashes} value file hashes
418
- */
419
- setFileHashes(value) {
420
- this._flags |= SNAPSHOT_FLAG_FILE_HASHES;
421
- this.fileHashes = value;
422
- }
423
-
424
- hasFileTshs() {
425
- return (this._flags & SNAPSHOT_FLAG_FILE_TSHS) !== 0;
426
- }
427
-
428
- /**
429
- * Updates file tshs using the provided value.
430
- * @param {FileTshs} value file tshs
431
- */
432
- setFileTshs(value) {
433
- this._flags |= SNAPSHOT_FLAG_FILE_TSHS;
434
- this.fileTshs = value;
435
- }
436
-
437
- hasContextTimestamps() {
438
- return (this._flags & SNAPSHOT_FLAG_CONTEXT_TIMESTAMPS) !== 0;
439
- }
440
-
441
- /**
442
- * Sets context timestamps.
443
- * @param {ContextTimestamps} value context timestamps
444
- */
445
- setContextTimestamps(value) {
446
- this._flags |= SNAPSHOT_FLAG_CONTEXT_TIMESTAMPS;
447
- this.contextTimestamps = value;
448
- }
449
-
450
- hasContextHashes() {
451
- return (this._flags & SNAPSHOT_FLAG_CONTEXT_HASHES) !== 0;
452
- }
453
-
454
- /**
455
- * Sets context hashes.
456
- * @param {ContextHashes} value context hashes
457
- */
458
- setContextHashes(value) {
459
- this._flags |= SNAPSHOT_FLAG_CONTEXT_HASHES;
460
- this.contextHashes = value;
461
- }
462
-
463
- hasContextTshs() {
464
- return (this._flags & SNAPSHOT_FLAG_CONTEXT_TSHS) !== 0;
465
- }
466
-
467
- /**
468
- * Updates context tshs using the provided value.
469
- * @param {ContextTshs} value context tshs
470
- */
471
- setContextTshs(value) {
472
- this._flags |= SNAPSHOT_FLAG_CONTEXT_TSHS;
473
- this.contextTshs = value;
474
- }
475
-
476
- hasMissingExistence() {
477
- return (this._flags & SNAPSHOT_FLAG_MISSING_EXISTENCE) !== 0;
478
- }
479
-
480
- /**
481
- * Sets missing existence.
482
- * @param {MissingExistence} value context tshs
483
- */
484
- setMissingExistence(value) {
485
- this._flags |= SNAPSHOT_FLAG_MISSING_EXISTENCE;
486
- this.missingExistence = value;
487
- }
488
-
489
- hasManagedItemInfo() {
490
- return (this._flags & SNAPSHOT_FLAG_MANAGED_ITEM_INFO) !== 0;
491
- }
492
-
493
- /**
494
- * Sets managed item info.
495
- * @param {ManagedItemInfo} value managed item info
496
- */
497
- setManagedItemInfo(value) {
498
- this._flags |= SNAPSHOT_FLAG_MANAGED_ITEM_INFO;
499
- this.managedItemInfo = value;
500
- }
501
-
502
- hasManagedFiles() {
503
- return (this._flags & SNAPSHOT_FLAG_MANAGED_FILES) !== 0;
504
- }
505
-
506
- /**
507
- * Sets managed files.
508
- * @param {ManagedFiles} value managed files
509
- */
510
- setManagedFiles(value) {
511
- this._flags |= SNAPSHOT_FLAG_MANAGED_FILES;
512
- this.managedFiles = value;
513
- }
514
-
515
- hasManagedContexts() {
516
- return (this._flags & SNAPSHOT_FLAG_MANAGED_CONTEXTS) !== 0;
517
- }
518
-
519
- /**
520
- * Sets managed contexts.
521
- * @param {ManagedContexts} value managed contexts
522
- */
523
- setManagedContexts(value) {
524
- this._flags |= SNAPSHOT_FLAG_MANAGED_CONTEXTS;
525
- this.managedContexts = value;
526
- }
527
-
528
- hasManagedMissing() {
529
- return (this._flags & SNAPSHOT_FLAG_MANAGED_MISSING) !== 0;
530
- }
531
-
532
- /**
533
- * Sets managed missing.
534
- * @param {ManagedMissing} value managed missing
535
- */
536
- setManagedMissing(value) {
537
- this._flags |= SNAPSHOT_FLAG_MANAGED_MISSING;
538
- this.managedMissing = value;
539
- }
540
-
541
- hasChildren() {
542
- return (this._flags & SNAPSHOT_FLAG_CHILDREN) !== 0;
543
- }
544
-
545
- /**
546
- * Updates children using the provided value.
547
- * @param {Children} value children
548
- */
549
- setChildren(value) {
550
- this._flags |= SNAPSHOT_FLAG_CHILDREN;
551
- this.children = value;
552
- }
553
-
554
- /**
555
- * Adds the provided child to the snapshot.
556
- * @param {Snapshot} child children
557
- */
558
- addChild(child) {
559
- if (!this.hasChildren()) {
560
- this.setChildren(new Set());
561
- }
562
- /** @type {Children} */
563
- (this.children).add(child);
564
- }
565
-
566
- /**
567
- * Serializes this instance into the provided serializer context.
568
- * @param {ObjectSerializerContext} context context
569
- */
570
- serialize({ write }) {
571
- write(this._flags);
572
- if (this.hasStartTime()) write(this.startTime);
573
- if (this.hasFileTimestamps()) write(this.fileTimestamps);
574
- if (this.hasFileHashes()) write(this.fileHashes);
575
- if (this.hasFileTshs()) write(this.fileTshs);
576
- if (this.hasContextTimestamps()) write(this.contextTimestamps);
577
- if (this.hasContextHashes()) write(this.contextHashes);
578
- if (this.hasContextTshs()) write(this.contextTshs);
579
- if (this.hasMissingExistence()) write(this.missingExistence);
580
- if (this.hasManagedItemInfo()) write(this.managedItemInfo);
581
- if (this.hasManagedFiles()) write(this.managedFiles);
582
- if (this.hasManagedContexts()) write(this.managedContexts);
583
- if (this.hasManagedMissing()) write(this.managedMissing);
584
- if (this.hasChildren()) write(this.children);
585
- }
586
-
587
- /**
588
- * Restores this instance from the provided deserializer context.
589
- * @param {ObjectDeserializerContext} context context
590
- */
591
- deserialize({ read }) {
592
- this._flags = read();
593
- if (this.hasStartTime()) this.startTime = read();
594
- if (this.hasFileTimestamps()) this.fileTimestamps = read();
595
- if (this.hasFileHashes()) this.fileHashes = read();
596
- if (this.hasFileTshs()) this.fileTshs = read();
597
- if (this.hasContextTimestamps()) this.contextTimestamps = read();
598
- if (this.hasContextHashes()) this.contextHashes = read();
599
- if (this.hasContextTshs()) this.contextTshs = read();
600
- if (this.hasMissingExistence()) this.missingExistence = read();
601
- if (this.hasManagedItemInfo()) this.managedItemInfo = read();
602
- if (this.hasManagedFiles()) this.managedFiles = read();
603
- if (this.hasManagedContexts()) this.managedContexts = read();
604
- if (this.hasManagedMissing()) this.managedMissing = read();
605
- if (this.hasChildren()) this.children = read();
606
- }
607
-
608
- /**
609
- * Creates an iterable from the provided get map.
610
- * @template T
611
- * @param {GetMapsFunction<T>} getMaps first
612
- * @returns {SnapshotIterable<T>} iterable
613
- */
614
- _createIterable(getMaps) {
615
- return new SnapshotIterable(this, getMaps);
616
- }
617
-
618
- /**
619
- * Gets file iterable.
620
- * @returns {Iterable<string>} iterable
621
- */
622
- getFileIterable() {
623
- if (this._cachedFileIterable === undefined) {
624
- this._cachedFileIterable = this._createIterable((s) => [
625
- s.fileTimestamps,
626
- s.fileHashes,
627
- s.fileTshs,
628
- s.managedFiles
629
- ]);
630
- }
631
- return this._cachedFileIterable;
632
- }
633
-
634
- /**
635
- * Gets context iterable.
636
- * @returns {Iterable<string>} iterable
637
- */
638
- getContextIterable() {
639
- if (this._cachedContextIterable === undefined) {
640
- this._cachedContextIterable = this._createIterable((s) => [
641
- s.contextTimestamps,
642
- s.contextHashes,
643
- s.contextTshs,
644
- s.managedContexts
645
- ]);
646
- }
647
- return this._cachedContextIterable;
648
- }
649
-
650
- /**
651
- * Gets missing iterable.
652
- * @returns {Iterable<string>} iterable
653
- */
654
- getMissingIterable() {
655
- if (this._cachedMissingIterable === undefined) {
656
- this._cachedMissingIterable = this._createIterable((s) => [
657
- s.missingExistence,
658
- s.managedMissing
659
- ]);
660
- }
661
- return this._cachedMissingIterable;
662
- }
663
- }
664
-
665
- makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot");
666
-
667
- const MIN_COMMON_SNAPSHOT_SIZE = 3;
668
-
669
- /**
670
- * Defines the snapshot optimization value type used by this module.
671
- * @template U, T
672
- * @typedef {U extends true ? Set<string> : Map<string, T>} SnapshotOptimizationValue
673
- */
674
-
675
- /**
676
- * Represents SnapshotOptimization.
677
- * @template T
678
- * @template {boolean} [U=false]
679
- */
680
- class SnapshotOptimization {
681
- /**
682
- * Creates an instance of SnapshotOptimization.
683
- * @param {(snapshot: Snapshot) => boolean} has has value
684
- * @param {(snapshot: Snapshot) => SnapshotOptimizationValue<U, T> | undefined} get get value
685
- * @param {(snapshot: Snapshot, value: SnapshotOptimizationValue<U, T>) => void} set set value
686
- * @param {boolean=} useStartTime use the start time of snapshots
687
- * @param {U=} isSet value is an Set instead of a Map
688
- */
689
- constructor(
690
- has,
691
- get,
692
- set,
693
- useStartTime = true,
694
- isSet = /** @type {U} */ (false)
695
- ) {
696
- this._has = has;
697
- this._get = get;
698
- this._set = set;
699
- /** @type {boolean} */
700
- this._useStartTime = useStartTime;
701
- /** @type {U} */
702
- this._isSet = isSet;
703
- /** @type {Map<string, SnapshotOptimizationEntry>} */
704
- this._map = new Map();
705
- /** @type {number} */
706
- this._statItemsShared = 0;
707
- /** @type {number} */
708
- this._statItemsUnshared = 0;
709
- /** @type {number} */
710
- this._statSharedSnapshots = 0;
711
- /** @type {number} */
712
- this._statReusedSharedSnapshots = 0;
713
- }
714
-
715
- getStatisticMessage() {
716
- const total = this._statItemsShared + this._statItemsUnshared;
717
- if (total === 0) return;
718
- return `${
719
- this._statItemsShared && Math.round((this._statItemsShared * 100) / total)
720
- }% (${this._statItemsShared}/${total}) entries shared via ${
721
- this._statSharedSnapshots
722
- } shared snapshots (${
723
- this._statReusedSharedSnapshots + this._statSharedSnapshots
724
- } times referenced)`;
725
- }
726
-
727
- clear() {
728
- this._map.clear();
729
- this._statItemsShared = 0;
730
- this._statItemsUnshared = 0;
731
- this._statSharedSnapshots = 0;
732
- this._statReusedSharedSnapshots = 0;
733
- }
734
-
735
- /**
736
- * Processes the provided new snapshot.
737
- * @param {Snapshot} newSnapshot snapshot
738
- * @param {Set<string>} capturedFiles files to snapshot/share
739
- * @returns {void}
740
- */
741
- optimize(newSnapshot, capturedFiles) {
742
- if (capturedFiles.size === 0) {
743
- return;
744
- }
745
- /**
746
- * Increase shared and store optimization entry.
747
- * @param {SnapshotOptimizationEntry} entry optimization entry
748
- * @returns {void}
749
- */
750
- const increaseSharedAndStoreOptimizationEntry = (entry) => {
751
- if (entry.children !== undefined) {
752
- for (const child of entry.children) {
753
- increaseSharedAndStoreOptimizationEntry(child);
754
- }
755
- }
756
- entry.shared++;
757
- storeOptimizationEntry(entry);
758
- };
759
- /**
760
- * Stores optimization entry.
761
- * @param {SnapshotOptimizationEntry} entry optimization entry
762
- * @returns {void}
763
- */
764
- const storeOptimizationEntry = (entry) => {
765
- for (const path of /** @type {SnapshotContent} */ (
766
- entry.snapshotContent
767
- )) {
768
- const old =
769
- /** @type {SnapshotOptimizationEntry} */
770
- (this._map.get(path));
771
- if (old.shared < entry.shared) {
772
- this._map.set(path, entry);
773
- }
774
- capturedFiles.delete(path);
775
- }
776
- };
777
-
778
- /** @type {SnapshotOptimizationEntry | undefined} */
779
- let newOptimizationEntry;
780
-
781
- const capturedFilesSize = capturedFiles.size;
782
-
783
- /** @type {Set<SnapshotOptimizationEntry> | undefined} */
784
- const optimizationEntries = new Set();
785
-
786
- for (const path of capturedFiles) {
787
- const optimizationEntry = this._map.get(path);
788
- if (optimizationEntry === undefined) {
789
- if (newOptimizationEntry === undefined) {
790
- newOptimizationEntry = {
791
- snapshot: newSnapshot,
792
- shared: 0,
793
- snapshotContent: undefined,
794
- children: undefined
795
- };
796
- }
797
- this._map.set(path, newOptimizationEntry);
798
- } else {
799
- optimizationEntries.add(optimizationEntry);
800
- }
801
- }
802
-
803
- optimizationEntriesLabel: for (const optimizationEntry of optimizationEntries) {
804
- const snapshot = optimizationEntry.snapshot;
805
- if (optimizationEntry.shared > 0) {
806
- // It's a shared snapshot
807
- // We can't change it, so we can only use it when all files match
808
- // and startTime is compatible
809
- if (
810
- this._useStartTime &&
811
- newSnapshot.startTime &&
812
- (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime)
813
- ) {
814
- continue;
815
- }
816
- /** @type {Set<string>} */
817
- const nonSharedFiles = new Set();
818
- const snapshotContent =
819
- /** @type {NonNullable<SnapshotOptimizationEntry["snapshotContent"]>} */
820
- (optimizationEntry.snapshotContent);
821
- const snapshotEntries =
822
- /** @type {SnapshotOptimizationValue<U, T>} */
823
- (this._get(snapshot));
824
- for (const path of snapshotContent) {
825
- if (!capturedFiles.has(path)) {
826
- if (!snapshotEntries.has(path)) {
827
- // File is not shared and can't be removed from the snapshot
828
- // because it's in a child of the snapshot
829
- continue optimizationEntriesLabel;
830
- }
831
- nonSharedFiles.add(path);
832
- }
833
- }
834
- if (nonSharedFiles.size === 0) {
835
- // The complete snapshot is shared
836
- // add it as child
837
- newSnapshot.addChild(snapshot);
838
- increaseSharedAndStoreOptimizationEntry(optimizationEntry);
839
- this._statReusedSharedSnapshots++;
840
- } else {
841
- // Only a part of the snapshot is shared
842
- const sharedCount = snapshotContent.size - nonSharedFiles.size;
843
- if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) {
844
- // Common part it too small
845
- continue;
846
- }
847
- // Extract common timestamps from both snapshots
848
- /** @type {Set<string> | Map<string, T>} */
849
- let commonMap;
850
- if (this._isSet) {
851
- commonMap = new Set();
852
- for (const path of /** @type {Set<string>} */ (snapshotEntries)) {
853
- if (nonSharedFiles.has(path)) continue;
854
- commonMap.add(path);
855
- snapshotEntries.delete(path);
856
- }
857
- } else {
858
- commonMap = new Map();
859
- const map = /** @type {Map<string, T>} */ (snapshotEntries);
860
- for (const [path, value] of map) {
861
- if (nonSharedFiles.has(path)) continue;
862
- commonMap.set(path, value);
863
- snapshotEntries.delete(path);
864
- }
865
- }
866
- // Create and attach snapshot
867
- const commonSnapshot = new Snapshot();
868
- if (this._useStartTime) {
869
- commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot);
870
- }
871
- this._set(
872
- commonSnapshot,
873
- /** @type {SnapshotOptimizationValue<U, T>} */ (commonMap)
874
- );
875
- newSnapshot.addChild(commonSnapshot);
876
- snapshot.addChild(commonSnapshot);
877
- // Create optimization entry
878
- const newEntry = {
879
- snapshot: commonSnapshot,
880
- shared: optimizationEntry.shared + 1,
881
- snapshotContent: new Set(commonMap.keys()),
882
- children: undefined
883
- };
884
- if (optimizationEntry.children === undefined) {
885
- optimizationEntry.children = new Set();
886
- }
887
- optimizationEntry.children.add(newEntry);
888
- storeOptimizationEntry(newEntry);
889
- this._statSharedSnapshots++;
890
- }
891
- } else {
892
- // It's a unshared snapshot
893
- // We can extract a common shared snapshot
894
- // with all common files
895
- const snapshotEntries = this._get(snapshot);
896
- if (snapshotEntries === undefined) {
897
- // Incomplete snapshot, that can't be used
898
- continue;
899
- }
900
- /** @type {Set<string> | Map<string, T>} */
901
- let commonMap;
902
- if (this._isSet) {
903
- commonMap = new Set();
904
- const set = /** @type {Set<string>} */ (snapshotEntries);
905
- if (capturedFiles.size < set.size) {
906
- for (const path of capturedFiles) {
907
- if (set.has(path)) commonMap.add(path);
908
- }
909
- } else {
910
- for (const path of set) {
911
- if (capturedFiles.has(path)) commonMap.add(path);
912
- }
913
- }
914
- } else {
915
- commonMap = new Map();
916
- const map = /** @type {Map<string, T>} */ (snapshotEntries);
917
- for (const path of capturedFiles) {
918
- const ts = map.get(path);
919
- if (ts === undefined) continue;
920
- commonMap.set(path, ts);
921
- }
922
- }
923
-
924
- if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) {
925
- // Common part it too small
926
- continue;
927
- }
928
- // Create and attach snapshot
929
- const commonSnapshot = new Snapshot();
930
- if (this._useStartTime) {
931
- commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot);
932
- }
933
- this._set(
934
- commonSnapshot,
935
- /** @type {SnapshotOptimizationValue<U, T>} */
936
- (commonMap)
937
- );
938
- newSnapshot.addChild(commonSnapshot);
939
- snapshot.addChild(commonSnapshot);
940
- // Remove files from snapshot
941
- for (const path of commonMap.keys()) snapshotEntries.delete(path);
942
- const sharedCount = commonMap.size;
943
- this._statItemsUnshared -= sharedCount;
944
- this._statItemsShared += sharedCount;
945
- // Create optimization entry
946
- storeOptimizationEntry({
947
- snapshot: commonSnapshot,
948
- shared: 2,
949
- snapshotContent: new Set(commonMap.keys()),
950
- children: undefined
951
- });
952
- this._statSharedSnapshots++;
953
- }
954
- }
955
- const unshared = capturedFiles.size;
956
- this._statItemsUnshared += unshared;
957
- this._statItemsShared += capturedFilesSize - unshared;
958
- }
959
- }
960
-
961
- /** @type {Record<string, string>} */
962
- const ESCAPES = {
963
- n: "\n",
964
- r: "\r",
965
- t: "\t",
966
- b: "\b",
967
- f: "\f",
968
- v: "\v"
969
- };
970
-
971
- /**
972
- * Cooks a JS string/template literal specifier into its evaluated value,
973
- * matching ECMAScript escape semantics (sloppy-mode for string literals).
974
- * @param {string} str input including the surrounding quotes
975
- * @returns {string | null} result, or null when not a quoted literal
976
- * @throws {Error} on a malformed escape sequence, like the JS parser would
977
- */
978
- const parseString = (str) => {
979
- const q = str[0];
980
-
981
- if (q !== '"' && q !== "'" && q !== "`") {
982
- return null;
983
- }
984
-
985
- const template = q === "`";
986
- const inner = str.slice(1, -1);
987
- const len = inner.length;
988
- let result = "";
989
- let i = 0;
990
-
991
- while (i < len) {
992
- const ch = inner[i];
993
- if (ch !== "\\") {
994
- // Template value normalizes raw <CR> and <CRLF> to <LF>
995
- if (template && ch === "\r") {
996
- result += "\n";
997
- i += inner[i + 1] === "\n" ? 2 : 1;
998
- } else {
999
- result += ch;
1000
- i++;
1001
- }
1002
- continue;
1003
- }
1004
-
1005
- i++;
1006
- if (i >= len) throw new Error("Unterminated escape sequence");
1007
- const esc = inner[i];
1008
-
1009
- if (esc === "x") {
1010
- const hex = inner.slice(i + 1, i + 3);
1011
- if (!/^[0-9a-fA-F]{2}$/.test(hex)) {
1012
- throw new Error("Invalid hexadecimal escape sequence");
1013
- }
1014
- result += String.fromCharCode(Number.parseInt(hex, 16));
1015
- i += 3;
1016
- } else if (esc === "u") {
1017
- if (inner[i + 1] === "{") {
1018
- // \u{N...}
1019
- const closeIdx = inner.indexOf("}", i + 2);
1020
- const codeStr = closeIdx === -1 ? "" : inner.slice(i + 2, closeIdx);
1021
- const code = Number.parseInt(codeStr, 16);
1022
- if (!/^[0-9a-fA-F]+$/.test(codeStr) || code > 0x10ffff) {
1023
- throw new Error("Invalid Unicode escape sequence");
1024
- }
1025
- result += String.fromCodePoint(code);
1026
- i = closeIdx + 1;
1027
- } else {
1028
- // \uNNNN
1029
- const hex = inner.slice(i + 1, i + 5);
1030
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
1031
- throw new Error("Invalid Unicode escape sequence");
1032
- }
1033
- result += String.fromCharCode(Number.parseInt(hex, 16));
1034
- i += 5;
1035
- }
1036
- } else if (esc === "\r") {
1037
- // Line continuation: \<CR> or \<CRLF>
1038
- i += inner[i + 1] === "\n" ? 2 : 1;
1039
- } else if (esc === "\n" || esc === "\u2028" || esc === "\u2029") {
1040
- // Line continuation: \<LF>, \<LS>, \<PS>
1041
- i++;
1042
- } else if (ESCAPES[esc] !== undefined) {
1043
- result += ESCAPES[esc];
1044
- i++;
1045
- } else if (esc >= "0" && esc <= "7") {
1046
- // \0 not followed by a digit is NUL, otherwise a legacy octal escape
1047
- const next = inner[i + 1];
1048
- if (esc === "0" && !(next >= "0" && next <= "9")) {
1049
- result += "\0";
1050
- i++;
1051
- continue;
1052
- }
1053
- if (template) throw new Error("Octal escape not allowed in template");
1054
- // Up to 3 octal digits, value capped at \377
1055
- let oct = esc;
1056
- i++;
1057
- const max = esc <= "3" ? 3 : 2;
1058
- while (oct.length < max && inner[i] >= "0" && inner[i] <= "7") {
1059
- oct += inner[i];
1060
- i++;
1061
- }
1062
- result += String.fromCharCode(Number.parseInt(oct, 8));
1063
- } else if (esc === "8" || esc === "9") {
1064
- if (template) throw new Error("\\8 and \\9 not allowed in template");
1065
- result += esc;
1066
- i++;
1067
- } else {
1068
- // \', \", \\, \`, and any other NonEscapeCharacter — the char itself
1069
- result += esc;
1070
- i++;
1071
- }
1072
- }
1073
-
1074
- return result;
1075
- };
1076
-
1077
- /* istanbul ignore next */
1078
- /**
1079
- * Processes the provided mtime.
1080
- * @param {number} mtime mtime
1081
- */
1082
- const applyMtime = (mtime) => {
1083
- if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1;
1084
- else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10;
1085
- else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100;
1086
- else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000;
1087
- };
1088
-
1089
- /**
1090
- * Merges the provided values into a single result.
1091
- * @template T
1092
- * @template K
1093
- * @param {Map<T, K> | undefined} a source map
1094
- * @param {Map<T, K> | undefined} b joining map
1095
- * @returns {Map<T, K>} joined map
1096
- */
1097
- const mergeMaps = (a, b) => {
1098
- if (!b || b.size === 0) return /** @type {Map<T, K>} */ (a);
1099
- if (!a || a.size === 0) return /** @type {Map<T, K>} */ (b);
1100
- /** @type {Map<T, K>} */
1101
- const map = new Map(a);
1102
- for (const [key, value] of b) {
1103
- map.set(key, value);
1104
- }
1105
- return map;
1106
- };
1107
-
1108
- /**
1109
- * Merges the provided values into a single result.
1110
- * @template T
1111
- * @param {Set<T> | undefined} a source map
1112
- * @param {Set<T> | undefined} b joining map
1113
- * @returns {Set<T>} joined map
1114
- */
1115
- const mergeSets = (a, b) => {
1116
- if (!b || b.size === 0) return /** @type {Set<T>} */ (a);
1117
- if (!a || a.size === 0) return /** @type {Set<T>} */ (b);
1118
- /** @type {Set<T>} */
1119
- const map = new Set(a);
1120
- for (const item of b) {
1121
- map.add(item);
1122
- }
1123
- return map;
1124
- };
1125
-
1126
- /**
1127
- * Finding file or directory to manage
1128
- * @param {string} managedPath path that is managing by {@link FileSystemInfo}
1129
- * @param {string} path path to file or directory
1130
- * @returns {string | null} managed item
1131
- * @example
1132
- * getManagedItem(
1133
- * '/Users/user/my-project/node_modules/',
1134
- * '/Users/user/my-project/node_modules/package/index.js'
1135
- * ) === '/Users/user/my-project/node_modules/package'
1136
- * getManagedItem(
1137
- * '/Users/user/my-project/node_modules/',
1138
- * '/Users/user/my-project/node_modules/package1/node_modules/package2'
1139
- * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2'
1140
- * getManagedItem(
1141
- * '/Users/user/my-project/node_modules/',
1142
- * '/Users/user/my-project/node_modules/.bin/script.js'
1143
- * ) === null // hidden files are disallowed as managed items
1144
- * getManagedItem(
1145
- * '/Users/user/my-project/node_modules/',
1146
- * '/Users/user/my-project/node_modules/package'
1147
- * ) === '/Users/user/my-project/node_modules/package'
1148
- */
1149
- const getManagedItem = (managedPath, path) => {
1150
- let i = managedPath.length;
1151
- let slashes = 1;
1152
- let startingPosition = true;
1153
- loop: while (i < path.length) {
1154
- switch (path.charCodeAt(i)) {
1155
- case 47: // slash
1156
- case 92: // backslash
1157
- if (--slashes === 0) break loop;
1158
- startingPosition = true;
1159
- break;
1160
- case 46: // .
1161
- // hidden files are disallowed as managed items
1162
- // it's probably .yarn-integrity or .cache
1163
- if (startingPosition) return null;
1164
- break;
1165
- case 64: // @
1166
- if (!startingPosition) return null;
1167
- slashes++;
1168
- break;
1169
- default:
1170
- startingPosition = false;
1171
- break;
1172
- }
1173
- i++;
1174
- }
1175
- if (i === path.length) slashes--;
1176
- // return null when path is incomplete
1177
- if (slashes !== 0) return null;
1178
- // if (path.slice(i + 1, i + 13) === "node_modules")
1179
- if (
1180
- path.length >= i + 13 &&
1181
- path.charCodeAt(i + 1) === 110 &&
1182
- path.charCodeAt(i + 2) === 111 &&
1183
- path.charCodeAt(i + 3) === 100 &&
1184
- path.charCodeAt(i + 4) === 101 &&
1185
- path.charCodeAt(i + 5) === 95 &&
1186
- path.charCodeAt(i + 6) === 109 &&
1187
- path.charCodeAt(i + 7) === 111 &&
1188
- path.charCodeAt(i + 8) === 100 &&
1189
- path.charCodeAt(i + 9) === 117 &&
1190
- path.charCodeAt(i + 10) === 108 &&
1191
- path.charCodeAt(i + 11) === 101 &&
1192
- path.charCodeAt(i + 12) === 115
1193
- ) {
1194
- // if this is the end of the path
1195
- if (path.length === i + 13) {
1196
- // return the node_modules directory
1197
- // it's special
1198
- return path;
1199
- }
1200
- const c = path.charCodeAt(i + 13);
1201
- // if next symbol is slash or backslash
1202
- if (c === 47 || c === 92) {
1203
- // Managed subpath
1204
- return getManagedItem(path.slice(0, i + 14), path);
1205
- }
1206
- }
1207
- return path.slice(0, i);
1208
- };
1209
-
1210
- /**
1211
- * The managed directory a `snapshot.managedPaths` RegExp matched. The schema
1212
- * documents it as matching that directory, so a capture-less pattern is it.
1213
- * @param {RegExpExecArray} match a match of a managed path RegExp
1214
- * @returns {string} the managed directory
1215
- */
1216
- const getManagedPathFromMatch = (match) =>
1217
- match[1] === undefined ? match[0] : match[1];
1218
-
1219
- /**
1220
- * Gets resolved timestamp.
1221
- * @template {ContextFileSystemInfoEntry | ContextTimestampAndHash} T
1222
- * @param {T | null} entry entry
1223
- * @returns {T["resolved"] | null | undefined} the resolved entry
1224
- */
1225
- const getResolvedTimestamp = (entry) => {
1226
- if (entry === null) return null;
1227
- if (entry.resolved !== undefined) return entry.resolved;
1228
- return entry.symlinks === undefined ? entry : undefined;
1229
- };
1230
-
1231
- /**
1232
- * Gets resolved hash.
1233
- * @param {ContextHash | null} entry entry
1234
- * @returns {string | null | undefined} the resolved entry
1235
- */
1236
- const getResolvedHash = (entry) => {
1237
- if (entry === null) return null;
1238
- if (entry.resolved !== undefined) return entry.resolved;
1239
- return entry.symlinks === undefined ? entry.hash : undefined;
1240
- };
1241
-
1242
- /**
1243
- * Adds the provided source to the snapshot optimization.
1244
- * @template T
1245
- * @param {Set<T>} source source
1246
- * @param {Set<T>} target target
1247
- */
1248
- const addAll = (source, target) => {
1249
- for (const key of source) target.add(key);
1250
- };
1251
-
1252
- // Bun doesn't populate `require.cache` `module.children`, so the CJS build-dependency
1253
- // walk needs a source-parsing fallback there. Node/Deno populate it — never pay for it.
1254
- const IS_BUN = Boolean(process.versions.bun);
1255
-
1256
- /** @typedef {Set<string>} LoggedPaths */
1257
-
1258
- /** @typedef {FileSystemInfoEntry | ExistenceOnlyTimeEntry | "ignore" | null} FileTimestamp */
1259
- /** @typedef {ContextFileSystemInfoEntry | ExistenceOnlyTimeEntry | "ignore" | null} ContextTimestamp */
1260
- /** @typedef {ResolvedContextFileSystemInfoEntry | "ignore" | null} ResolvedContextTimestamp */
1261
-
1262
- /**
1263
- * `watchpack` may report `{}` (existence-only) for files and directories it
1264
- * is watching but has no time information for. Such entries cannot be used
1265
- * for snapshot comparison, so cache lookups treat them as "no cached value"
1266
- * and fall back to a fresh on-disk read.
1267
- * @param {FileTimestamp | ContextTimestamp | undefined} entry cache entry
1268
- * @returns {entry is ExistenceOnlyTimeEntry} true if the entry exists but carries no time info
1269
- */
1270
- const isExistenceOnly = (entry) => {
1271
- if (entry === undefined || entry === null || entry === "ignore") return false;
1272
- return (
1273
- /** @type {Partial<FileSystemInfoEntry> & Partial<ContextFileSystemInfoEntry>} */
1274
- (entry).safeTime === undefined
1275
- );
1276
- };
1277
-
1278
- /**
1279
- * Watchpack directory entries may carry `safeTime` / `timestamp` but never
1280
- * `timestampHash`; such object caches cannot back snapshot checks or symlink walks.
1281
- * @param {ContextFileSystemInfoEntry | null | "ignore" | undefined} entry cache entry
1282
- * @returns {boolean} true when a non-null object entry lacks `timestampHash`
1283
- */
1284
- const contextCacheEntryLacksTimestampHash = (entry) =>
1285
- entry !== null &&
1286
- typeof entry === "object" &&
1287
- /** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash === undefined;
1288
-
1289
- /** @typedef {(err?: WebpackError | null, result?: boolean) => void} CheckSnapshotValidCallback */
1290
-
1291
- /**
1292
- * Used to access information about the filesystem in a cached way
1293
- */
1294
- class FileSystemInfo {
1295
- /**
1296
- * Creates an instance of FileSystemInfo.
1297
- * @param {InputFileSystem} fs file system
1298
- * @param {object} options options
1299
- * @param {Iterable<string | RegExp>=} options.unmanagedPaths paths that are not managed by a package manager and the contents are subject to change
1300
- * @param {Iterable<string | RegExp>=} options.managedPaths paths that are only managed by a package manager
1301
- * @param {Iterable<string | RegExp>=} options.immutablePaths paths that are immutable
1302
- * @param {Logger=} options.logger logger used to log invalid snapshots
1303
- * @param {HashFunction=} options.hashFunction the hash function to use
1304
- */
1305
- constructor(
1306
- fs,
1307
- {
1308
- unmanagedPaths = [],
1309
- managedPaths = [],
1310
- immutablePaths = [],
1311
- logger,
1312
- hashFunction = DEFAULTS.HASH_FUNCTION
1313
- } = {}
1314
- ) {
1315
- /** @type {InputFileSystem} */
1316
- this.fs = fs;
1317
- this.logger = logger;
1318
- /** @type {number} */
1319
- this._remainingLogs = logger ? 40 : 0;
1320
- /** @type {LoggedPaths | undefined} */
1321
- this._loggedPaths = logger ? new Set() : undefined;
1322
- /** @type {HashFunction} */
1323
- this._hashFunction = hashFunction;
1324
- /** @type {WeakMap<Snapshot, boolean | CheckSnapshotValidCallback[]>} */
1325
- this._snapshotCache = new WeakMap();
1326
- /** @type {SnapshotOptimization<FileSystemInfoEntry | null, false>} */
1327
- this._fileTimestampsOptimization = new SnapshotOptimization(
1328
- (s) => s.hasFileTimestamps(),
1329
- (s) => s.fileTimestamps,
1330
- (s, v) => s.setFileTimestamps(v)
1331
- );
1332
- /** @type {SnapshotOptimization<string | null, false>} */
1333
- this._fileHashesOptimization = new SnapshotOptimization(
1334
- (s) => s.hasFileHashes(),
1335
- (s) => s.fileHashes,
1336
- (s, v) => s.setFileHashes(v),
1337
- false
1338
- );
1339
- /** @type {SnapshotOptimization<string | TimestampAndHash | null, false>} */
1340
- this._fileTshsOptimization = new SnapshotOptimization(
1341
- (s) => s.hasFileTshs(),
1342
- (s) => s.fileTshs,
1343
- (s, v) => s.setFileTshs(v)
1344
- );
1345
- /** @type {SnapshotOptimization<ResolvedContextFileSystemInfoEntry | null, false>} */
1346
- this._contextTimestampsOptimization = new SnapshotOptimization(
1347
- (s) => s.hasContextTimestamps(),
1348
- (s) => s.contextTimestamps,
1349
- (s, v) => s.setContextTimestamps(v)
1350
- );
1351
- /** @type {SnapshotOptimization<string | null, false>} */
1352
- this._contextHashesOptimization = new SnapshotOptimization(
1353
- (s) => s.hasContextHashes(),
1354
- (s) => s.contextHashes,
1355
- (s, v) => s.setContextHashes(v),
1356
- false
1357
- );
1358
- /** @type {SnapshotOptimization<ResolvedContextTimestampAndHash | null, false>} */
1359
- this._contextTshsOptimization = new SnapshotOptimization(
1360
- (s) => s.hasContextTshs(),
1361
- (s) => s.contextTshs,
1362
- (s, v) => s.setContextTshs(v)
1363
- );
1364
- /** @type {SnapshotOptimization<boolean, false>} */
1365
- this._missingExistenceOptimization = new SnapshotOptimization(
1366
- (s) => s.hasMissingExistence(),
1367
- (s) => s.missingExistence,
1368
- (s, v) => s.setMissingExistence(v),
1369
- false
1370
- );
1371
- /** @type {SnapshotOptimization<string, false>} */
1372
- this._managedItemInfoOptimization = new SnapshotOptimization(
1373
- (s) => s.hasManagedItemInfo(),
1374
- (s) => s.managedItemInfo,
1375
- (s, v) => s.setManagedItemInfo(v),
1376
- false
1377
- );
1378
- this._managedFilesOptimization = new SnapshotOptimization(
1379
- (s) => s.hasManagedFiles(),
1380
- (s) => s.managedFiles,
1381
- (s, v) => s.setManagedFiles(v),
1382
- false,
1383
- true
1384
- );
1385
- this._managedContextsOptimization = new SnapshotOptimization(
1386
- (s) => s.hasManagedContexts(),
1387
- (s) => s.managedContexts,
1388
- (s, v) => s.setManagedContexts(v),
1389
- false,
1390
- true
1391
- );
1392
- this._managedMissingOptimization = new SnapshotOptimization(
1393
- (s) => s.hasManagedMissing(),
1394
- (s) => s.managedMissing,
1395
- (s, v) => s.setManagedMissing(v),
1396
- false,
1397
- true
1398
- );
1399
- /** @type {StackedCacheMap<string, FileTimestamp>} */
1400
- this._fileTimestamps = new StackedCacheMap();
1401
- /** @type {Map<string, string | null>} */
1402
- this._fileHashes = new Map();
1403
- /** @type {Map<string, TimestampAndHash | string>} */
1404
- this._fileTshs = new Map();
1405
- /** @type {StackedCacheMap<string, ContextTimestamp>} */
1406
- this._contextTimestamps = new StackedCacheMap();
1407
- /** @type {Map<string, ContextHash>} */
1408
- this._contextHashes = new Map();
1409
- /** @type {Map<string, ContextTimestampAndHash>} */
1410
- this._contextTshs = new Map();
1411
- /** @type {Map<string, string>} */
1412
- this._managedItems = new Map();
1413
- // memoized checkManaged results: 0 = not managed, 1 = immutable, string = managed item
1414
- /** @type {Map<string, 0 | 1 | string>} */
1415
- this._pathClassificationCache = new Map();
1416
- /** @type {AsyncQueue<string, string, FileSystemInfoEntry>} */
1417
- this.fileTimestampQueue = new AsyncQueue({
1418
- name: "file timestamp",
1419
- parallelism: 30,
1420
- processor: this._readFileTimestamp.bind(this)
1421
- });
1422
- /** @type {AsyncQueue<string, string, string>} */
1423
- this.fileHashQueue = new AsyncQueue({
1424
- name: "file hash",
1425
- parallelism: 10,
1426
- processor: this._readFileHash.bind(this)
1427
- });
1428
- /** @type {AsyncQueue<string, string, ContextFileSystemInfoEntry>} */
1429
- this.contextTimestampQueue = new AsyncQueue({
1430
- name: "context timestamp",
1431
- parallelism: 2,
1432
- processor: this._readContextTimestamp.bind(this)
1433
- });
1434
- /** @type {AsyncQueue<string, string, ContextHash>} */
1435
- this.contextHashQueue = new AsyncQueue({
1436
- name: "context hash",
1437
- parallelism: 2,
1438
- processor: this._readContextHash.bind(this)
1439
- });
1440
- /** @type {AsyncQueue<string, string, ContextTimestampAndHash>} */
1441
- this.contextTshQueue = new AsyncQueue({
1442
- name: "context hash and timestamp",
1443
- parallelism: 2,
1444
- processor: this._readContextTimestampAndHash.bind(this)
1445
- });
1446
- /** @type {AsyncQueue<string, string, string>} */
1447
- this.managedItemQueue = new AsyncQueue({
1448
- name: "managed item info",
1449
- parallelism: 10,
1450
- processor: this._getManagedItemInfo.bind(this)
1451
- });
1452
- /** @type {AsyncQueue<string, string, Set<string>>} */
1453
- this.managedItemDirectoryQueue = new AsyncQueue({
1454
- name: "managed item directory info",
1455
- parallelism: 10,
1456
- processor: this._getManagedItemDirectoryInfo.bind(this)
1457
- });
1458
- const _unmanagedPaths = [...unmanagedPaths];
1459
- /** @type {string[]} */
1460
- this.unmanagedPathsWithSlash = _unmanagedPaths
1461
- .filter((p) => typeof p === "string")
1462
- .map((p) => join(fs, p, "_").slice(0, -1));
1463
- /** @type {RegExp[]} */
1464
- this.unmanagedPathsRegExps = _unmanagedPaths.filter(
1465
- (p) => typeof p !== "string"
1466
- );
1467
-
1468
- this.managedPaths = [...managedPaths];
1469
- /** @type {string[]} */
1470
- this.managedPathsWithSlash = this.managedPaths
1471
- .filter((p) => typeof p === "string")
1472
- .map((p) => join(fs, p, "_").slice(0, -1));
1473
- /** @type {RegExp[]} */
1474
- this.managedPathsRegExps = this.managedPaths.filter(
1475
- (p) => typeof p !== "string"
1476
- );
1477
-
1478
- this.immutablePaths = [...immutablePaths];
1479
- /** @type {string[]} */
1480
- this.immutablePathsWithSlash = this.immutablePaths
1481
- .filter((p) => typeof p === "string")
1482
- .map((p) => join(fs, p, "_").slice(0, -1));
1483
- /** @type {RegExp[]} */
1484
- this.immutablePathsRegExps = this.immutablePaths.filter(
1485
- (p) => typeof p !== "string"
1486
- );
1487
-
1488
- /** @type {Map<string, number | null> | undefined} */
1489
- this._cachedDeprecatedFileTimestamps = undefined;
1490
- /** @type {Map<string, number | null> | undefined} */
1491
- this._cachedDeprecatedContextTimestamps = undefined;
1492
-
1493
- /** @type {boolean} */
1494
- this._warnAboutExperimentalEsmTracking = false;
1495
-
1496
- /** @type {number} */
1497
- this._statCreatedSnapshots = 0;
1498
- /** @type {number} */
1499
- this._statTestedSnapshotsCached = 0;
1500
- /** @type {number} */
1501
- this._statTestedSnapshotsNotCached = 0;
1502
- /** @type {number} */
1503
- this._statTestedChildrenCached = 0;
1504
- /** @type {number} */
1505
- this._statTestedChildrenNotCached = 0;
1506
- /** @type {number} */
1507
- this._statTestedEntries = 0;
1508
- }
1509
-
1510
- logStatistics() {
1511
- const logger = /** @type {Logger} */ (this.logger);
1512
- /**
1513
- * Processes the provided header.
1514
- * @param {string} header header
1515
- * @param {string | undefined} message message
1516
- */
1517
- const logWhenMessage = (header, message) => {
1518
- if (message) {
1519
- logger.log(`${header}: ${message}`);
1520
- }
1521
- };
1522
- logger.log(`${this._statCreatedSnapshots} new snapshots created`);
1523
- logger.log(
1524
- `${
1525
- this._statTestedSnapshotsNotCached &&
1526
- Math.round(
1527
- (this._statTestedSnapshotsNotCached * 100) /
1528
- (this._statTestedSnapshotsCached +
1529
- this._statTestedSnapshotsNotCached)
1530
- )
1531
- }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${
1532
- this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached
1533
- })`
1534
- );
1535
- logger.log(
1536
- `${
1537
- this._statTestedChildrenNotCached &&
1538
- Math.round(
1539
- (this._statTestedChildrenNotCached * 100) /
1540
- (this._statTestedChildrenCached + this._statTestedChildrenNotCached)
1541
- )
1542
- }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${
1543
- this._statTestedChildrenCached + this._statTestedChildrenNotCached
1544
- })`
1545
- );
1546
- logger.log(`${this._statTestedEntries} entries tested`);
1547
- logger.log(
1548
- `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations`
1549
- );
1550
- logWhenMessage(
1551
- "File timestamp snapshot optimization",
1552
- this._fileTimestampsOptimization.getStatisticMessage()
1553
- );
1554
- logWhenMessage(
1555
- "File hash snapshot optimization",
1556
- this._fileHashesOptimization.getStatisticMessage()
1557
- );
1558
- logWhenMessage(
1559
- "File timestamp hash combination snapshot optimization",
1560
- this._fileTshsOptimization.getStatisticMessage()
1561
- );
1562
- logger.log(
1563
- `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations`
1564
- );
1565
- logWhenMessage(
1566
- "Directory timestamp snapshot optimization",
1567
- this._contextTimestampsOptimization.getStatisticMessage()
1568
- );
1569
- logWhenMessage(
1570
- "Directory hash snapshot optimization",
1571
- this._contextHashesOptimization.getStatisticMessage()
1572
- );
1573
- logWhenMessage(
1574
- "Directory timestamp hash combination snapshot optimization",
1575
- this._contextTshsOptimization.getStatisticMessage()
1576
- );
1577
- logWhenMessage(
1578
- "Missing items snapshot optimization",
1579
- this._missingExistenceOptimization.getStatisticMessage()
1580
- );
1581
- logger.log(`Managed items info in cache: ${this._managedItems.size} items`);
1582
- logWhenMessage(
1583
- "Managed items snapshot optimization",
1584
- this._managedItemInfoOptimization.getStatisticMessage()
1585
- );
1586
- logWhenMessage(
1587
- "Managed files snapshot optimization",
1588
- this._managedFilesOptimization.getStatisticMessage()
1589
- );
1590
- logWhenMessage(
1591
- "Managed contexts snapshot optimization",
1592
- this._managedContextsOptimization.getStatisticMessage()
1593
- );
1594
- logWhenMessage(
1595
- "Managed missing snapshot optimization",
1596
- this._managedMissingOptimization.getStatisticMessage()
1597
- );
1598
- }
1599
-
1600
- /**
1601
- * Processes the provided path.
1602
- * @private
1603
- * @param {string} path path
1604
- * @param {string} reason reason
1605
- * @param {EXPECTED_ANY[]} args arguments
1606
- */
1607
- _log(path, reason, ...args) {
1608
- const key = path + reason;
1609
- const loggedPaths = /** @type {LoggedPaths} */ (this._loggedPaths);
1610
- if (loggedPaths.has(key)) return;
1611
- loggedPaths.add(key);
1612
- /** @type {Logger} */
1613
- (this.logger).debug(`${path} invalidated because ${reason}`, ...args);
1614
- if (--this._remainingLogs === 0) {
1615
- /** @type {Logger} */
1616
- (this.logger).debug(
1617
- "Logging limit has been reached and no further logging will be emitted by FileSystemInfo"
1618
- );
1619
- }
1620
- }
1621
-
1622
- clear() {
1623
- this._remainingLogs = this.logger ? 40 : 0;
1624
- if (this._loggedPaths !== undefined) this._loggedPaths.clear();
1625
-
1626
- this._snapshotCache = new WeakMap();
1627
- this._fileTimestampsOptimization.clear();
1628
- this._fileHashesOptimization.clear();
1629
- this._fileTshsOptimization.clear();
1630
- this._contextTimestampsOptimization.clear();
1631
- this._contextHashesOptimization.clear();
1632
- this._contextTshsOptimization.clear();
1633
- this._missingExistenceOptimization.clear();
1634
- this._managedItemInfoOptimization.clear();
1635
- this._managedFilesOptimization.clear();
1636
- this._managedContextsOptimization.clear();
1637
- this._managedMissingOptimization.clear();
1638
- this._fileTimestamps.clear();
1639
- this._fileHashes.clear();
1640
- this._fileTshs.clear();
1641
- this._contextTimestamps.clear();
1642
- this._contextHashes.clear();
1643
- this._contextTshs.clear();
1644
- this._managedItems.clear();
1645
- this._pathClassificationCache.clear();
1646
-
1647
- this._cachedDeprecatedFileTimestamps = undefined;
1648
- this._cachedDeprecatedContextTimestamps = undefined;
1649
-
1650
- this._statCreatedSnapshots = 0;
1651
- this._statTestedSnapshotsCached = 0;
1652
- this._statTestedSnapshotsNotCached = 0;
1653
- this._statTestedChildrenCached = 0;
1654
- this._statTestedChildrenNotCached = 0;
1655
- this._statTestedEntries = 0;
1656
- }
1657
-
1658
- /**
1659
- * Adds file timestamps.
1660
- * @param {ReadonlyMap<string, FileTimestamp>} map timestamps
1661
- * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it
1662
- * @returns {void}
1663
- */
1664
- addFileTimestamps(map, immutable) {
1665
- this._fileTimestamps.addAll(map, immutable);
1666
- this._cachedDeprecatedFileTimestamps = undefined;
1667
- }
1668
-
1669
- /**
1670
- * Adds context timestamps.
1671
- * @param {ReadonlyMap<string, ContextTimestamp>} map timestamps
1672
- * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it
1673
- * @returns {void}
1674
- */
1675
- addContextTimestamps(map, immutable) {
1676
- this._contextTimestamps.addAll(map, immutable);
1677
- this._cachedDeprecatedContextTimestamps = undefined;
1678
- }
1679
-
1680
- /**
1681
- * Gets file timestamp.
1682
- * @param {string} path file path
1683
- * @param {(err?: WebpackError | null, fileTimestamp?: FileSystemInfoEntry | "ignore" | null) => void} callback callback function
1684
- * @returns {void}
1685
- */
1686
- getFileTimestamp(path, callback) {
1687
- const cache = this._fileTimestamps.get(path);
1688
- if (cache !== undefined && !isExistenceOnly(cache)) {
1689
- return callback(
1690
- null,
1691
- /** @type {FileSystemInfoEntry | "ignore" | null} */ (cache)
1692
- );
1693
- }
1694
- this.fileTimestampQueue.add(path, callback);
1695
- }
1696
-
1697
- /**
1698
- * Gets context timestamp.
1699
- * @param {string} path context path
1700
- * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback function
1701
- * @returns {void}
1702
- */
1703
- getContextTimestamp(path, callback) {
1704
- const cache = this._contextTimestamps.get(path);
1705
- if (cache !== undefined && !isExistenceOnly(cache)) {
1706
- if (cache === "ignore") return callback(null, "ignore");
1707
- const fullEntry =
1708
- /** @type {ContextFileSystemInfoEntry | null} */
1709
- (cache);
1710
- const resolved = getResolvedTimestamp(fullEntry);
1711
- if (resolved !== undefined) return callback(null, resolved);
1712
- return this._resolveContextTimestamp(
1713
- /** @type {ContextFileSystemInfoEntry} */
1714
- (fullEntry),
1715
- callback
1716
- );
1717
- }
1718
- this._readFreshContextTimestamp(path, callback);
1719
- }
1720
-
1721
- /**
1722
- * Reads a context timestamp directly from disk, bypassing any cached
1723
- * entry. Used by `getContextTimestamp` and the snapshot validity
1724
- * checks when the cached entry is missing or is an `ExistenceOnlyTimeEntry`
1725
- * (`{}`) supplied by watchpack — both cases require a fresh read to
1726
- * obtain the `timestampHash`.
1727
- * @private
1728
- * @param {string} path context path
1729
- * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback function
1730
- * @returns {void}
1731
- */
1732
- _readFreshContextTimestamp(path, callback) {
1733
- this.contextTimestampQueue.add(path, (err, _entry) => {
1734
- if (err) return callback(err);
1735
- const entry = /** @type {ContextFileSystemInfoEntry | null} */ (_entry);
1736
- if (entry === null) return callback(null, null);
1737
- const resolved = getResolvedTimestamp(entry);
1738
- if (resolved !== undefined) return callback(null, resolved);
1739
- this._resolveContextTimestamp(entry, callback);
1740
- });
1741
- }
1742
-
1743
- /**
1744
- * Get unresolved context timestamp. Existence-only cache entries (`{}`)
1745
- * are bypassed so the callback always receives a complete entry, "ignore"
1746
- * or null.
1747
- * @private
1748
- * @param {string} path context path
1749
- * @param {(err?: WebpackError | null, contextTimestamp?: ContextFileSystemInfoEntry | "ignore" | null) => void} callback callback function
1750
- * @returns {void}
1751
- */
1752
- _getUnresolvedContextTimestamp(path, callback) {
1753
- const cache = this._contextTimestamps.get(path);
1754
- if (
1755
- cache !== undefined &&
1756
- !isExistenceOnly(cache) &&
1757
- !contextCacheEntryLacksTimestampHash(
1758
- /** @type {ContextFileSystemInfoEntry | null | "ignore"} */ (cache)
1759
- )
1760
- ) {
1761
- return callback(
1762
- null,
1763
- /** @type {ContextFileSystemInfoEntry | "ignore" | null} */ (cache)
1764
- );
1765
- }
1766
- this.contextTimestampQueue.add(path, callback);
1767
- }
1768
-
1769
- /**
1770
- * Returns file hash.
1771
- * @param {string} path file path
1772
- * @param {(err?: WebpackError | null, hash?: string | null) => void} callback callback function
1773
- * @returns {void}
1774
- */
1775
- getFileHash(path, callback) {
1776
- const cache = this._fileHashes.get(path);
1777
- if (cache !== undefined) return callback(null, cache);
1778
- this.fileHashQueue.add(path, callback);
1779
- }
1780
-
1781
- /**
1782
- * Returns context hash.
1783
- * @param {string} path context path
1784
- * @param {(err?: WebpackError | null, contextHash?: string) => void} callback callback function
1785
- * @returns {void}
1786
- */
1787
- getContextHash(path, callback) {
1788
- const cache = this._contextHashes.get(path);
1789
- if (cache !== undefined) {
1790
- const resolved = getResolvedHash(cache);
1791
- if (resolved !== undefined) {
1792
- return callback(null, /** @type {string} */ (resolved));
1793
- }
1794
- return this._resolveContextHash(cache, callback);
1795
- }
1796
- this.contextHashQueue.add(path, (err, _entry) => {
1797
- if (err) return callback(err);
1798
- const entry = /** @type {ContextHash} */ (_entry);
1799
- const resolved = getResolvedHash(entry);
1800
- if (resolved !== undefined) {
1801
- return callback(null, /** @type {string} */ (resolved));
1802
- }
1803
- this._resolveContextHash(entry, callback);
1804
- });
1805
- }
1806
-
1807
- /**
1808
- * Get unresolved context hash.
1809
- * @private
1810
- * @param {string} path context path
1811
- * @param {(err?: WebpackError | null, contextHash?: ContextHash | null) => void} callback callback function
1812
- * @returns {void}
1813
- */
1814
- _getUnresolvedContextHash(path, callback) {
1815
- const cache = this._contextHashes.get(path);
1816
- if (cache !== undefined) return callback(null, cache);
1817
- this.contextHashQueue.add(path, callback);
1818
- }
1819
-
1820
- /**
1821
- * Returns context tsh.
1822
- * @param {string} path context path
1823
- * @param {(err?: WebpackError | null, resolvedContextTimestampAndHash?: ResolvedContextTimestampAndHash | null) => void} callback callback function
1824
- * @returns {void}
1825
- */
1826
- getContextTsh(path, callback) {
1827
- const cache = this._contextTshs.get(path);
1828
- if (cache !== undefined) {
1829
- const resolved = getResolvedTimestamp(cache);
1830
- if (resolved !== undefined) return callback(null, resolved);
1831
- return this._resolveContextTsh(cache, callback);
1832
- }
1833
- this.contextTshQueue.add(path, (err, _entry) => {
1834
- if (err) return callback(err);
1835
- const entry = /** @type {ContextTimestampAndHash} */ (_entry);
1836
- const resolved = getResolvedTimestamp(entry);
1837
- if (resolved !== undefined) return callback(null, resolved);
1838
- this._resolveContextTsh(entry, callback);
1839
- });
1840
- }
1841
-
1842
- /**
1843
- * Get unresolved context tsh.
1844
- * @private
1845
- * @param {string} path context path
1846
- * @param {(err?: WebpackError | null, contextTimestampAndHash?: ContextTimestampAndHash | null) => void} callback callback function
1847
- * @returns {void}
1848
- */
1849
- _getUnresolvedContextTsh(path, callback) {
1850
- const cache = this._contextTshs.get(path);
1851
- if (cache !== undefined) return callback(null, cache);
1852
- this.contextTshQueue.add(path, callback);
1853
- }
1854
-
1855
- _createBuildDependenciesResolvers() {
1856
- const resolveContext = createResolver({
1857
- resolveToContext: true,
1858
- exportsFields: [],
1859
- fileSystem: this.fs
1860
- });
1861
- const resolveCjs = createResolver({
1862
- extensions: [".js", ".json", ".node"],
1863
- conditionNames: ["require", "module-sync", "node"],
1864
- exportsFields: ["exports"],
1865
- fileSystem: this.fs
1866
- });
1867
- const resolveCjsAsChild = createResolver({
1868
- extensions: [".js", ".json", ".node"],
1869
- conditionNames: ["require", "module-sync", "node"],
1870
- exportsFields: [],
1871
- fileSystem: this.fs
1872
- });
1873
- const resolveEsm = createResolver({
1874
- extensions: [".js", ".json", ".node"],
1875
- fullySpecified: true,
1876
- conditionNames: ["import", "module-sync", "node"],
1877
- exportsFields: ["exports"],
1878
- fileSystem: this.fs
1879
- });
1880
- return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild };
1881
- }
1882
-
1883
- /**
1884
- * Resolves build dependencies.
1885
- * @param {string} context context directory
1886
- * @param {Iterable<string>} deps dependencies
1887
- * @param {Iterable<string> | undefined} optionalDeps optional dependencies that may be missing
1888
- * @param {(err?: Error | null, resolveBuildDependenciesResult?: ResolveBuildDependenciesResult) => void} callback callback function
1889
- * @returns {void}
1890
- */
1891
- resolveBuildDependencies(context, deps, optionalDeps, callback) {
1892
- /** @type {Set<string>} */
1893
- const optional = new Set(optionalDeps);
1894
- const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } =
1895
- this._createBuildDependenciesResolvers();
1896
-
1897
- /** @type {Files} */
1898
- const files = new Set();
1899
- /** @type {Symlinks} */
1900
- const fileSymlinks = new Set();
1901
- /** @type {Directories} */
1902
- const directories = new Set();
1903
- /** @type {Symlinks} */
1904
- const directorySymlinks = new Set();
1905
- /** @type {Missing} */
1906
- const missing = new Set();
1907
- /** @type {ResolveDependencies["files"]} */
1908
- const resolveFiles = new Set();
1909
- /** @type {ResolveDependencies["directories"]} */
1910
- const resolveDirectories = new Set();
1911
- /** @type {ResolveDependencies["missing"]} */
1912
- const resolveMissing = new Set();
1913
- /** @type {ResolveResults} */
1914
- const resolveResults = new Map();
1915
- /** @type {Set<string>} */
1916
- const invalidResolveResults = new Set();
1917
- const resolverContext = {
1918
- fileDependencies: resolveFiles,
1919
- contextDependencies: resolveDirectories,
1920
- missingDependencies: resolveMissing
1921
- };
1922
- /**
1923
- * Expected to string.
1924
- * @param {undefined | boolean | string} expected expected result
1925
- * @returns {string} expected result
1926
- */
1927
- const expectedToString = (expected) =>
1928
- expected ? ` (expected ${expected})` : "";
1929
- /** @typedef {{ type: JobType, context: string | undefined, path: string, issuer: Job | undefined, expected: undefined | boolean | string }} Job */
1930
-
1931
- /**
1932
- * Returns result.
1933
- * @param {Job} job job
1934
- * @returns {string} result
1935
- */
1936
- const jobToString = (job) => {
1937
- switch (job.type) {
1938
- case RBDT_RESOLVE_FILE:
1939
- return `resolve file ${job.path}${expectedToString(job.expected)}`;
1940
- case RBDT_RESOLVE_DIRECTORY:
1941
- return `resolve directory ${job.path}`;
1942
- case RBDT_RESOLVE_CJS_FILE:
1943
- return `resolve commonjs file ${job.path}${expectedToString(
1944
- job.expected
1945
- )}`;
1946
- case RBDT_RESOLVE_ESM_FILE:
1947
- return `resolve esm file ${job.path}${expectedToString(
1948
- job.expected
1949
- )}`;
1950
- case RBDT_DIRECTORY:
1951
- return `directory ${job.path}`;
1952
- case RBDT_FILE:
1953
- return `file ${job.path}`;
1954
- case RBDT_DIRECTORY_DEPENDENCIES:
1955
- return `directory dependencies ${job.path}`;
1956
- case RBDT_FILE_DEPENDENCIES:
1957
- return `file dependencies ${job.path}`;
1958
- }
1959
- return `unknown ${job.type} ${job.path}`;
1960
- };
1961
- /**
1962
- * Returns string value.
1963
- * @param {Job} job job
1964
- * @returns {string} string value
1965
- */
1966
- const pathToString = (job) => {
1967
- let result = ` at ${jobToString(job)}`;
1968
- /** @type {Job | undefined} */
1969
- (job) = job.issuer;
1970
- while (job !== undefined) {
1971
- result += `\n at ${jobToString(job)}`;
1972
- job = /** @type {Job} */ (job.issuer);
1973
- }
1974
- return result;
1975
- };
1976
- const logger = /** @type {Logger} */ (this.logger);
1977
- processAsyncTree(
1978
- Array.from(
1979
- deps,
1980
- (dep) =>
1981
- /** @type {Job} */ ({
1982
- type: RBDT_RESOLVE_INITIAL,
1983
- context,
1984
- path: dep,
1985
- expected: optional.has(dep) ? false : undefined,
1986
- issuer: undefined
1987
- })
1988
- ),
1989
- 20,
1990
- (job, push, callback) => {
1991
- const { type, context, path, expected } = job;
1992
- /**
1993
- * Resolves directory.
1994
- * @param {string} path path
1995
- * @returns {void}
1996
- */
1997
- const resolveDirectory = (path) => {
1998
- const key = `d\n${context}\n${path}`;
1999
- if (resolveResults.has(key)) {
2000
- return callback();
2001
- }
2002
- resolveResults.set(key, undefined);
2003
- resolveContext(
2004
- /** @type {string} */ (context),
2005
- path,
2006
- resolverContext,
2007
- (err, _, result) => {
2008
- if (err) {
2009
- if (expected === false) {
2010
- resolveResults.set(key, false);
2011
- resolveMissing.add(path);
2012
- return callback();
2013
- }
2014
- invalidResolveResults.add(key);
2015
- err.message += `\nwhile resolving '${path}' in ${context} to a directory`;
2016
- return callback(err);
2017
- }
2018
- const resultPath = /** @type {ResolveRequest} */ (result).path;
2019
- resolveResults.set(key, resultPath);
2020
- push({
2021
- type: RBDT_DIRECTORY,
2022
- context: undefined,
2023
- path: /** @type {string} */ (resultPath),
2024
- expected: undefined,
2025
- issuer: job
2026
- });
2027
- callback();
2028
- }
2029
- );
2030
- };
2031
- /**
2032
- * Processes the provided path.
2033
- * @param {string} path path
2034
- * @param {("f" | "c" | "e")=} symbol symbol
2035
- * @param {(ResolveFunctionAsync)=} resolve resolve fn
2036
- * @returns {void}
2037
- */
2038
- const resolveFile = (path, symbol, resolve) => {
2039
- const key = `${symbol}\n${context}\n${path}`;
2040
- if (resolveResults.has(key)) {
2041
- return callback();
2042
- }
2043
- resolveResults.set(key, undefined);
2044
- /** @type {ResolveFunctionAsync} */
2045
- (resolve)(
2046
- /** @type {string} */ (context),
2047
- path,
2048
- resolverContext,
2049
- (err, _, result) => {
2050
- if (typeof expected === "string") {
2051
- if (!err && result && result.path === expected) {
2052
- resolveResults.set(key, result.path);
2053
- } else {
2054
- invalidResolveResults.add(key);
2055
- logger.warn(
2056
- `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${
2057
- err || (result && result.path)
2058
- }' instead. Resolving dependencies are ignored for this path.\n${pathToString(
2059
- job
2060
- )}`
2061
- );
2062
- }
2063
- } else {
2064
- if (err) {
2065
- if (expected === false) {
2066
- resolveResults.set(key, false);
2067
- resolveMissing.add(path);
2068
- return callback();
2069
- }
2070
- invalidResolveResults.add(key);
2071
- err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString(
2072
- job
2073
- )}`;
2074
- return callback(err);
2075
- }
2076
- const resultPath = /** @type {ResolveRequest} */ (result).path;
2077
- resolveResults.set(key, resultPath);
2078
- push({
2079
- type: RBDT_FILE,
2080
- context: undefined,
2081
- path: /** @type {string} */ (resultPath),
2082
- expected: undefined,
2083
- issuer: job
2084
- });
2085
- }
2086
- callback();
2087
- }
2088
- );
2089
- };
2090
- const resolvedType =
2091
- type === RBDT_RESOLVE_INITIAL
2092
- ? /[\\/]$/.test(path)
2093
- ? RBDT_RESOLVE_DIRECTORY
2094
- : RBDT_RESOLVE_FILE
2095
- : type;
2096
- switch (resolvedType) {
2097
- case RBDT_RESOLVE_FILE: {
2098
- resolveFile(
2099
- path,
2100
- "f",
2101
- /\.mjs$/.test(path) ? resolveEsm : resolveCjs
2102
- );
2103
- break;
2104
- }
2105
- case RBDT_RESOLVE_DIRECTORY: {
2106
- resolveDirectory(
2107
- type === RBDT_RESOLVE_INITIAL ? path.slice(0, -1) : path
2108
- );
2109
- break;
2110
- }
2111
- case RBDT_RESOLVE_CJS_FILE: {
2112
- resolveFile(path, "f", resolveCjs);
2113
- break;
2114
- }
2115
- case RBDT_RESOLVE_CJS_FILE_AS_CHILD: {
2116
- resolveFile(path, "c", resolveCjsAsChild);
2117
- break;
2118
- }
2119
- case RBDT_RESOLVE_ESM_FILE: {
2120
- resolveFile(path, "e", resolveEsm);
2121
- break;
2122
- }
2123
- case RBDT_FILE: {
2124
- if (files.has(path)) {
2125
- callback();
2126
- break;
2127
- }
2128
- files.add(path);
2129
- /** @type {NonNullable<InputFileSystem["realpath"]>} */
2130
- (this.fs.realpath)(path, (err, _realPath) => {
2131
- if (err) return callback(err);
2132
- const realPath = /** @type {string} */ (_realPath);
2133
- if (realPath !== path) {
2134
- fileSymlinks.add(path);
2135
- resolveFiles.add(path);
2136
- if (files.has(realPath)) return callback();
2137
- files.add(realPath);
2138
- }
2139
- push({
2140
- type: RBDT_FILE_DEPENDENCIES,
2141
- context: undefined,
2142
- path: realPath,
2143
- expected: undefined,
2144
- issuer: job
2145
- });
2146
- callback();
2147
- });
2148
- break;
2149
- }
2150
- case RBDT_DIRECTORY: {
2151
- if (directories.has(path)) {
2152
- callback();
2153
- break;
2154
- }
2155
- directories.add(path);
2156
- /** @type {NonNullable<InputFileSystem["realpath"]>} */
2157
- (this.fs.realpath)(path, (err, _realPath) => {
2158
- if (err) return callback(err);
2159
- const realPath = /** @type {string} */ (_realPath);
2160
- if (realPath !== path) {
2161
- directorySymlinks.add(path);
2162
- resolveFiles.add(path);
2163
- if (directories.has(realPath)) return callback();
2164
- directories.add(realPath);
2165
- }
2166
- push({
2167
- type: RBDT_DIRECTORY_DEPENDENCIES,
2168
- context: undefined,
2169
- path: realPath,
2170
- expected: undefined,
2171
- issuer: job
2172
- });
2173
- callback();
2174
- });
2175
- break;
2176
- }
2177
- case RBDT_FILE_DEPENDENCIES: {
2178
- // Check for known files without dependencies
2179
- if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) {
2180
- process.nextTick(callback);
2181
- break;
2182
- }
2183
- // Check commonjs cache for the module
2184
- /** @type {NodeModule | undefined} */
2185
- const module = require.cache[path];
2186
- if (
2187
- module &&
2188
- Array.isArray(module.children) &&
2189
- // https://github.com/nodejs/node/issues/59868
2190
- // Force use `es-module-lexer` for mjs
2191
- !/\.mjs$/.test(path)
2192
- ) {
2193
- children: for (const child of module.children) {
2194
- const childPath = child.filename;
2195
- if (childPath) {
2196
- push({
2197
- type: RBDT_FILE,
2198
- context: undefined,
2199
- path: childPath,
2200
- expected: undefined,
2201
- issuer: job
2202
- });
2203
- const context = dirname(this.fs, path);
2204
- for (const modulePath of module.paths) {
2205
- if (childPath.startsWith(modulePath)) {
2206
- const subPath = childPath.slice(modulePath.length + 1);
2207
- const packageMatch = /^@[^\\/]+[\\/][^\\/]+/.exec(
2208
- subPath
2209
- );
2210
- if (packageMatch) {
2211
- push({
2212
- type: RBDT_FILE,
2213
- context: undefined,
2214
- path: `${
2215
- modulePath +
2216
- childPath[modulePath.length] +
2217
- packageMatch[0] +
2218
- childPath[modulePath.length]
2219
- }package.json`,
2220
- expected: false,
2221
- issuer: job
2222
- });
2223
- }
2224
- let request = subPath.replace(/\\/g, "/");
2225
- if (request.endsWith(".js")) {
2226
- request = request.slice(0, -3);
2227
- }
2228
- push({
2229
- type: RBDT_RESOLVE_CJS_FILE_AS_CHILD,
2230
- context,
2231
- path: request,
2232
- expected: child.filename,
2233
- issuer: job
2234
- });
2235
- continue children;
2236
- }
2237
- }
2238
- let request = relative(this.fs, context, childPath);
2239
- if (request.endsWith(".js")) request = request.slice(0, -3);
2240
- request = request.replace(/\\/g, "/");
2241
- if (!request.startsWith("../") && !isAbsolute(request)) {
2242
- request = `./${request}`;
2243
- }
2244
- push({
2245
- type: RBDT_RESOLVE_CJS_FILE,
2246
- context,
2247
- path: request,
2248
- expected: child.filename,
2249
- issuer: job
2250
- });
2251
- }
2252
- }
2253
- // On Bun the children array is empty (unpopulated), so recover the
2254
- // static require() specifiers by parsing the source; Node/Deno don't.
2255
- /* istanbul ignore next */
2256
- if (IS_BUN && module.children.length === 0) {
2257
- this.fs.readFile(path, (err, content) => {
2258
- if (err) return callback(err);
2259
- try {
2260
- const context = dirname(this.fs, path);
2261
- const source = /** @type {Buffer} */ (content).toString();
2262
- for (const dependency of collectCjsRequireSpecifiers(
2263
- source
2264
- )) {
2265
- if (dependency.startsWith("node:")) continue;
2266
- if (builtinModules.has(dependency)) continue;
2267
- push({
2268
- type: RBDT_RESOLVE_CJS_FILE,
2269
- context,
2270
- path: dependency,
2271
- // Best effort: tolerate specifiers that don't resolve.
2272
- expected: false,
2273
- issuer: job
2274
- });
2275
- }
2276
- } catch (_err) {
2277
- // Source we can't parse as CommonJS — ignore its dependencies.
2278
- }
2279
- process.nextTick(callback);
2280
- });
2281
- break;
2282
- }
2283
- } else if (supportsEsm && /\.m?js$/.test(path)) {
2284
- if (!this._warnAboutExperimentalEsmTracking) {
2285
- logger.log(
2286
- "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" +
2287
- "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" +
2288
- "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking."
2289
- );
2290
- this._warnAboutExperimentalEsmTracking = true;
2291
- }
2292
-
2293
- const lexer = getEsModuleLexer();
2294
-
2295
- lexer.init.then(() => {
2296
- this.fs.readFile(path, (err, content) => {
2297
- if (err) return callback(err);
2298
- try {
2299
- const context = dirname(this.fs, path);
2300
- const source = /** @type {Buffer} */ (content).toString();
2301
- const [imports] = lexer.parse(source);
2302
- /** @type {Set<string>} */
2303
- const added = new Set();
2304
- for (const imp of imports) {
2305
- try {
2306
- // import.meta
2307
- if (imp.d === -2) {
2308
- continue;
2309
- }
2310
-
2311
- /** @type {string | null} */
2312
- const dependency =
2313
- imp.n ||
2314
- parseString(source.slice(imp.s, imp.e).trim());
2315
-
2316
- if (!dependency) {
2317
- continue;
2318
- }
2319
-
2320
- // We should not track Node.js build dependencies
2321
- if (dependency.startsWith("node:")) continue;
2322
- if (builtinModules.has(dependency)) continue;
2323
- // Avoid extra jobs for identical imports
2324
- if (added.has(dependency)) continue;
2325
-
2326
- push({
2327
- type: RBDT_RESOLVE_ESM_FILE,
2328
- context,
2329
- path: dependency,
2330
- expected: imp.d > -1 ? false : undefined,
2331
- issuer: job
2332
- });
2333
- added.add(dependency);
2334
- } catch (err1) {
2335
- logger.warn(
2336
- `Parsing of ${path} for build dependencies failed at 'import(${source.slice(
2337
- imp.s,
2338
- imp.e
2339
- )})'.\n` +
2340
- "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation."
2341
- );
2342
- logger.debug(pathToString(job));
2343
- logger.debug(/** @type {Error} */ (err1).stack);
2344
- }
2345
- }
2346
- } catch (err2) {
2347
- logger.warn(
2348
- `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..`
2349
- );
2350
- logger.debug(pathToString(job));
2351
- logger.debug(/** @type {Error} */ (err2).stack);
2352
- }
2353
- process.nextTick(callback);
2354
- });
2355
- }, callback);
2356
- break;
2357
- } else {
2358
- logger.log(
2359
- `Assuming ${path} has no dependencies as we were unable to assign it to any module system.`
2360
- );
2361
- logger.debug(pathToString(job));
2362
- }
2363
- process.nextTick(callback);
2364
- break;
2365
- }
2366
- case RBDT_DIRECTORY_DEPENDENCIES: {
2367
- const match =
2368
- /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path);
2369
- const packagePath = match ? match[1] : path;
2370
- const packageJson = join(this.fs, packagePath, "package.json");
2371
- this.fs.readFile(packageJson, (err, content) => {
2372
- if (err) {
2373
- if (err.code === "ENOENT") {
2374
- resolveMissing.add(packageJson);
2375
- const parent = dirname(this.fs, packagePath);
2376
- if (parent !== packagePath) {
2377
- push({
2378
- type: RBDT_DIRECTORY_DEPENDENCIES,
2379
- context: undefined,
2380
- path: parent,
2381
- expected: undefined,
2382
- issuer: job
2383
- });
2384
- }
2385
- callback();
2386
- return;
2387
- }
2388
- return callback(err);
2389
- }
2390
- resolveFiles.add(packageJson);
2391
- /** @type {JsonObject} */
2392
- let packageData;
2393
- try {
2394
- packageData = JSON.parse(
2395
- /** @type {Buffer} */
2396
- (content).toString("utf8")
2397
- );
2398
- } catch (parseErr) {
2399
- return callback(/** @type {Error} */ (parseErr));
2400
- }
2401
- const depsObject = packageData.dependencies;
2402
- const optionalDepsObject = packageData.optionalDependencies;
2403
- /** @type {Set<string>} */
2404
- const allDeps = new Set();
2405
- /** @type {Set<string>} */
2406
- const optionalDeps = new Set();
2407
- if (typeof depsObject === "object" && depsObject) {
2408
- for (const dep of Object.keys(depsObject)) {
2409
- allDeps.add(dep);
2410
- }
2411
- }
2412
- if (
2413
- typeof optionalDepsObject === "object" &&
2414
- optionalDepsObject
2415
- ) {
2416
- for (const dep of Object.keys(optionalDepsObject)) {
2417
- allDeps.add(dep);
2418
- optionalDeps.add(dep);
2419
- }
2420
- }
2421
- for (const dep of allDeps) {
2422
- push({
2423
- type: RBDT_RESOLVE_DIRECTORY,
2424
- context: packagePath,
2425
- path: dep,
2426
- expected: !optionalDeps.has(dep),
2427
- issuer: job
2428
- });
2429
- }
2430
- callback();
2431
- });
2432
- break;
2433
- }
2434
- }
2435
- },
2436
- (err) => {
2437
- if (err) return callback(err);
2438
- for (const l of fileSymlinks) files.delete(l);
2439
- for (const l of directorySymlinks) directories.delete(l);
2440
- for (const k of invalidResolveResults) resolveResults.delete(k);
2441
- callback(null, {
2442
- files,
2443
- directories,
2444
- missing,
2445
- resolveResults,
2446
- resolveDependencies: {
2447
- files: resolveFiles,
2448
- directories: resolveDirectories,
2449
- missing: resolveMissing
2450
- }
2451
- });
2452
- }
2453
- );
2454
- }
2455
-
2456
- /**
2457
- * Checks resolve results valid.
2458
- * @param {ResolveResults} resolveResults results from resolving
2459
- * @param {(err?: Error | null, result?: boolean) => void} callback callback with true when resolveResults resolve the same way
2460
- * @returns {void}
2461
- */
2462
- checkResolveResultsValid(resolveResults, callback) {
2463
- const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } =
2464
- this._createBuildDependenciesResolvers();
2465
- asyncLib.eachLimit(
2466
- resolveResults,
2467
- 20,
2468
- ([key, expectedResult], callback) => {
2469
- const [type, context, path] = key.split("\n");
2470
- switch (type) {
2471
- case "d":
2472
- resolveContext(context, path, {}, (err, _, result) => {
2473
- if (expectedResult === false) {
2474
- return callback(err ? undefined : INVALID);
2475
- }
2476
- if (err) return callback(err);
2477
- const resultPath = /** @type {ResolveRequest} */ (result).path;
2478
- if (resultPath !== expectedResult) return callback(INVALID);
2479
- callback();
2480
- });
2481
- break;
2482
- case "f":
2483
- resolveCjs(context, path, {}, (err, _, result) => {
2484
- if (expectedResult === false) {
2485
- return callback(err ? undefined : INVALID);
2486
- }
2487
- if (err) return callback(err);
2488
- const resultPath = /** @type {ResolveRequest} */ (result).path;
2489
- if (resultPath !== expectedResult) return callback(INVALID);
2490
- callback();
2491
- });
2492
- break;
2493
- case "c":
2494
- resolveCjsAsChild(context, path, {}, (err, _, result) => {
2495
- if (expectedResult === false) {
2496
- return callback(err ? undefined : INVALID);
2497
- }
2498
- if (err) return callback(err);
2499
- const resultPath = /** @type {ResolveRequest} */ (result).path;
2500
- if (resultPath !== expectedResult) return callback(INVALID);
2501
- callback();
2502
- });
2503
- break;
2504
- case "e":
2505
- resolveEsm(context, path, {}, (err, _, result) => {
2506
- if (expectedResult === false) {
2507
- return callback(err ? undefined : INVALID);
2508
- }
2509
- if (err) return callback(err);
2510
- const resultPath = /** @type {ResolveRequest} */ (result).path;
2511
- if (resultPath !== expectedResult) return callback(INVALID);
2512
- callback();
2513
- });
2514
- break;
2515
- default:
2516
- callback(new Error("Unexpected type in resolve result key"));
2517
- break;
2518
- }
2519
- },
2520
- /**
2521
- * Processes the provided err.
2522
- * @param {(Error | typeof INVALID | null)=} err error or invalid flag
2523
- * @returns {void}
2524
- */
2525
- (err) => {
2526
- if (err === INVALID) {
2527
- return callback(null, false);
2528
- }
2529
- if (err) {
2530
- return callback(err);
2531
- }
2532
- return callback(null, true);
2533
- }
2534
- );
2535
- }
2536
-
2537
- /**
2538
- * Creates a snapshot.
2539
- * @param {number | null | undefined} startTime when processing the files has started
2540
- * @param {Iterable<string> | null | undefined} files all files
2541
- * @param {Iterable<string> | null | undefined} directories all directories
2542
- * @param {Iterable<string> | null | undefined} missing all missing files or directories
2543
- * @param {SnapshotOptions | null | undefined} options options object (for future extensions)
2544
- * @param {(err: WebpackError | null, snapshot: Snapshot | null) => void} callback callback function
2545
- * @returns {void}
2546
- */
2547
- createSnapshot(startTime, files, directories, missing, options, callback) {
2548
- // collections are allocated lazily to avoid per-snapshot garbage for unused modes
2549
- /** @type {FileTimestamps | undefined} */
2550
- let fileTimestamps;
2551
- /** @type {FileHashes | undefined} */
2552
- let fileHashes;
2553
- /** @type {FileTshs | undefined} */
2554
- let fileTshs;
2555
- /** @type {ContextTimestamps | undefined} */
2556
- let contextTimestamps;
2557
- /** @type {ContextHashes | undefined} */
2558
- let contextHashes;
2559
- /** @type {ContextTshs | undefined} */
2560
- let contextTshs;
2561
- /** @type {MissingExistence | undefined} */
2562
- let missingExistence;
2563
- /** @type {ManagedItemInfo | undefined} */
2564
- let managedItemInfo;
2565
- /** @type {ManagedFiles} */
2566
- const managedFiles = new Set();
2567
- /** @type {ManagedContexts} */
2568
- const managedContexts = new Set();
2569
- /** @type {ManagedMissing} */
2570
- const managedMissing = new Set();
2571
-
2572
- const snapshot = new Snapshot();
2573
- if (startTime) snapshot.setStartTime(startTime);
2574
-
2575
- /** @type {Set<string>} */
2576
- const managedItems = new Set();
2577
-
2578
- /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */
2579
- const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1;
2580
-
2581
- let jobs = 1;
2582
- const jobDone = () => {
2583
- if (--jobs === 0) {
2584
- if (fileTimestamps !== undefined && fileTimestamps.size !== 0) {
2585
- snapshot.setFileTimestamps(fileTimestamps);
2586
- }
2587
- if (fileHashes !== undefined && fileHashes.size !== 0) {
2588
- snapshot.setFileHashes(fileHashes);
2589
- }
2590
- if (fileTshs !== undefined && fileTshs.size !== 0) {
2591
- snapshot.setFileTshs(fileTshs);
2592
- }
2593
- if (contextTimestamps !== undefined && contextTimestamps.size !== 0) {
2594
- snapshot.setContextTimestamps(contextTimestamps);
2595
- }
2596
- if (contextHashes !== undefined && contextHashes.size !== 0) {
2597
- snapshot.setContextHashes(contextHashes);
2598
- }
2599
- if (contextTshs !== undefined && contextTshs.size !== 0) {
2600
- snapshot.setContextTshs(contextTshs);
2601
- }
2602
- if (missingExistence !== undefined && missingExistence.size !== 0) {
2603
- snapshot.setMissingExistence(missingExistence);
2604
- }
2605
- if (managedItemInfo !== undefined && managedItemInfo.size !== 0) {
2606
- snapshot.setManagedItemInfo(managedItemInfo);
2607
- }
2608
- this._managedFilesOptimization.optimize(snapshot, managedFiles);
2609
- if (managedFiles.size !== 0) {
2610
- snapshot.setManagedFiles(managedFiles);
2611
- }
2612
- this._managedContextsOptimization.optimize(snapshot, managedContexts);
2613
- if (managedContexts.size !== 0) {
2614
- snapshot.setManagedContexts(managedContexts);
2615
- }
2616
- this._managedMissingOptimization.optimize(snapshot, managedMissing);
2617
- if (managedMissing.size !== 0) {
2618
- snapshot.setManagedMissing(managedMissing);
2619
- }
2620
- this._snapshotCache.set(snapshot, true);
2621
- this._statCreatedSnapshots++;
2622
-
2623
- callback(null, snapshot);
2624
- }
2625
- };
2626
- const jobError = () => {
2627
- if (jobs > 0) {
2628
- // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
2629
- jobs = -100000000;
2630
- callback(null, null);
2631
- }
2632
- };
2633
- const classificationCache = this._pathClassificationCache;
2634
- /**
2635
- * Checks true when managed.
2636
- * @param {string} path path
2637
- * @param {ManagedFiles} managedSet managed set
2638
- * @returns {boolean} true when managed
2639
- */
2640
- const checkManaged = (path, managedSet) => {
2641
- // classification is a pure function of the path, so it's shared across snapshots
2642
- const cached = classificationCache.get(path);
2643
- if (cached !== undefined) {
2644
- if (cached === 0) return false;
2645
- if (cached !== 1) managedItems.add(cached);
2646
- managedSet.add(path);
2647
- return true;
2648
- }
2649
- for (const unmanagedPath of this.unmanagedPathsRegExps) {
2650
- if (unmanagedPath.test(path)) {
2651
- classificationCache.set(path, 0);
2652
- return false;
2653
- }
2654
- }
2655
- for (const unmanagedPath of this.unmanagedPathsWithSlash) {
2656
- if (path.startsWith(unmanagedPath)) {
2657
- classificationCache.set(path, 0);
2658
- return false;
2659
- }
2660
- }
2661
- for (const immutablePath of this.immutablePathsRegExps) {
2662
- if (immutablePath.test(path)) {
2663
- classificationCache.set(path, 1);
2664
- managedSet.add(path);
2665
- return true;
2666
- }
2667
- }
2668
- for (const immutablePath of this.immutablePathsWithSlash) {
2669
- if (path.startsWith(immutablePath)) {
2670
- classificationCache.set(path, 1);
2671
- managedSet.add(path);
2672
- return true;
2673
- }
2674
- }
2675
- for (const managedPath of this.managedPathsRegExps) {
2676
- const match = managedPath.exec(path);
2677
- if (match) {
2678
- const managedItem = getManagedItem(
2679
- getManagedPathFromMatch(match),
2680
- path
2681
- );
2682
- if (managedItem) {
2683
- classificationCache.set(path, managedItem);
2684
- managedItems.add(managedItem);
2685
- managedSet.add(path);
2686
- return true;
2687
- }
2688
- }
2689
- }
2690
- for (const managedPath of this.managedPathsWithSlash) {
2691
- if (path.startsWith(managedPath)) {
2692
- const managedItem = getManagedItem(managedPath, path);
2693
- if (managedItem) {
2694
- classificationCache.set(path, managedItem);
2695
- managedItems.add(managedItem);
2696
- managedSet.add(path);
2697
- return true;
2698
- }
2699
- }
2700
- }
2701
- classificationCache.set(path, 0);
2702
- return false;
2703
- };
2704
- /**
2705
- * Capture non managed.
2706
- * @param {Iterable<string>} items items
2707
- * @param {Set<string>} managedSet managed set
2708
- * @returns {Set<string>} result
2709
- */
2710
- const captureNonManaged = (items, managedSet) => {
2711
- /** @type {Set<string>} */
2712
- const capturedItems = new Set();
2713
- for (const path of items) {
2714
- if (!checkManaged(path, managedSet)) capturedItems.add(path);
2715
- }
2716
- return capturedItems;
2717
- };
2718
- /**
2719
- * Process captured files.
2720
- * @param {ManagedFiles} capturedFiles captured files
2721
- */
2722
- const processCapturedFiles = (capturedFiles) => {
2723
- if (capturedFiles.size === 0) {
2724
- return;
2725
- }
2726
- switch (mode) {
2727
- case 3: {
2728
- this._fileTshsOptimization.optimize(snapshot, capturedFiles);
2729
- if (fileTshs === undefined) fileTshs = new Map();
2730
- const fileTshsMap = fileTshs;
2731
- for (const path of capturedFiles) {
2732
- const cache = this._fileTshs.get(path);
2733
- if (cache !== undefined) {
2734
- fileTshsMap.set(path, cache);
2735
- } else {
2736
- jobs++;
2737
- this._getFileTimestampAndHash(path, (err, entry) => {
2738
- if (err) {
2739
- if (this.logger) {
2740
- this.logger.debug(
2741
- `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}`
2742
- );
2743
- }
2744
- jobError();
2745
- } else {
2746
- fileTshsMap.set(
2747
- path,
2748
- /** @type {TimestampAndHash} */ (entry)
2749
- );
2750
- jobDone();
2751
- }
2752
- });
2753
- }
2754
- }
2755
- break;
2756
- }
2757
- case 2: {
2758
- this._fileHashesOptimization.optimize(snapshot, capturedFiles);
2759
- if (fileHashes === undefined) fileHashes = new Map();
2760
- const fileHashesMap = fileHashes;
2761
- for (const path of capturedFiles) {
2762
- const cache = this._fileHashes.get(path);
2763
- if (cache !== undefined) {
2764
- fileHashesMap.set(path, cache);
2765
- } else {
2766
- jobs++;
2767
- this.fileHashQueue.add(path, (err, entry) => {
2768
- if (err) {
2769
- if (this.logger) {
2770
- this.logger.debug(
2771
- `Error snapshotting file hash of ${path}: ${err.stack}`
2772
- );
2773
- }
2774
- jobError();
2775
- } else {
2776
- fileHashesMap.set(path, /** @type {string} */ (entry));
2777
- jobDone();
2778
- }
2779
- });
2780
- }
2781
- }
2782
- break;
2783
- }
2784
- case 1: {
2785
- this._fileTimestampsOptimization.optimize(snapshot, capturedFiles);
2786
- if (fileTimestamps === undefined) fileTimestamps = new Map();
2787
- const fileTimestampsMap = fileTimestamps;
2788
- for (const path of capturedFiles) {
2789
- const cache = this._fileTimestamps.get(path);
2790
- if (cache !== undefined && !isExistenceOnly(cache)) {
2791
- if (cache !== "ignore") {
2792
- fileTimestampsMap.set(
2793
- path,
2794
- /** @type {FileSystemInfoEntry | null} */ (cache)
2795
- );
2796
- }
2797
- } else {
2798
- jobs++;
2799
- this.fileTimestampQueue.add(path, (err, entry) => {
2800
- if (err) {
2801
- if (this.logger) {
2802
- this.logger.debug(
2803
- `Error snapshotting file timestamp of ${path}: ${err.stack}`
2804
- );
2805
- }
2806
- jobError();
2807
- } else {
2808
- fileTimestampsMap.set(
2809
- path,
2810
- /** @type {FileSystemInfoEntry} */
2811
- (entry)
2812
- );
2813
- jobDone();
2814
- }
2815
- });
2816
- }
2817
- }
2818
- break;
2819
- }
2820
- }
2821
- };
2822
- if (files) {
2823
- processCapturedFiles(captureNonManaged(files, managedFiles));
2824
- }
2825
- /**
2826
- * Process captured directories.
2827
- * @param {ManagedContexts} capturedDirectories captured directories
2828
- */
2829
- const processCapturedDirectories = (capturedDirectories) => {
2830
- if (capturedDirectories.size === 0) {
2831
- return;
2832
- }
2833
- switch (mode) {
2834
- case 3: {
2835
- this._contextTshsOptimization.optimize(snapshot, capturedDirectories);
2836
- if (contextTshs === undefined) contextTshs = new Map();
2837
- const contextTshsMap = contextTshs;
2838
- for (const path of capturedDirectories) {
2839
- const cache = this._contextTshs.get(path);
2840
- /** @type {ResolvedContextTimestampAndHash | null | undefined} */
2841
- let resolved;
2842
- if (
2843
- cache !== undefined &&
2844
- (resolved = getResolvedTimestamp(cache)) !== undefined
2845
- ) {
2846
- contextTshsMap.set(path, resolved);
2847
- } else {
2848
- jobs++;
2849
- /**
2850
- * Processes the provided err.
2851
- * @param {(WebpackError | null)=} err error
2852
- * @param {(ResolvedContextTimestampAndHash | null)=} entry entry
2853
- * @returns {void}
2854
- */
2855
- const callback = (err, entry) => {
2856
- if (err) {
2857
- if (this.logger) {
2858
- this.logger.debug(
2859
- `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}`
2860
- );
2861
- }
2862
- jobError();
2863
- } else {
2864
- contextTshsMap.set(
2865
- path,
2866
- /** @type {ResolvedContextTimestampAndHash | null} */
2867
- (entry)
2868
- );
2869
- jobDone();
2870
- }
2871
- };
2872
- if (cache !== undefined) {
2873
- this._resolveContextTsh(cache, callback);
2874
- } else {
2875
- this.getContextTsh(path, callback);
2876
- }
2877
- }
2878
- }
2879
- break;
2880
- }
2881
- case 2: {
2882
- this._contextHashesOptimization.optimize(
2883
- snapshot,
2884
- capturedDirectories
2885
- );
2886
- if (contextHashes === undefined) contextHashes = new Map();
2887
- const contextHashesMap = contextHashes;
2888
- for (const path of capturedDirectories) {
2889
- const cache = this._contextHashes.get(path);
2890
- /** @type {undefined | null | string} */
2891
- let resolved;
2892
- if (
2893
- cache !== undefined &&
2894
- (resolved = getResolvedHash(cache)) !== undefined
2895
- ) {
2896
- contextHashesMap.set(path, resolved);
2897
- } else {
2898
- jobs++;
2899
- /**
2900
- * Processes the provided err.
2901
- * @param {(WebpackError | null)=} err err
2902
- * @param {string=} entry entry
2903
- */
2904
- const callback = (err, entry) => {
2905
- if (err) {
2906
- if (this.logger) {
2907
- this.logger.debug(
2908
- `Error snapshotting context hash of ${path}: ${err.stack}`
2909
- );
2910
- }
2911
- jobError();
2912
- } else {
2913
- contextHashesMap.set(path, /** @type {string} */ (entry));
2914
- jobDone();
2915
- }
2916
- };
2917
- if (cache !== undefined) {
2918
- this._resolveContextHash(cache, callback);
2919
- } else {
2920
- this.getContextHash(path, callback);
2921
- }
2922
- }
2923
- }
2924
- break;
2925
- }
2926
- case 1: {
2927
- this._contextTimestampsOptimization.optimize(
2928
- snapshot,
2929
- capturedDirectories
2930
- );
2931
- if (contextTimestamps === undefined) contextTimestamps = new Map();
2932
- const contextTimestampsMap = contextTimestamps;
2933
- for (const path of capturedDirectories) {
2934
- const cache = this._contextTimestamps.get(path);
2935
- if (cache === "ignore") continue;
2936
- /** @type {ContextFileSystemInfoEntry | null | undefined} */
2937
- const usableCache =
2938
- cache === undefined || isExistenceOnly(cache)
2939
- ? undefined
2940
- : /** @type {ContextFileSystemInfoEntry | null} */ (cache);
2941
- const cacheLacksHash =
2942
- contextCacheEntryLacksTimestampHash(usableCache);
2943
- /** @type {undefined | null | ResolvedContextFileSystemInfoEntry} */
2944
- let resolved;
2945
- if (
2946
- usableCache !== undefined &&
2947
- !cacheLacksHash &&
2948
- (resolved = getResolvedTimestamp(usableCache)) !== undefined
2949
- ) {
2950
- contextTimestampsMap.set(path, resolved);
2951
- } else {
2952
- jobs++;
2953
- /**
2954
- * Processes the provided err.
2955
- * @param {(WebpackError | null)=} err error
2956
- * @param {ResolvedContextTimestamp=} entry entry
2957
- * @returns {void}
2958
- */
2959
- const callback = (err, entry) => {
2960
- if (err) {
2961
- if (this.logger) {
2962
- this.logger.debug(
2963
- `Error snapshotting context timestamp of ${path}: ${err.stack}`
2964
- );
2965
- }
2966
- jobError();
2967
- } else {
2968
- contextTimestampsMap.set(
2969
- path,
2970
- /** @type {ResolvedContextFileSystemInfoEntry | null} */
2971
- (entry)
2972
- );
2973
- jobDone();
2974
- }
2975
- };
2976
- if (cacheLacksHash) {
2977
- this._readFreshContextTimestamp(path, callback);
2978
- } else if (usableCache !== undefined && usableCache !== null) {
2979
- this._resolveContextTimestamp(usableCache, callback);
2980
- } else {
2981
- // Force a fresh on-disk read so the snapshot stores a
2982
- // complete entry (with `timestampHash`).
2983
- this._readFreshContextTimestamp(path, callback);
2984
- }
2985
- }
2986
- }
2987
- break;
2988
- }
2989
- }
2990
- };
2991
- if (directories) {
2992
- processCapturedDirectories(
2993
- captureNonManaged(directories, managedContexts)
2994
- );
2995
- }
2996
- /**
2997
- * Process captured missing.
2998
- * @param {ManagedMissing} capturedMissing captured missing
2999
- */
3000
- const processCapturedMissing = (capturedMissing) => {
3001
- if (capturedMissing.size === 0) {
3002
- return;
3003
- }
3004
- this._missingExistenceOptimization.optimize(snapshot, capturedMissing);
3005
- if (missingExistence === undefined) missingExistence = new Map();
3006
- const missingExistenceMap = missingExistence;
3007
- for (const path of capturedMissing) {
3008
- const cache = this._fileTimestamps.get(path);
3009
- if (cache !== undefined && !isExistenceOnly(cache)) {
3010
- if (cache !== "ignore") {
3011
- missingExistenceMap.set(path, Boolean(cache));
3012
- }
3013
- } else {
3014
- jobs++;
3015
- this.fileTimestampQueue.add(path, (err, entry) => {
3016
- if (err) {
3017
- if (this.logger) {
3018
- this.logger.debug(
3019
- `Error snapshotting missing timestamp of ${path}: ${err.stack}`
3020
- );
3021
- }
3022
- jobError();
3023
- } else {
3024
- missingExistenceMap.set(path, Boolean(entry));
3025
- jobDone();
3026
- }
3027
- });
3028
- }
3029
- }
3030
- };
3031
- if (missing) {
3032
- processCapturedMissing(captureNonManaged(missing, managedMissing));
3033
- }
3034
- this._managedItemInfoOptimization.optimize(snapshot, managedItems);
3035
- if (managedItems.size !== 0 && managedItemInfo === undefined) {
3036
- managedItemInfo = new Map();
3037
- }
3038
- const managedItemInfoMap = managedItemInfo;
3039
- for (const path of managedItems) {
3040
- const cache = this._managedItems.get(path);
3041
- if (cache !== undefined) {
3042
- if (!cache.startsWith("*")) {
3043
- managedFiles.add(join(this.fs, path, "package.json"));
3044
- } else if (cache === "*nested") {
3045
- managedMissing.add(join(this.fs, path, "package.json"));
3046
- }
3047
- /** @type {ManagedItemInfo} */ (managedItemInfoMap).set(path, cache);
3048
- } else {
3049
- jobs++;
3050
- this.managedItemQueue.add(path, (err, entry) => {
3051
- if (err) {
3052
- if (this.logger) {
3053
- this.logger.debug(
3054
- `Error snapshotting managed item ${path}: ${err.stack}`
3055
- );
3056
- }
3057
- jobError();
3058
- } else if (entry) {
3059
- if (!entry.startsWith("*")) {
3060
- managedFiles.add(join(this.fs, path, "package.json"));
3061
- } else if (cache === "*nested") {
3062
- managedMissing.add(join(this.fs, path, "package.json"));
3063
- }
3064
- /** @type {ManagedItemInfo} */ (managedItemInfoMap).set(
3065
- path,
3066
- entry
3067
- );
3068
- jobDone();
3069
- } else {
3070
- // Fallback to normal snapshotting
3071
- /**
3072
- * Processes the provided set.
3073
- * @param {Set<string>} set set
3074
- * @param {(set: Set<string>) => void} fn fn
3075
- */
3076
- const process = (set, fn) => {
3077
- if (set.size === 0) return;
3078
- /** @type {Set<string>} */
3079
- const captured = new Set();
3080
- for (const file of set) {
3081
- if (file.startsWith(path)) captured.add(file);
3082
- }
3083
- if (captured.size > 0) fn(captured);
3084
- };
3085
- process(managedFiles, processCapturedFiles);
3086
- process(managedContexts, processCapturedDirectories);
3087
- process(managedMissing, processCapturedMissing);
3088
- jobDone();
3089
- }
3090
- });
3091
- }
3092
- }
3093
- jobDone();
3094
- }
3095
-
3096
- /**
3097
- * Merges the provided values into a single result.
3098
- * @param {Snapshot} snapshot1 a snapshot
3099
- * @param {Snapshot} snapshot2 a snapshot
3100
- * @returns {Snapshot} merged snapshot
3101
- */
3102
- mergeSnapshots(snapshot1, snapshot2) {
3103
- const snapshot = new Snapshot();
3104
- if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) {
3105
- snapshot.setStartTime(
3106
- Math.min(
3107
- /** @type {NonNullable<Snapshot["startTime"]>} */
3108
- (snapshot1.startTime),
3109
- /** @type {NonNullable<Snapshot["startTime"]>} */
3110
- (snapshot2.startTime)
3111
- )
3112
- );
3113
- } else if (snapshot2.hasStartTime()) {
3114
- snapshot.startTime = snapshot2.startTime;
3115
- } else if (snapshot1.hasStartTime()) {
3116
- snapshot.startTime = snapshot1.startTime;
3117
- }
3118
- if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) {
3119
- snapshot.setFileTimestamps(
3120
- mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps)
3121
- );
3122
- }
3123
- if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) {
3124
- snapshot.setFileHashes(
3125
- mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes)
3126
- );
3127
- }
3128
- if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) {
3129
- snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs));
3130
- }
3131
- if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) {
3132
- snapshot.setContextTimestamps(
3133
- mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps)
3134
- );
3135
- }
3136
- if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) {
3137
- snapshot.setContextHashes(
3138
- mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes)
3139
- );
3140
- }
3141
- if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) {
3142
- snapshot.setContextTshs(
3143
- mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs)
3144
- );
3145
- }
3146
- if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) {
3147
- snapshot.setMissingExistence(
3148
- mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence)
3149
- );
3150
- }
3151
- if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) {
3152
- snapshot.setManagedItemInfo(
3153
- mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo)
3154
- );
3155
- }
3156
- if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) {
3157
- snapshot.setManagedFiles(
3158
- mergeSets(snapshot1.managedFiles, snapshot2.managedFiles)
3159
- );
3160
- }
3161
- if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) {
3162
- snapshot.setManagedContexts(
3163
- mergeSets(snapshot1.managedContexts, snapshot2.managedContexts)
3164
- );
3165
- }
3166
- if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) {
3167
- snapshot.setManagedMissing(
3168
- mergeSets(snapshot1.managedMissing, snapshot2.managedMissing)
3169
- );
3170
- }
3171
- if (snapshot1.hasChildren() || snapshot2.hasChildren()) {
3172
- snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children));
3173
- }
3174
- if (
3175
- this._snapshotCache.get(snapshot1) === true &&
3176
- this._snapshotCache.get(snapshot2) === true
3177
- ) {
3178
- this._snapshotCache.set(snapshot, true);
3179
- }
3180
- return snapshot;
3181
- }
3182
-
3183
- /**
3184
- * Checks snapshot valid.
3185
- * @param {Snapshot} snapshot the snapshot made
3186
- * @param {CheckSnapshotValidCallback} callback callback function
3187
- * @returns {void}
3188
- */
3189
- checkSnapshotValid(snapshot, callback) {
3190
- const cachedResult = this._snapshotCache.get(snapshot);
3191
- if (cachedResult !== undefined) {
3192
- this._statTestedSnapshotsCached++;
3193
- if (typeof cachedResult === "boolean") {
3194
- callback(null, cachedResult);
3195
- } else {
3196
- cachedResult.push(callback);
3197
- }
3198
- return;
3199
- }
3200
- this._statTestedSnapshotsNotCached++;
3201
- this._checkSnapshotValidNoCache(snapshot, callback);
3202
- }
3203
-
3204
- /**
3205
- * Check snapshot valid no cache.
3206
- * @private
3207
- * @param {Snapshot} snapshot the snapshot made
3208
- * @param {CheckSnapshotValidCallback} callback callback function
3209
- * @returns {void}
3210
- */
3211
- _checkSnapshotValidNoCache(snapshot, callback) {
3212
- /** @type {number | undefined} */
3213
- let startTime;
3214
- if (snapshot.hasStartTime()) {
3215
- startTime = snapshot.startTime;
3216
- }
3217
- let jobs = 1;
3218
- const jobDone = () => {
3219
- if (--jobs === 0) {
3220
- this._snapshotCache.set(snapshot, true);
3221
- callback(null, true);
3222
- }
3223
- };
3224
- const invalid = () => {
3225
- if (jobs > 0) {
3226
- // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
3227
- jobs = -100000000;
3228
- this._snapshotCache.set(snapshot, false);
3229
- callback(null, false);
3230
- }
3231
- };
3232
- /**
3233
- * Invalid with error.
3234
- * @param {string} path path
3235
- * @param {WebpackError} err err
3236
- */
3237
- const invalidWithError = (path, err) => {
3238
- if (this._remainingLogs > 0) {
3239
- this._log(path, "error occurred: %s", err);
3240
- }
3241
- invalid();
3242
- };
3243
- /**
3244
- * Checks true, if ok.
3245
- * @param {string} path file path
3246
- * @param {string | null} current current hash
3247
- * @param {string | null} snap snapshot hash
3248
- * @returns {boolean} true, if ok
3249
- */
3250
- const checkHash = (path, current, snap) => {
3251
- if (current !== snap) {
3252
- // If hash differ it's invalid
3253
- if (this._remainingLogs > 0) {
3254
- this._log(path, "hashes differ (%s != %s)", current, snap);
3255
- }
3256
- return false;
3257
- }
3258
- return true;
3259
- };
3260
- /**
3261
- * Checks true, if ok.
3262
- * @param {string} path file path
3263
- * @param {boolean} current current entry
3264
- * @param {boolean} snap entry from snapshot
3265
- * @returns {boolean} true, if ok
3266
- */
3267
- const checkExistence = (path, current, snap) => {
3268
- if (!current !== !snap) {
3269
- // If existence of item differs
3270
- // it's invalid
3271
- if (this._remainingLogs > 0) {
3272
- this._log(
3273
- path,
3274
- current ? "it didn't exist before" : "it does no longer exist"
3275
- );
3276
- }
3277
- return false;
3278
- }
3279
- return true;
3280
- };
3281
- /**
3282
- * Checks true, if ok.
3283
- * @param {string} path file path
3284
- * @param {FileSystemInfoEntry | null} c current entry
3285
- * @param {FileSystemInfoEntry | null} s entry from snapshot
3286
- * @param {boolean} log log reason
3287
- * @returns {boolean} true, if ok
3288
- */
3289
- const checkFile = (path, c, s, log = true) => {
3290
- if (c === s) return true;
3291
- if (!checkExistence(path, Boolean(c), Boolean(s))) return false;
3292
- if (c) {
3293
- // For existing items only
3294
- if (typeof startTime === "number" && c.safeTime > startTime) {
3295
- // If a change happened after starting reading the item
3296
- // this may no longer be valid
3297
- if (log && this._remainingLogs > 0) {
3298
- this._log(
3299
- path,
3300
- "it may have changed (%d) after the start time of the snapshot (%d)",
3301
- c.safeTime,
3302
- startTime
3303
- );
3304
- }
3305
- return false;
3306
- }
3307
- const snap = /** @type {FileSystemInfoEntry} */ (s);
3308
- if (snap.timestamp !== undefined && c.timestamp !== snap.timestamp) {
3309
- // If we have a timestamp (it was a file or symlink) and it differs from current timestamp
3310
- // it's invalid
3311
- if (log && this._remainingLogs > 0) {
3312
- this._log(
3313
- path,
3314
- "timestamps differ (%d != %d)",
3315
- c.timestamp,
3316
- snap.timestamp
3317
- );
3318
- }
3319
- return false;
3320
- }
3321
- }
3322
- return true;
3323
- };
3324
- /**
3325
- * Checks true, if ok.
3326
- * @param {string} path file path
3327
- * @param {ResolvedContextFileSystemInfoEntry | null} c current entry
3328
- * @param {ResolvedContextFileSystemInfoEntry | null} s entry from snapshot
3329
- * @param {boolean} log log reason
3330
- * @returns {boolean} true, if ok
3331
- */
3332
- const checkContext = (path, c, s, log = true) => {
3333
- if (c === s) return true;
3334
- if (!checkExistence(path, Boolean(c), Boolean(s))) return false;
3335
- if (c) {
3336
- // For existing items only
3337
- if (typeof startTime === "number" && c.safeTime > startTime) {
3338
- // If a change happened after starting reading the item
3339
- // this may no longer be valid
3340
- if (log && this._remainingLogs > 0) {
3341
- this._log(
3342
- path,
3343
- "it may have changed (%d) after the start time of the snapshot (%d)",
3344
- c.safeTime,
3345
- startTime
3346
- );
3347
- }
3348
- return false;
3349
- }
3350
- const snap = /** @type {ResolvedContextFileSystemInfoEntry} */ (s);
3351
- if (
3352
- snap.timestampHash !== undefined &&
3353
- c.timestampHash !== snap.timestampHash
3354
- ) {
3355
- // If we have a timestampHash (it was a directory) and it differs from current timestampHash
3356
- // it's invalid
3357
- if (log && this._remainingLogs > 0) {
3358
- this._log(
3359
- path,
3360
- "timestamps hashes differ (%s != %s)",
3361
- c.timestampHash,
3362
- snap.timestampHash
3363
- );
3364
- }
3365
- return false;
3366
- }
3367
- }
3368
- return true;
3369
- };
3370
- if (snapshot.hasChildren()) {
3371
- /**
3372
- * Processes the provided err.
3373
- * @param {(WebpackError | null)=} err err
3374
- * @param {boolean=} result result
3375
- * @returns {void}
3376
- */
3377
- const childCallback = (err, result) => {
3378
- if (err || !result) return invalid();
3379
- jobDone();
3380
- };
3381
- for (const child of /** @type {Children} */ (snapshot.children)) {
3382
- const cache = this._snapshotCache.get(child);
3383
- if (cache !== undefined) {
3384
- this._statTestedChildrenCached++;
3385
- /* istanbul ignore else */
3386
- if (typeof cache === "boolean") {
3387
- if (cache === false) {
3388
- invalid();
3389
- return;
3390
- }
3391
- } else {
3392
- jobs++;
3393
- cache.push(childCallback);
3394
- }
3395
- } else {
3396
- this._statTestedChildrenNotCached++;
3397
- jobs++;
3398
- this._checkSnapshotValidNoCache(child, childCallback);
3399
- }
3400
- }
3401
- }
3402
- if (snapshot.hasFileTimestamps()) {
3403
- const fileTimestamps =
3404
- /** @type {FileTimestamps} */
3405
- (snapshot.fileTimestamps);
3406
- this._statTestedEntries += fileTimestamps.size;
3407
- for (const [path, ts] of fileTimestamps) {
3408
- const cache = this._fileTimestamps.get(path);
3409
- if (cache !== undefined && !isExistenceOnly(cache)) {
3410
- if (
3411
- cache !== "ignore" &&
3412
- !checkFile(
3413
- path,
3414
- /** @type {FileSystemInfoEntry | null} */ (cache),
3415
- ts
3416
- )
3417
- ) {
3418
- invalid();
3419
- return;
3420
- }
3421
- } else {
3422
- jobs++;
3423
- this.fileTimestampQueue.add(path, (err, entry) => {
3424
- if (err) return invalidWithError(path, err);
3425
- if (
3426
- !checkFile(
3427
- path,
3428
- /** @type {FileSystemInfoEntry | null} */ (entry),
3429
- ts
3430
- )
3431
- ) {
3432
- invalid();
3433
- } else {
3434
- jobDone();
3435
- }
3436
- });
3437
- }
3438
- }
3439
- }
3440
- /**
3441
- * Process file hash snapshot.
3442
- * @param {string} path file path
3443
- * @param {string | null} hash hash
3444
- */
3445
- const processFileHashSnapshot = (path, hash) => {
3446
- const cache = this._fileHashes.get(path);
3447
- if (cache !== undefined) {
3448
- if (cache !== "ignore" && !checkHash(path, cache, hash)) {
3449
- invalid();
3450
- }
3451
- } else {
3452
- jobs++;
3453
- this.fileHashQueue.add(path, (err, entry) => {
3454
- if (err) return invalidWithError(path, err);
3455
- if (!checkHash(path, /** @type {string} */ (entry), hash)) {
3456
- invalid();
3457
- } else {
3458
- jobDone();
3459
- }
3460
- });
3461
- }
3462
- };
3463
- if (snapshot.hasFileHashes()) {
3464
- const fileHashes = /** @type {FileHashes} */ (snapshot.fileHashes);
3465
- this._statTestedEntries += fileHashes.size;
3466
- for (const [path, hash] of fileHashes) {
3467
- processFileHashSnapshot(path, hash);
3468
- }
3469
- }
3470
- if (snapshot.hasFileTshs()) {
3471
- const fileTshs = /** @type {FileTshs} */ (snapshot.fileTshs);
3472
- this._statTestedEntries += fileTshs.size;
3473
- for (const [path, tsh] of fileTshs) {
3474
- if (typeof tsh === "string") {
3475
- processFileHashSnapshot(path, tsh);
3476
- } else {
3477
- const cache = this._fileTimestamps.get(path);
3478
- if (cache !== undefined && !isExistenceOnly(cache)) {
3479
- if (
3480
- cache === "ignore" ||
3481
- !checkFile(
3482
- path,
3483
- /** @type {FileSystemInfoEntry | null} */ (cache),
3484
- tsh,
3485
- false
3486
- )
3487
- ) {
3488
- processFileHashSnapshot(path, tsh && tsh.hash);
3489
- }
3490
- } else {
3491
- jobs++;
3492
- this.fileTimestampQueue.add(path, (err, entry) => {
3493
- if (err) return invalidWithError(path, err);
3494
- if (
3495
- !checkFile(
3496
- path,
3497
- /** @type {FileSystemInfoEntry | null} */
3498
- (entry),
3499
- tsh,
3500
- false
3501
- )
3502
- ) {
3503
- processFileHashSnapshot(path, tsh && tsh.hash);
3504
- }
3505
- jobDone();
3506
- });
3507
- }
3508
- }
3509
- }
3510
- }
3511
- if (snapshot.hasContextTimestamps()) {
3512
- const contextTimestamps =
3513
- /** @type {ContextTimestamps} */
3514
- (snapshot.contextTimestamps);
3515
- this._statTestedEntries += contextTimestamps.size;
3516
- for (const [path, ts] of contextTimestamps) {
3517
- const cache = this._contextTimestamps.get(path);
3518
- if (cache === "ignore") continue;
3519
- // Treat existence-only entries (`{}` from watchpack) as a cache
3520
- // miss — they carry no time info, so we cannot compare them to
3521
- // the snapshot.
3522
- /** @type {ContextFileSystemInfoEntry | null | undefined} */
3523
- const usableCache =
3524
- cache === undefined || isExistenceOnly(cache)
3525
- ? undefined
3526
- : /** @type {ContextFileSystemInfoEntry | null} */ (cache);
3527
- const cacheLacksHash =
3528
- contextCacheEntryLacksTimestampHash(usableCache) &&
3529
- ts !== null &&
3530
- ts.timestampHash !== undefined;
3531
- /** @type {undefined | null | ResolvedContextFileSystemInfoEntry} */
3532
- let resolved;
3533
- if (
3534
- usableCache !== undefined &&
3535
- !cacheLacksHash &&
3536
- (resolved = getResolvedTimestamp(usableCache)) !== undefined
3537
- ) {
3538
- if (!checkContext(path, resolved, ts)) {
3539
- invalid();
3540
- return;
3541
- }
3542
- } else {
3543
- jobs++;
3544
- /**
3545
- * Processes the provided err.
3546
- * @param {(WebpackError | null)=} err error
3547
- * @param {ResolvedContextTimestamp=} entry entry
3548
- * @returns {void}
3549
- */
3550
- const callback = (err, entry) => {
3551
- if (err) return invalidWithError(path, err);
3552
- if (
3553
- !checkContext(
3554
- path,
3555
- /** @type {ResolvedContextFileSystemInfoEntry | null} */
3556
- (entry),
3557
- ts
3558
- )
3559
- ) {
3560
- invalid();
3561
- } else {
3562
- jobDone();
3563
- }
3564
- };
3565
- if (cacheLacksHash) {
3566
- this._readFreshContextTimestamp(path, callback);
3567
- } else if (usableCache !== undefined && usableCache !== null) {
3568
- this._resolveContextTimestamp(usableCache, callback);
3569
- } else {
3570
- this.getContextTimestamp(path, callback);
3571
- }
3572
- }
3573
- }
3574
- }
3575
- /**
3576
- * Process context hash snapshot.
3577
- * @param {string} path path
3578
- * @param {string | null} hash hash
3579
- */
3580
- const processContextHashSnapshot = (path, hash) => {
3581
- const cache = this._contextHashes.get(path);
3582
- /** @type {undefined | null | string} */
3583
- let resolved;
3584
- if (
3585
- cache !== undefined &&
3586
- (resolved = getResolvedHash(cache)) !== undefined
3587
- ) {
3588
- if (!checkHash(path, resolved, hash)) {
3589
- invalid();
3590
- }
3591
- } else {
3592
- jobs++;
3593
- /**
3594
- * Processes the provided err.
3595
- * @param {(WebpackError | null)=} err err
3596
- * @param {string=} entry entry
3597
- * @returns {void}
3598
- */
3599
- const callback = (err, entry) => {
3600
- if (err) return invalidWithError(path, err);
3601
- if (!checkHash(path, /** @type {string} */ (entry), hash)) {
3602
- invalid();
3603
- } else {
3604
- jobDone();
3605
- }
3606
- };
3607
- if (cache !== undefined) {
3608
- this._resolveContextHash(cache, callback);
3609
- } else {
3610
- this.getContextHash(path, callback);
3611
- }
3612
- }
3613
- };
3614
- if (snapshot.hasContextHashes()) {
3615
- const contextHashes =
3616
- /** @type {ContextHashes} */
3617
- (snapshot.contextHashes);
3618
- this._statTestedEntries += contextHashes.size;
3619
- for (const [path, hash] of contextHashes) {
3620
- processContextHashSnapshot(path, hash);
3621
- }
3622
- }
3623
- if (snapshot.hasContextTshs()) {
3624
- const contextTshs = /** @type {ContextTshs} */ (snapshot.contextTshs);
3625
- this._statTestedEntries += contextTshs.size;
3626
- for (const [path, tsh] of contextTshs) {
3627
- if (typeof tsh === "string") {
3628
- processContextHashSnapshot(path, tsh);
3629
- } else {
3630
- const cache = this._contextTimestamps.get(path);
3631
- if (cache === "ignore") continue;
3632
- // See the matching block in `hasContextTimestamps` above.
3633
- /** @type {ContextFileSystemInfoEntry | null | undefined} */
3634
- const usableCache =
3635
- cache === undefined || isExistenceOnly(cache)
3636
- ? undefined
3637
- : /** @type {ContextFileSystemInfoEntry | null} */ (cache);
3638
- const cacheLacksHash =
3639
- contextCacheEntryLacksTimestampHash(usableCache) &&
3640
- tsh !== null &&
3641
- tsh.timestampHash !== undefined;
3642
- /** @type {undefined | null | ResolvedContextFileSystemInfoEntry} */
3643
- let resolved;
3644
- if (
3645
- usableCache !== undefined &&
3646
- !cacheLacksHash &&
3647
- (resolved = getResolvedTimestamp(usableCache)) !== undefined
3648
- ) {
3649
- if (!checkContext(path, resolved, tsh, false)) {
3650
- processContextHashSnapshot(path, tsh && tsh.hash);
3651
- }
3652
- } else {
3653
- jobs++;
3654
- /**
3655
- * Processes the provided err.
3656
- * @param {(WebpackError | null)=} err error
3657
- * @param {ResolvedContextTimestamp=} entry entry
3658
- * @returns {void}
3659
- */
3660
- const callback = (err, entry) => {
3661
- if (err) return invalidWithError(path, err);
3662
- if (
3663
- !checkContext(
3664
- path,
3665
- /** @type {ResolvedContextFileSystemInfoEntry | null} */
3666
- (entry),
3667
- tsh,
3668
- false
3669
- )
3670
- ) {
3671
- processContextHashSnapshot(path, tsh && tsh.hash);
3672
- }
3673
- jobDone();
3674
- };
3675
- if (cacheLacksHash) {
3676
- this._readFreshContextTimestamp(path, callback);
3677
- } else if (usableCache !== undefined && usableCache !== null) {
3678
- this._resolveContextTimestamp(usableCache, callback);
3679
- } else {
3680
- this.getContextTimestamp(path, callback);
3681
- }
3682
- }
3683
- }
3684
- }
3685
- }
3686
- if (snapshot.hasMissingExistence()) {
3687
- const missingExistence =
3688
- /** @type {MissingExistence} */
3689
- (snapshot.missingExistence);
3690
- this._statTestedEntries += missingExistence.size;
3691
- for (const [path, existence] of missingExistence) {
3692
- const cache = this._fileTimestamps.get(path);
3693
- if (cache !== undefined && !isExistenceOnly(cache)) {
3694
- if (
3695
- cache !== "ignore" &&
3696
- !checkExistence(path, Boolean(cache), Boolean(existence))
3697
- ) {
3698
- invalid();
3699
- return;
3700
- }
3701
- } else {
3702
- jobs++;
3703
- this.fileTimestampQueue.add(path, (err, entry) => {
3704
- if (err) return invalidWithError(path, err);
3705
- if (!checkExistence(path, Boolean(entry), Boolean(existence))) {
3706
- invalid();
3707
- } else {
3708
- jobDone();
3709
- }
3710
- });
3711
- }
3712
- }
3713
- }
3714
- if (snapshot.hasManagedItemInfo()) {
3715
- const managedItemInfo =
3716
- /** @type {ManagedItemInfo} */
3717
- (snapshot.managedItemInfo);
3718
- this._statTestedEntries += managedItemInfo.size;
3719
- for (const [path, info] of managedItemInfo) {
3720
- const cache = this._managedItems.get(path);
3721
- if (cache !== undefined) {
3722
- if (!checkHash(path, cache, info)) {
3723
- invalid();
3724
- return;
3725
- }
3726
- } else {
3727
- jobs++;
3728
- this.managedItemQueue.add(path, (err, entry) => {
3729
- if (err) return invalidWithError(path, err);
3730
- if (!checkHash(path, /** @type {string} */ (entry), info)) {
3731
- invalid();
3732
- } else {
3733
- jobDone();
3734
- }
3735
- });
3736
- }
3737
- }
3738
- }
3739
- jobDone();
3740
-
3741
- // if there was an async action
3742
- // try to join multiple concurrent request for this snapshot
3743
- if (jobs > 0) {
3744
- const callbacks = [callback];
3745
- callback = (err, result) => {
3746
- for (const callback of callbacks) callback(err, result);
3747
- };
3748
- this._snapshotCache.set(snapshot, callbacks);
3749
- }
3750
- }
3751
-
3752
- /**
3753
- * @private
3754
- * @type {Processor<string, FileSystemInfoEntry>}
3755
- */
3756
- _readFileTimestamp(path, callback) {
3757
- this.fs.stat(path, (err, _stat) => {
3758
- if (err) {
3759
- if (err.code === "ENOENT") {
3760
- this._fileTimestamps.set(path, null);
3761
- this._cachedDeprecatedFileTimestamps = undefined;
3762
- return callback(null, null);
3763
- }
3764
- return callback(/** @type {WebpackError} */ (err));
3765
- }
3766
- const stat = /** @type {IStats} */ (_stat);
3767
- /** @type {FileSystemInfoEntry} */
3768
- let ts;
3769
- if (stat.isDirectory()) {
3770
- ts = {
3771
- safeTime: 0,
3772
- timestamp: undefined
3773
- };
3774
- } else {
3775
- const mtime = Number(stat.mtime);
3776
-
3777
- if (mtime) applyMtime(mtime);
3778
-
3779
- ts = {
3780
- safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
3781
- timestamp: mtime
3782
- };
3783
- }
3784
-
3785
- this._fileTimestamps.set(path, ts);
3786
- this._cachedDeprecatedFileTimestamps = undefined;
3787
-
3788
- callback(null, ts);
3789
- });
3790
- }
3791
-
3792
- /**
3793
- * @private
3794
- * @type {Processor<string, string>}
3795
- */
3796
- _readFileHash(path, callback) {
3797
- this.fs.readFile(path, (err, content) => {
3798
- if (err) {
3799
- if (err.code === "EISDIR") {
3800
- this._fileHashes.set(path, "directory");
3801
- return callback(null, "directory");
3802
- }
3803
- if (err.code === "ENOENT") {
3804
- this._fileHashes.set(path, null);
3805
- return callback(null, null);
3806
- }
3807
- if (err.code === "ERR_FS_FILE_TOO_LARGE") {
3808
- /** @type {Logger} */
3809
- (this.logger).warn(`Ignoring ${path} for hashing as it's very large`);
3810
- this._fileHashes.set(path, "too large");
3811
- return callback(null, "too large");
3812
- }
3813
- return callback(/** @type {WebpackError} */ (err));
3814
- }
3815
-
3816
- const hash = createHash(this._hashFunction);
3817
-
3818
- hash.update(/** @type {string | Buffer} */ (content));
3819
-
3820
- const digest = hash.digest("hex");
3821
-
3822
- this._fileHashes.set(path, digest);
3823
-
3824
- callback(null, digest);
3825
- });
3826
- }
3827
-
3828
- /**
3829
- * Get file timestamp and hash.
3830
- * @private
3831
- * @param {string} path path
3832
- * @param {(err: WebpackError | null, timestampAndHash?: TimestampAndHash | string) => void} callback callback
3833
- */
3834
- _getFileTimestampAndHash(path, callback) {
3835
- /**
3836
- * Continue with hash.
3837
- * @param {string} hash hash
3838
- * @returns {void}
3839
- */
3840
- const continueWithHash = (hash) => {
3841
- const cache = this._fileTimestamps.get(path);
3842
- if (cache !== undefined) {
3843
- if (cache !== "ignore") {
3844
- /** @type {TimestampAndHash} */
3845
- const result = {
3846
- .../** @type {FileSystemInfoEntry} */ (cache),
3847
- hash
3848
- };
3849
- this._fileTshs.set(path, result);
3850
- return callback(null, result);
3851
- }
3852
- this._fileTshs.set(path, hash);
3853
- return callback(null, hash);
3854
- }
3855
- this.fileTimestampQueue.add(path, (err, entry) => {
3856
- if (err) {
3857
- return callback(err);
3858
- }
3859
- /** @type {TimestampAndHash} */
3860
- const result = {
3861
- .../** @type {FileSystemInfoEntry} */ (entry),
3862
- hash
3863
- };
3864
- this._fileTshs.set(path, result);
3865
- return callback(null, result);
3866
- });
3867
- };
3868
-
3869
- const cache = this._fileHashes.get(path);
3870
- if (cache !== undefined) {
3871
- continueWithHash(/** @type {string} */ (cache));
3872
- } else {
3873
- this.fileHashQueue.add(path, (err, entry) => {
3874
- if (err) {
3875
- return callback(err);
3876
- }
3877
- continueWithHash(/** @type {string} */ (entry));
3878
- });
3879
- }
3880
- }
3881
-
3882
- /**
3883
- * Processes the provided object.
3884
- * @private
3885
- * @template T
3886
- * @template ItemType
3887
- * @param {object} options options
3888
- * @param {string} options.path path
3889
- * @param {(value: string) => ItemType} options.fromImmutablePath called when context item is an immutable path
3890
- * @param {(value: string) => ItemType} options.fromManagedItem called when context item is a managed path
3891
- * @param {(value: string, result: string, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromSymlink called when context item is a symlink
3892
- * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType | null) => void) => void} options.fromFile called when context item is a file
3893
- * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromDirectory called when context item is a directory
3894
- * @param {(arr: string[], arr1: ItemType[]) => T} options.reduce called from all context items
3895
- * @param {(err?: Error | null, result?: T | null) => void} callback callback
3896
- */
3897
- _readContext(
3898
- {
3899
- path,
3900
- fromImmutablePath,
3901
- fromManagedItem,
3902
- fromSymlink,
3903
- fromFile,
3904
- fromDirectory,
3905
- reduce
3906
- },
3907
- callback
3908
- ) {
3909
- this.fs.readdir(path, (err, _files) => {
3910
- if (err) {
3911
- if (err.code === "ENOENT") {
3912
- return callback(null, null);
3913
- }
3914
- return callback(err);
3915
- }
3916
- const files = /** @type {string[]} */ (_files)
3917
- .map((file) => file.normalize("NFC"))
3918
- .filter((file) => !/^\./.test(file))
3919
- .sort();
3920
- asyncLib.map(
3921
- files,
3922
- (file, callback) => {
3923
- const child = join(this.fs, path, file);
3924
- for (const immutablePath of this.immutablePathsRegExps) {
3925
- if (immutablePath.test(path)) {
3926
- // ignore any immutable path for timestamping
3927
- return callback(null, fromImmutablePath(path));
3928
- }
3929
- }
3930
- for (const immutablePath of this.immutablePathsWithSlash) {
3931
- if (path.startsWith(immutablePath)) {
3932
- // ignore any immutable path for timestamping
3933
- return callback(null, fromImmutablePath(path));
3934
- }
3935
- }
3936
- for (const managedPath of this.managedPathsRegExps) {
3937
- const match = managedPath.exec(path);
3938
- if (match) {
3939
- const managedItem = getManagedItem(
3940
- getManagedPathFromMatch(match),
3941
- path
3942
- );
3943
- if (managedItem) {
3944
- // construct timestampHash from managed info
3945
- return this.managedItemQueue.add(managedItem, (err, info) => {
3946
- if (err) return callback(err);
3947
- return callback(
3948
- null,
3949
- fromManagedItem(/** @type {string} */ (info))
3950
- );
3951
- });
3952
- }
3953
- }
3954
- }
3955
- for (const managedPath of this.managedPathsWithSlash) {
3956
- if (path.startsWith(managedPath)) {
3957
- const managedItem = getManagedItem(managedPath, child);
3958
- if (managedItem) {
3959
- // construct timestampHash from managed info
3960
- return this.managedItemQueue.add(managedItem, (err, info) => {
3961
- if (err) return callback(err);
3962
- return callback(
3963
- null,
3964
- fromManagedItem(/** @type {string} */ (info))
3965
- );
3966
- });
3967
- }
3968
- }
3969
- }
3970
-
3971
- lstatReadlinkAbsolute(this.fs, child, (err, _stat) => {
3972
- if (err) return callback(err);
3973
-
3974
- const stat = /** @type {IStats | string} */ (_stat);
3975
-
3976
- if (typeof stat === "string") {
3977
- return fromSymlink(child, stat, callback);
3978
- }
3979
-
3980
- if (stat.isFile()) {
3981
- return fromFile(child, stat, callback);
3982
- }
3983
- if (stat.isDirectory()) {
3984
- return fromDirectory(child, stat, callback);
3985
- }
3986
- callback(null, null);
3987
- });
3988
- },
3989
- (err, results) => {
3990
- if (err) return callback(err);
3991
- const result = reduce(files, /** @type {ItemType[]} */ (results));
3992
- callback(null, result);
3993
- }
3994
- );
3995
- });
3996
- }
3997
-
3998
- /**
3999
- * @private
4000
- * @type {Processor<string, ContextFileSystemInfoEntry>}
4001
- */
4002
- _readContextTimestamp(path, callback) {
4003
- this._readContext(
4004
- {
4005
- path,
4006
- fromImmutablePath: () =>
4007
- /** @type {ContextFileSystemInfoEntry | FileSystemInfoEntry | "ignore" | null} */
4008
- (null),
4009
- fromManagedItem: (info) => ({
4010
- safeTime: 0,
4011
- timestampHash: info
4012
- }),
4013
- fromSymlink: (file, target, callback) => {
4014
- callback(
4015
- null,
4016
- /** @type {ContextFileSystemInfoEntry} */
4017
- ({
4018
- timestampHash: target,
4019
- symlinks: new Set([target])
4020
- })
4021
- );
4022
- },
4023
- fromFile: (file, stat, callback) => {
4024
- // Prefer the cached value over our new stat to report consistent results
4025
- const cache = this._fileTimestamps.get(file);
4026
- if (cache !== undefined && !isExistenceOnly(cache)) {
4027
- return callback(
4028
- null,
4029
- cache === "ignore"
4030
- ? null
4031
- : /** @type {FileSystemInfoEntry | null} */ (cache)
4032
- );
4033
- }
4034
-
4035
- const mtime = Number(stat.mtime);
4036
-
4037
- if (mtime) applyMtime(mtime);
4038
-
4039
- /** @type {FileSystemInfoEntry} */
4040
- const ts = {
4041
- safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
4042
- timestamp: mtime
4043
- };
4044
-
4045
- this._fileTimestamps.set(file, ts);
4046
- this._cachedDeprecatedFileTimestamps = undefined;
4047
- callback(null, ts);
4048
- },
4049
- fromDirectory: (directory, stat, callback) => {
4050
- this.contextTimestampQueue.increaseParallelism();
4051
- this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => {
4052
- this.contextTimestampQueue.decreaseParallelism();
4053
- callback(err, tsEntry);
4054
- });
4055
- },
4056
- reduce: (files, tsEntries) => {
4057
- /** @type {undefined | Symlinks} */
4058
- let symlinks;
4059
-
4060
- const hash = createHash(this._hashFunction);
4061
-
4062
- for (const file of files) hash.update(file);
4063
- let safeTime = 0;
4064
- for (const _e of tsEntries) {
4065
- if (!_e) {
4066
- hash.update("n");
4067
- continue;
4068
- }
4069
- const entry =
4070
- /** @type {FileSystemInfoEntry | ContextFileSystemInfoEntry} */
4071
- (_e);
4072
- if (/** @type {FileSystemInfoEntry} */ (entry).timestamp) {
4073
- hash.update("f");
4074
- hash.update(
4075
- `${/** @type {FileSystemInfoEntry} */ (entry).timestamp}`
4076
- );
4077
- } else if (
4078
- /** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash
4079
- ) {
4080
- hash.update("d");
4081
- hash.update(
4082
- `${/** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash}`
4083
- );
4084
- }
4085
- if (
4086
- /** @type {ContextFileSystemInfoEntry} */
4087
- (entry).symlinks !== undefined
4088
- ) {
4089
- if (symlinks === undefined) symlinks = new Set();
4090
- addAll(
4091
- /** @type {ContextFileSystemInfoEntry} */ (entry).symlinks,
4092
- symlinks
4093
- );
4094
- }
4095
- if (entry.safeTime) {
4096
- safeTime = Math.max(safeTime, entry.safeTime);
4097
- }
4098
- }
4099
-
4100
- const digest = hash.digest("hex");
4101
- /** @type {ContextFileSystemInfoEntry} */
4102
- const result = {
4103
- safeTime,
4104
- timestampHash: digest
4105
- };
4106
- if (symlinks) result.symlinks = symlinks;
4107
- return result;
4108
- }
4109
- },
4110
- (err, result) => {
4111
- if (err) return callback(/** @type {WebpackError} */ (err));
4112
- this._contextTimestamps.set(path, result);
4113
- this._cachedDeprecatedContextTimestamps = undefined;
4114
-
4115
- callback(null, result);
4116
- }
4117
- );
4118
- }
4119
-
4120
- /**
4121
- * Resolve context timestamp.
4122
- * @private
4123
- * @param {ContextFileSystemInfoEntry} entry entry
4124
- * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback
4125
- * @returns {void}
4126
- */
4127
- _resolveContextTimestamp(entry, callback) {
4128
- /** @type {string[]} */
4129
- const hashes = [];
4130
- let safeTime = 0;
4131
- // Skip already-visited symlink targets so cyclic pnpm/peer-variant graphs terminate (#21084).
4132
- const seen = new Set(entry.symlinks);
4133
- processAsyncTree(
4134
- /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
4135
- 10,
4136
- (target, push, callback) => {
4137
- this._getUnresolvedContextTimestamp(target, (err, entry) => {
4138
- if (err) return callback(err);
4139
- if (entry && entry !== "ignore") {
4140
- hashes.push(/** @type {string} */ (entry.timestampHash));
4141
- if (entry.safeTime) {
4142
- safeTime = Math.max(safeTime, entry.safeTime);
4143
- }
4144
- if (entry.symlinks !== undefined) {
4145
- for (const target of entry.symlinks) {
4146
- if (!seen.has(target)) {
4147
- seen.add(target);
4148
- push(target);
4149
- }
4150
- }
4151
- }
4152
- }
4153
- callback();
4154
- });
4155
- },
4156
- (err) => {
4157
- if (err) return callback(/** @type {WebpackError} */ (err));
4158
- const hash = createHash(this._hashFunction);
4159
- hash.update(/** @type {string} */ (entry.timestampHash));
4160
- if (entry.safeTime) {
4161
- safeTime = Math.max(safeTime, entry.safeTime);
4162
- }
4163
- hashes.sort();
4164
- for (const h of hashes) {
4165
- hash.update(h);
4166
- }
4167
- callback(
4168
- null,
4169
- (entry.resolved = {
4170
- safeTime,
4171
- timestampHash: hash.digest("hex")
4172
- })
4173
- );
4174
- }
4175
- );
4176
- }
4177
-
4178
- /**
4179
- * @private
4180
- * @type {Processor<string, ContextHash>}
4181
- */
4182
- _readContextHash(path, callback) {
4183
- this._readContext(
4184
- {
4185
- path,
4186
- fromImmutablePath: () => /** @type {ContextHash | ""} */ (""),
4187
- fromManagedItem: (info) => info || "",
4188
- fromSymlink: (file, target, callback) => {
4189
- callback(
4190
- null,
4191
- /** @type {ContextHash} */
4192
- ({
4193
- hash: target,
4194
- symlinks: new Set([target])
4195
- })
4196
- );
4197
- },
4198
- fromFile: (file, stat, callback) =>
4199
- this.getFileHash(file, (err, hash) => {
4200
- callback(err, hash || "");
4201
- }),
4202
- fromDirectory: (directory, stat, callback) => {
4203
- this.contextHashQueue.increaseParallelism();
4204
- this._getUnresolvedContextHash(directory, (err, hash) => {
4205
- this.contextHashQueue.decreaseParallelism();
4206
- callback(err, hash || "");
4207
- });
4208
- },
4209
- /**
4210
- * Returns reduced hash.
4211
- * @param {string[]} files files
4212
- * @param {(string | ContextHash | null)[]} fileHashes hashes
4213
- * @returns {ContextHash} reduced hash
4214
- */
4215
- reduce: (files, fileHashes) => {
4216
- /** @type {undefined | Symlinks} */
4217
- let symlinks;
4218
- const hash = createHash(this._hashFunction);
4219
-
4220
- for (const file of files) hash.update(file);
4221
- for (const entry of fileHashes) {
4222
- // null for unsupported entry kinds (FIFO, socket); skip like the tsh reduce
4223
- if (!entry) {
4224
- continue;
4225
- } else if (typeof entry === "string") {
4226
- hash.update(entry);
4227
- } else {
4228
- if (entry.hash) hash.update(entry.hash);
4229
- if (entry.symlinks) {
4230
- if (symlinks === undefined) symlinks = new Set();
4231
- addAll(entry.symlinks, symlinks);
4232
- }
4233
- }
4234
- }
4235
-
4236
- /** @type {ContextHash} */
4237
- const result = {
4238
- hash: hash.digest("hex")
4239
- };
4240
- if (symlinks) result.symlinks = symlinks;
4241
- return result;
4242
- }
4243
- },
4244
- (err, _result) => {
4245
- if (err) return callback(/** @type {WebpackError} */ (err));
4246
- const result = /** @type {ContextHash} */ (_result);
4247
- this._contextHashes.set(path, result);
4248
- return callback(null, result);
4249
- }
4250
- );
4251
- }
4252
-
4253
- /**
4254
- * Resolve context hash.
4255
- * @private
4256
- * @param {ContextHash} entry context hash
4257
- * @param {(err: WebpackError | null, contextHash?: string) => void} callback callback
4258
- * @returns {void}
4259
- */
4260
- _resolveContextHash(entry, callback) {
4261
- /** @type {string[]} */
4262
- const hashes = [];
4263
- // Skip already-visited symlink targets so cyclic pnpm/peer-variant graphs terminate (#21084).
4264
- const seen = new Set(entry.symlinks);
4265
- processAsyncTree(
4266
- /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
4267
- 10,
4268
- (target, push, callback) => {
4269
- this._getUnresolvedContextHash(target, (err, hash) => {
4270
- if (err) return callback(err);
4271
- if (hash) {
4272
- hashes.push(hash.hash);
4273
- if (hash.symlinks !== undefined) {
4274
- for (const target of hash.symlinks) {
4275
- if (!seen.has(target)) {
4276
- seen.add(target);
4277
- push(target);
4278
- }
4279
- }
4280
- }
4281
- }
4282
- callback();
4283
- });
4284
- },
4285
- (err) => {
4286
- if (err) return callback(/** @type {WebpackError} */ (err));
4287
- const hash = createHash(this._hashFunction);
4288
- hash.update(entry.hash);
4289
- hashes.sort();
4290
- for (const h of hashes) {
4291
- hash.update(h);
4292
- }
4293
- callback(null, (entry.resolved = hash.digest("hex")));
4294
- }
4295
- );
4296
- }
4297
-
4298
- /**
4299
- * @private
4300
- * @type {Processor<string, ContextTimestampAndHash>}
4301
- */
4302
- _readContextTimestampAndHash(path, callback) {
4303
- /**
4304
- * Processes the provided timestamp.
4305
- * @param {ContextTimestamp} timestamp timestamp
4306
- * @param {ContextHash | null} hash hash
4307
- */
4308
- const finalize = (timestamp, hash) => {
4309
- // Merging two `null` reads yields `{}`, which reads as "exists, no hash" (#21636)
4310
- const result =
4311
- /** @type {ContextTimestampAndHash} */
4312
- (
4313
- hash === null || timestamp === "ignore"
4314
- ? hash
4315
- : { ...timestamp, ...hash }
4316
- );
4317
- this._contextTshs.set(path, result);
4318
- callback(null, result);
4319
- };
4320
- const cachedHash = this._contextHashes.get(path);
4321
- const cachedTimestamp = this._contextTimestamps.get(path);
4322
- if (cachedHash !== undefined) {
4323
- if (cachedTimestamp !== undefined) {
4324
- finalize(cachedTimestamp, cachedHash);
4325
- } else {
4326
- this.contextTimestampQueue.add(path, (err, entry) => {
4327
- if (err) return callback(err);
4328
- finalize(
4329
- /** @type {ContextFileSystemInfoEntry} */
4330
- (entry),
4331
- cachedHash
4332
- );
4333
- });
4334
- }
4335
- } else if (cachedTimestamp !== undefined) {
4336
- this.contextHashQueue.add(path, (err, entry) => {
4337
- if (err) return callback(err);
4338
- finalize(cachedTimestamp, /** @type {ContextHash} */ (entry));
4339
- });
4340
- } else {
4341
- this._readContext(
4342
- {
4343
- path,
4344
- fromImmutablePath: () =>
4345
- /** @type {ContextTimestampAndHash | Omit<ContextTimestampAndHash, "safeTime"> | string | null} */ (
4346
- null
4347
- ),
4348
- fromManagedItem: (info) => ({
4349
- safeTime: 0,
4350
- timestampHash: info,
4351
- hash: info || ""
4352
- }),
4353
- fromSymlink: (file, target, callback) => {
4354
- callback(null, {
4355
- timestampHash: target,
4356
- hash: target,
4357
- symlinks: new Set([target])
4358
- });
4359
- },
4360
- fromFile: (file, stat, callback) => {
4361
- this._getFileTimestampAndHash(file, callback);
4362
- },
4363
- fromDirectory: (directory, stat, callback) => {
4364
- this.contextTshQueue.increaseParallelism();
4365
- this.contextTshQueue.add(directory, (err, result) => {
4366
- this.contextTshQueue.decreaseParallelism();
4367
- callback(err, result);
4368
- });
4369
- },
4370
- /**
4371
- * Returns tsh.
4372
- * @param {string[]} files files
4373
- * @param {(Partial<TimestampAndHash> & Partial<ContextTimestampAndHash> | string | null)[]} results results
4374
- * @returns {ContextTimestampAndHash} tsh
4375
- */
4376
- reduce: (files, results) => {
4377
- /** @type {undefined | Symlinks} */
4378
- let symlinks;
4379
-
4380
- const tsHash = createHash(this._hashFunction);
4381
- const hash = createHash(this._hashFunction);
4382
-
4383
- for (const file of files) {
4384
- tsHash.update(file);
4385
- hash.update(file);
4386
- }
4387
- let safeTime = 0;
4388
- for (const entry of results) {
4389
- if (!entry) {
4390
- tsHash.update("n");
4391
- continue;
4392
- }
4393
- if (typeof entry === "string") {
4394
- tsHash.update("n");
4395
- hash.update(entry);
4396
- continue;
4397
- }
4398
- if (entry.timestamp) {
4399
- tsHash.update("f");
4400
- tsHash.update(`${entry.timestamp}`);
4401
- } else if (entry.timestampHash) {
4402
- tsHash.update("d");
4403
- tsHash.update(`${entry.timestampHash}`);
4404
- }
4405
- if (entry.symlinks !== undefined) {
4406
- if (symlinks === undefined) symlinks = new Set();
4407
- addAll(entry.symlinks, symlinks);
4408
- }
4409
- if (entry.safeTime) {
4410
- safeTime = Math.max(safeTime, entry.safeTime);
4411
- }
4412
- hash.update(/** @type {string} */ (entry.hash));
4413
- }
4414
-
4415
- /** @type {ContextTimestampAndHash} */
4416
- const result = {
4417
- safeTime,
4418
- timestampHash: tsHash.digest("hex"),
4419
- hash: hash.digest("hex")
4420
- };
4421
- if (symlinks) result.symlinks = symlinks;
4422
- return result;
4423
- }
4424
- },
4425
- (err, _result) => {
4426
- if (err) return callback(/** @type {WebpackError} */ (err));
4427
- const result = /** @type {ContextTimestampAndHash} */ (_result);
4428
- this._contextTshs.set(path, result);
4429
- return callback(null, result);
4430
- }
4431
- );
4432
- }
4433
- }
4434
-
4435
- /**
4436
- * Resolve context tsh.
4437
- * @private
4438
- * @param {ContextTimestampAndHash} entry entry
4439
- * @param {ProcessorCallback<ResolvedContextTimestampAndHash>} callback callback
4440
- * @returns {void}
4441
- */
4442
- _resolveContextTsh(entry, callback) {
4443
- /** @type {string[]} */
4444
- const hashes = [];
4445
- /** @type {string[]} */
4446
- const tsHashes = [];
4447
- let safeTime = 0;
4448
- // Skip already-visited symlink targets so cyclic pnpm/peer-variant graphs terminate (#21084).
4449
- const seen = new Set(entry.symlinks);
4450
- processAsyncTree(
4451
- /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
4452
- 10,
4453
- (target, push, callback) => {
4454
- this._getUnresolvedContextTsh(target, (err, entry) => {
4455
- if (err) return callback(err);
4456
- if (entry) {
4457
- hashes.push(entry.hash);
4458
- if (entry.timestampHash) tsHashes.push(entry.timestampHash);
4459
- if (entry.safeTime) {
4460
- safeTime = Math.max(safeTime, entry.safeTime);
4461
- }
4462
- if (entry.symlinks !== undefined) {
4463
- for (const target of entry.symlinks) {
4464
- if (!seen.has(target)) {
4465
- seen.add(target);
4466
- push(target);
4467
- }
4468
- }
4469
- }
4470
- }
4471
- callback();
4472
- });
4473
- },
4474
- (err) => {
4475
- if (err) return callback(/** @type {WebpackError} */ (err));
4476
- const hash = createHash(this._hashFunction);
4477
- const tsHash = createHash(this._hashFunction);
4478
- hash.update(entry.hash);
4479
- if (entry.timestampHash) tsHash.update(entry.timestampHash);
4480
- if (entry.safeTime) {
4481
- safeTime = Math.max(safeTime, entry.safeTime);
4482
- }
4483
- hashes.sort();
4484
- for (const h of hashes) {
4485
- hash.update(h);
4486
- }
4487
- tsHashes.sort();
4488
- for (const h of tsHashes) {
4489
- tsHash.update(h);
4490
- }
4491
- callback(
4492
- null,
4493
- (entry.resolved = {
4494
- safeTime,
4495
- timestampHash: tsHash.digest("hex"),
4496
- hash: hash.digest("hex")
4497
- })
4498
- );
4499
- }
4500
- );
4501
- }
4502
-
4503
- /**
4504
- * @private
4505
- * @type {Processor<string, Set<string>>}
4506
- */
4507
- _getManagedItemDirectoryInfo(path, callback) {
4508
- this.fs.readdir(path, (err, elements) => {
4509
- if (err) {
4510
- if (err.code === "ENOENT" || err.code === "ENOTDIR") {
4511
- return callback(null, EMPTY_SET);
4512
- }
4513
- return callback(/** @type {WebpackError} */ (err));
4514
- }
4515
- const set = new Set(
4516
- /** @type {string[]} */
4517
- (elements).map((element) => join(this.fs, path, element))
4518
- );
4519
- callback(null, set);
4520
- });
4521
- }
4522
-
4523
- /**
4524
- * @private
4525
- * @type {Processor<string, string>}
4526
- */
4527
- _getManagedItemInfo(path, callback) {
4528
- const dir = dirname(this.fs, path);
4529
- this.managedItemDirectoryQueue.add(dir, (err, elements) => {
4530
- if (err) {
4531
- return callback(err);
4532
- }
4533
- if (!(/** @type {Set<string>} */ (elements).has(path))) {
4534
- // file or directory doesn't exist
4535
- this._managedItems.set(path, "*missing");
4536
- return callback(null, "*missing");
4537
- }
4538
- // something exists
4539
- // it may be a file or directory
4540
- if (
4541
- path.endsWith("node_modules") &&
4542
- (path.endsWith("/node_modules") || path.endsWith("\\node_modules"))
4543
- ) {
4544
- // we are only interested in existence of this special directory
4545
- this._managedItems.set(path, "*node_modules");
4546
- return callback(null, "*node_modules");
4547
- }
4548
-
4549
- // we assume it's a directory, as files shouldn't occur in managed paths
4550
- const packageJsonPath = join(this.fs, path, "package.json");
4551
- this.fs.readFile(packageJsonPath, (err, content) => {
4552
- if (err) {
4553
- if (err.code === "ENOENT" || err.code === "ENOTDIR") {
4554
- // no package.json or path is not a directory
4555
- this.fs.readdir(path, (err, elements) => {
4556
- if (
4557
- !err &&
4558
- /** @type {string[]} */ (elements).length === 1 &&
4559
- /** @type {string[]} */ (elements)[0] === "node_modules"
4560
- ) {
4561
- // This is only a grouping folder e.g. used by yarn
4562
- // we are only interested in existence of this special directory
4563
- this._managedItems.set(path, "*nested");
4564
- return callback(null, "*nested");
4565
- }
4566
- /** @type {Logger} */
4567
- (this.logger).warn(
4568
- `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)`
4569
- );
4570
- return callback();
4571
- });
4572
- return;
4573
- }
4574
- return callback(/** @type {WebpackError} */ (err));
4575
- }
4576
- /** @type {JsonObject} */
4577
- let data;
4578
- try {
4579
- data = JSON.parse(/** @type {Buffer} */ (content).toString("utf8"));
4580
- } catch (parseErr) {
4581
- return callback(/** @type {WebpackError} */ (parseErr));
4582
- }
4583
- if (!data.name) {
4584
- /** @type {Logger} */
4585
- (this.logger).warn(
4586
- `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)`
4587
- );
4588
- return callback();
4589
- }
4590
- const info = `${data.name || ""}@${data.version || ""}`;
4591
- this._managedItems.set(path, info);
4592
- callback(null, info);
4593
- });
4594
- });
4595
- }
4596
-
4597
- getDeprecatedFileTimestamps() {
4598
- if (this._cachedDeprecatedFileTimestamps !== undefined) {
4599
- return this._cachedDeprecatedFileTimestamps;
4600
- }
4601
- /** @type {Map<string, number | null>} */
4602
- const map = new Map();
4603
- for (const [path, info] of this._fileTimestamps) {
4604
- if (info) {
4605
- const safeTime =
4606
- typeof info === "object"
4607
- ? /** @type {Partial<FileSystemInfoEntry>} */ (info).safeTime
4608
- : undefined;
4609
- map.set(path, safeTime === undefined ? null : safeTime);
4610
- }
4611
- }
4612
- return (this._cachedDeprecatedFileTimestamps = map);
4613
- }
4614
-
4615
- getDeprecatedContextTimestamps() {
4616
- if (this._cachedDeprecatedContextTimestamps !== undefined) {
4617
- return this._cachedDeprecatedContextTimestamps;
4618
- }
4619
- /** @type {Map<string, number | null>} */
4620
- const map = new Map();
4621
- for (const [path, info] of this._contextTimestamps) {
4622
- if (info) {
4623
- const safeTime =
4624
- typeof info === "object"
4625
- ? /** @type {Partial<ContextFileSystemInfoEntry>} */ (info).safeTime
4626
- : undefined;
4627
- map.set(path, safeTime === undefined ? null : safeTime);
4628
- }
4629
- }
4630
- return (this._cachedDeprecatedContextTimestamps = map);
4631
- }
4632
- }
4633
-
4634
- FileSystemInfo.Snapshot = Snapshot;
4635
-
4636
- module.exports = FileSystemInfo;
8
+ // TODO in the next major release: remove
9
+ // Some old plugins use `require("webpack/lib/FileSystemInfo")`, in the next major release developer should migrate to `compiler.webpack.FileSystemInfo`
10
+ module.exports = require("./fs/FileSystemInfo");