From 7123369f04318356bb6d133270161ff90002ef2f Mon Sep 17 00:00:00 2001 From: ahabhgk Date: Thu, 14 Nov 2024 18:04:27 +0800 Subject: [PATCH] refactor: use asset filename new type --- crates/rspack_binding_values/src/asset.rs | 4 +- crates/rspack_binding_values/src/chunk.rs | 5 +- .../src/compilation/mod.rs | 27 +- crates/rspack_core/src/chunk.rs | 15 +- crates/rspack_core/src/chunk_group.rs | 27 +- crates/rspack_core/src/compiler/assets.rs | 294 ++++++++++++++++++ .../rspack_core/src/compiler/compilation.rs | 222 +------------ crates/rspack_core/src/compiler/mod.rs | 15 +- .../src/compiler/module_executor/execute.rs | 7 +- .../src/compiler/module_executor/mod.rs | 5 +- .../src/compiler/{hmr.rs => rebuild.rs} | 0 crates/rspack_core/src/stats/mod.rs | 27 +- crates/rspack_core/src/stats/utils.rs | 1 + crates/rspack_plugin_asset/src/lib.rs | 2 +- crates/rspack_plugin_copy/src/lib.rs | 6 +- .../src/plugin/impl_plugin_for_css_plugin.rs | 2 +- .../src/mapped_assets_cache.rs | 14 +- .../src/source_map_dev_tool_plugin.rs | 42 +-- .../src/lib_manifest_plugin.rs | 2 +- .../rspack_plugin_extract_css/src/plugin.rs | 4 +- crates/rspack_plugin_hmr/src/lib.rs | 10 +- crates/rspack_plugin_html/src/asset.rs | 2 +- crates/rspack_plugin_html/src/plugin.rs | 8 +- .../src/plugin/impl_plugin_for_js_plugin.rs | 2 +- .../src/plugin/module_concatenation_plugin.rs | 10 +- .../src/lib.rs | 2 +- .../src/lib.rs | 2 +- crates/rspack_plugin_size_limits/src/lib.rs | 18 +- .../rspack_plugin_swc_js_minimizer/src/lib.rs | 2 +- crates/rspack_plugin_wasm/src/wasm_plugin.rs | 2 +- 30 files changed, 447 insertions(+), 332 deletions(-) create mode 100644 crates/rspack_core/src/compiler/assets.rs rename crates/rspack_core/src/compiler/{hmr.rs => rebuild.rs} (100%) diff --git a/crates/rspack_binding_values/src/asset.rs b/crates/rspack_binding_values/src/asset.rs index 615e1f1485a..219fb78fdd8 100644 --- a/crates/rspack_binding_values/src/asset.rs +++ b/crates/rspack_binding_values/src/asset.rs @@ -8,7 +8,7 @@ pub struct JsAssetInfoRelated { impl From for rspack_core::AssetInfoRelated { fn from(i: JsAssetInfoRelated) -> Self { Self { - source_map: i.source_map, + source_map: i.source_map.map(Into::into), } } } @@ -83,7 +83,7 @@ pub struct JsAsset { impl From for JsAssetInfoRelated { fn from(related: rspack_core::AssetInfoRelated) -> Self { Self { - source_map: related.source_map, + source_map: related.source_map.map(|f| f.to_string()), } } } diff --git a/crates/rspack_binding_values/src/chunk.rs b/crates/rspack_binding_values/src/chunk.rs index 0402e4738ef..411a7458e38 100644 --- a/crates/rspack_binding_values/src/chunk.rs +++ b/crates/rspack_binding_values/src/chunk.rs @@ -29,9 +29,10 @@ pub struct JsChunk { impl JsChunk { pub fn from(chunk: &rspack_core::Chunk, compilation: &Compilation) -> Self { - let mut files = Vec::from_iter(chunk.files().iter().cloned()); + let mut files = Vec::from_iter(chunk.files().iter().map(|file| file.to_string())); files.sort_unstable(); - let mut auxiliary_files = Vec::from_iter(chunk.auxiliary_files().iter().cloned()); + let mut auxiliary_files = + Vec::from_iter(chunk.auxiliary_files().iter().map(|file| file.to_string())); auxiliary_files.sort_unstable(); Self { diff --git a/crates/rspack_binding_values/src/compilation/mod.rs b/crates/rspack_binding_values/src/compilation/mod.rs index e1a65c5549f..65969eb8953 100644 --- a/crates/rspack_binding_values/src/compilation/mod.rs +++ b/crates/rspack_binding_values/src/compilation/mod.rs @@ -10,6 +10,7 @@ use entries::JsEntries; use napi_derive::napi; use rspack_collections::IdentifierSet; use rspack_core::rspack_sources::BoxSource; +use rspack_core::AssetFilename; use rspack_core::AssetInfo; use rspack_core::ChunkUkey; use rspack_core::Compilation; @@ -124,7 +125,7 @@ impl JsCompilation { for (filename, asset) in compilation.assets() { assets.push(JsAsset { - name: filename.clone(), + name: filename.to_string(), info: asset.info.clone().into(), }); } @@ -136,7 +137,7 @@ impl JsCompilation { pub fn get_asset(&self, name: String) -> Result> { let compilation = self.as_ref()?; - match compilation.assets().get(&name) { + match compilation.assets().get(name.as_str()) { Some(asset) => Ok(Some(JsAsset { name, info: asset.info.clone().into(), @@ -151,7 +152,7 @@ impl JsCompilation { compilation .assets() - .get(&name) + .get(name.as_str()) .and_then(|v| v.source.as_ref().map(|s| s.to_js_compat_source())) .transpose() } @@ -267,7 +268,7 @@ impl JsCompilation { let compilation = self.as_mut()?; let source: BoxSource = source.into(); - match compilation.assets_mut().entry(name) { + match compilation.assets_mut().entry(name.into()) { std::collections::hash_map::Entry::Occupied(mut e) => e.get_mut().set_source(Some(source)), std::collections::hash_map::Entry::Vacant(e) => { e.insert(rspack_core::CompilationAsset::from(source)); @@ -282,7 +283,7 @@ impl JsCompilation { compilation .assets_mut() - .entry(name) + .entry(name.into()) .and_modify(|a| a.set_source(None)); Ok(()) } @@ -296,8 +297,7 @@ impl JsCompilation { .assets() .iter() .filter(|(_, asset)| asset.get_source().is_some()) - .map(|(filename, _)| filename) - .cloned() + .map(|(filename, _)| filename.to_string()) .collect(), ) } @@ -306,7 +306,7 @@ impl JsCompilation { pub fn has_asset(&self, name: String) -> Result { let compilation = self.as_ref()?; - Ok(compilation.assets().contains_key(&name)) + Ok(compilation.assets().contains_key(name.as_str())) } #[napi] @@ -318,6 +318,7 @@ impl JsCompilation { module: String, ) -> Result<()> { let compilation = self.as_mut()?; + let filename: AssetFilename = filename.into(); compilation.emit_asset( filename.clone(), @@ -342,7 +343,7 @@ impl JsCompilation { let compilation = self.as_mut()?; compilation.emit_asset( - filename, + filename.into(), rspack_core::CompilationAsset::new(Some(source.into()), asset_info.into()), ); Ok(()) @@ -360,7 +361,7 @@ impl JsCompilation { pub fn rename_asset(&mut self, filename: String, new_name: String) -> Result<()> { let compilation = self.as_mut()?; - compilation.rename_asset(&filename, new_name); + compilation.rename_asset(&filename, new_name.into()); Ok(()) } @@ -665,7 +666,11 @@ impl JsCompilation { .into_iter() .map(|d| d.to_string_lossy().to_string()) .collect(), - assets: res.assets.into_iter().collect(), + assets: res + .assets + .into_iter() + .map(|file| file.to_string()) + .collect(), id: res.id, }; Ok(js_result) diff --git a/crates/rspack_core/src/chunk.rs b/crates/rspack_core/src/chunk.rs index 92b8c92a695..bd5eaeb65da 100644 --- a/crates/rspack_core/src/chunk.rs +++ b/crates/rspack_core/src/chunk.rs @@ -9,7 +9,8 @@ use rspack_hash::{RspackHash, RspackHashDigest}; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet, FxHasher}; use crate::{ - compare_chunk_group, merge_runtime, sort_group_by_index, ChunkGraph, ChunkGroupOrderKey, + compare_chunk_group, merge_runtime, sort_group_by_index, AssetFilename, ChunkGraph, + ChunkGroupOrderKey, }; use crate::{ChunkGroupByUkey, ChunkGroupUkey, ChunkUkey, SourceType}; use crate::{Compilation, EntryOptions, Filename, ModuleGraph, RuntimeSpec}; @@ -57,8 +58,8 @@ pub struct Chunk { prevent_integration: bool, groups: UkeySet, runtime: RuntimeSpec, - files: HashSet, - auxiliary_files: HashSet, + files: HashSet, + auxiliary_files: HashSet, chunk_reason: Option, rendered: bool, } @@ -148,11 +149,11 @@ impl Chunk { self.runtime = runtime; } - pub fn files(&self) -> &HashSet { + pub fn files(&self) -> &HashSet { &self.files } - pub fn add_file(&mut self, file: String) { + pub fn add_file(&mut self, file: AssetFilename) { self.files.insert(file); } @@ -160,11 +161,11 @@ impl Chunk { self.files.remove(file) } - pub fn auxiliary_files(&self) -> &HashSet { + pub fn auxiliary_files(&self) -> &HashSet { &self.auxiliary_files } - pub fn add_auxiliary_file(&mut self, auxiliary_file: String) { + pub fn add_auxiliary_file(&mut self, auxiliary_file: AssetFilename) { self.auxiliary_files.insert(auxiliary_file); } diff --git a/crates/rspack_core/src/chunk_group.rs b/crates/rspack_core/src/chunk_group.rs index 65a2406f75b..a2825ab7341 100644 --- a/crates/rspack_core/src/chunk_group.rs +++ b/crates/rspack_core/src/chunk_group.rs @@ -8,8 +8,8 @@ use rspack_error::{error, Result}; use rustc_hash::FxHashMap as HashMap; use crate::{ - compare_chunk_group, Chunk, ChunkByUkey, ChunkGroupByUkey, ChunkGroupUkey, DependencyLocation, - DynamicImportFetchPriority, Filename, ModuleLayer, + compare_chunk_group, AssetFilename, Chunk, ChunkByUkey, ChunkGroupByUkey, ChunkGroupUkey, + DependencyLocation, DynamicImportFetchPriority, Filename, ModuleLayer, }; use crate::{ChunkLoading, ChunkUkey, Compilation}; use crate::{LibraryOptions, ModuleIdentifier, PublicPath}; @@ -83,18 +83,17 @@ impl ChunkGroup { .copied() } - pub fn get_files(&self, chunk_by_ukey: &ChunkByUkey) -> Vec { - self - .chunks - .iter() - .flat_map(|chunk_ukey| { - chunk_by_ukey - .expect_get(chunk_ukey) - .files() - .iter() - .map(|file| file.to_string()) - }) - .collect() + pub fn get_files<'a>( + &self, + chunk_by_ukey: &'a ChunkByUkey, + ) -> impl Iterator + use<'a, '_> { + self.chunks.iter().flat_map(|chunk_ukey| { + chunk_by_ukey + .expect_get(chunk_ukey) + .files() + .iter() + .map(|file| file) + }) } pub(crate) fn connect_chunk(&mut self, chunk: &mut Chunk) { diff --git a/crates/rspack_core/src/compiler/assets.rs b/crates/rspack_core/src/compiler/assets.rs new file mode 100644 index 00000000000..213460e3263 --- /dev/null +++ b/crates/rspack_core/src/compiler/assets.rs @@ -0,0 +1,294 @@ +use std::borrow::Borrow; + +use rspack_sources::BoxSource; +use rustc_hash::{FxHashMap, FxHashSet}; + +#[derive(Clone, Default, PartialEq, Eq, Hash)] +pub struct AssetFilename(rspack_util::atom::Atom); + +impl AssetFilename { + pub fn new(s: S) -> Self + where + rspack_util::atom::Atom: From, + { + Self(rspack_util::atom::Atom::from(s)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::ops::Deref for AssetFilename { + type Target = str; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +macro_rules! impl_eq { + ($T:ty) => { + impl PartialEq<$T> for AssetFilename { + fn eq(&self, other: &$T) -> bool { + &**self == &**other + } + } + }; +} + +macro_rules! impl_from { + ($T:ty) => { + impl From<$T> for AssetFilename { + fn from(s: $T) -> Self { + Self::new(s) + } + } + }; +} + +impl PartialEq for AssetFilename { + fn eq(&self, other: &str) -> bool { + &**self == other + } +} + +impl_eq!(&'_ str); +impl_eq!(Box); +impl_eq!(std::sync::Arc); +impl_eq!(std::rc::Rc); +impl_eq!(std::borrow::Cow<'_, str>); +impl_eq!(String); + +impl_from!(&'_ str); +impl_from!(Box); +impl_from!(String); +impl_from!(std::borrow::Cow<'_, str>); + +impl AsRef for AssetFilename { + fn as_ref(&self) -> &str { + self + } +} + +impl Borrow for AssetFilename { + fn borrow(&self) -> &str { + self + } +} + +impl std::fmt::Debug for AssetFilename { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&**self, f) + } +} + +impl std::fmt::Display for AssetFilename { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(&**self, f) + } +} + +impl PartialOrd for AssetFilename { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for AssetFilename { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.as_str().cmp(other.as_str()) + } +} + +pub type CompilationAssets = FxHashMap; + +#[derive(Debug, Clone)] +pub struct CompilationAsset { + pub source: Option, + pub info: AssetInfo, +} + +impl From for CompilationAsset { + fn from(value: BoxSource) -> Self { + Self::new(Some(value), Default::default()) + } +} + +impl CompilationAsset { + pub fn new(source: Option, info: AssetInfo) -> Self { + Self { source, info } + } + + pub fn get_source(&self) -> Option<&BoxSource> { + self.source.as_ref() + } + + pub fn get_source_mut(&mut self) -> Option<&mut BoxSource> { + self.source.as_mut() + } + + pub fn set_source(&mut self, source: Option) { + self.source = source; + } + + pub fn get_info(&self) -> &AssetInfo { + &self.info + } + + pub fn get_info_mut(&mut self) -> &mut AssetInfo { + &mut self.info + } + + pub fn set_info(&mut self, info: AssetInfo) { + self.info = info; + } +} + +#[derive(Debug, Default, Clone)] +pub struct AssetInfo { + /// if the asset can be long term cached forever (contains a hash) + pub immutable: Option, + /// whether the asset is minimized + pub minimized: Option, + /// the value(s) of the full hash used for this asset + pub full_hash: FxHashSet, + /// the value(s) of the chunk hash used for this asset + pub chunk_hash: FxHashSet, + /// the value(s) of the module hash used for this asset + // pub module_hash: + /// the value(s) of the content hash used for this asset + pub content_hash: FxHashSet, + /// when asset was created from a source file (potentially transformed), the original filename relative to compilation context + pub source_filename: Option, + /// when asset was created from a source file (potentially transformed), it should be flagged as copied + pub copied: Option, + /// size in bytes, only set after asset has been emitted + // pub size: f64, + /// when asset is only used for development and doesn't count towards user-facing assets + pub development: Option, + /// when asset ships data for updating an existing application (HMR) + pub hot_module_replacement: Option, + /// when asset is javascript and an ESM + pub javascript_module: Option, + /// related object to other assets, keyed by type of relation (only points from parent to child) + pub related: AssetInfoRelated, + /// the asset version, emit can be skipped when both filename and version are the same + /// An empty string means no version, it will always emit + pub version: String, + /// unused local idents of the chunk + pub css_unused_idents: Option>, + /// Webpack: AssetInfo = KnownAssetInfo & Record + /// But Napi.rs does not support Intersectiont types. This is a hack to store the additional fields + /// in the rust struct and have the Js side to reshape and align with webpack. + /// Related: packages/rspack/src/Compilation.ts + pub extras: serde_json::Map, + /// whether this asset is over the size limit + pub is_over_size_limit: Option, +} + +impl AssetInfo { + pub fn with_minimized(mut self, v: Option) -> Self { + self.minimized = v; + self + } + + pub fn with_development(mut self, v: Option) -> Self { + self.development = v; + self + } + + pub fn with_hot_module_replacement(mut self, v: Option) -> Self { + self.hot_module_replacement = v; + self + } + + pub fn with_related(mut self, v: AssetInfoRelated) -> Self { + self.related = v; + self + } + + pub fn with_content_hashes(mut self, v: FxHashSet) -> Self { + self.content_hash = v; + self + } + + pub fn with_version(mut self, v: String) -> Self { + self.version = v; + self + } + + pub fn set_full_hash(&mut self, v: String) { + self.full_hash.insert(v); + } + + pub fn set_content_hash(&mut self, v: String) { + self.content_hash.insert(v); + } + + pub fn set_chunk_hash(&mut self, v: String) { + self.chunk_hash.insert(v); + } + + pub fn set_immutable(&mut self, v: Option) { + self.immutable = v; + } + + pub fn set_source_filename(&mut self, v: String) { + self.source_filename = Some(v); + } + + pub fn set_javascript_module(&mut self, v: bool) { + self.javascript_module = Some(v); + } + + pub fn set_css_unused_idents(&mut self, v: FxHashSet) { + self.css_unused_idents = Some(v); + } + + pub fn set_is_over_size_limit(&mut self, v: bool) { + self.is_over_size_limit = Some(v); + } + // another should have high priority than self + // self = { immutable:true} + // merge_another_asset({immutable: false}) + // self == { immutable: false} + // align with https://github.com/webpack/webpack/blob/899f06934391baede59da3dcd35b5ef51c675dbe/lib/Compilation.js#L4554 + pub fn merge_another_asset(&mut self, another: AssetInfo) { + // "another" first fields + self.minimized = another.minimized; + + self.source_filename = another.source_filename.or(self.source_filename.take()); + self.version = another.version; + self.related.merge_another(another.related); + + // merge vec fields + self.chunk_hash.extend(another.chunk_hash); + self.content_hash.extend(another.content_hash); + self.extras.extend(another.extras); + // self.full_hash.extend(another.full_hash.iter().cloned()); + // self.module_hash.extend(another.module_hash.iter().cloned()); + + // old first fields or truthy first fields + self.javascript_module = another.javascript_module.or(self.javascript_module.take()); + self.immutable = another.immutable.or(self.immutable); + self.development = another.development.or(self.development); + self.hot_module_replacement = another + .hot_module_replacement + .or(self.hot_module_replacement); + self.is_over_size_limit = another.is_over_size_limit.or(self.is_over_size_limit); + } +} + +#[derive(Debug, Default, Clone)] +pub struct AssetInfoRelated { + pub source_map: Option, +} + +impl AssetInfoRelated { + pub fn merge_another(&mut self, another: AssetInfoRelated) { + if let Some(source_map) = another.source_map { + self.source_map = Some(source_map); + } + } +} diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index 41f4540b6b0..31964b4b415 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -24,9 +24,10 @@ use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet, FxHasher}; use tracing::instrument; use super::{ - hmr::CompilationRecords, make::{make_module_graph, update_module_graph, MakeArtifact, MakeParam}, module_executor::ModuleExecutor, + rebuild::CompilationRecords, + AssetFilename, AssetInfo, CompilationAsset, CompilationAssets, }; use crate::{ build_chunk_graph::build_chunk_graph, @@ -156,8 +157,8 @@ pub struct Compilation { pub entrypoints: IndexMap, pub async_entrypoints: Vec, assets: CompilationAssets, - pub module_assets: IdentifierMap>, - pub emitted_assets: DashSet>, + pub module_assets: IdentifierMap>, + pub emitted_assets: DashSet>, diagnostics: Vec, logging: CompilationLogging, pub plugin_driver: SharedPluginDriver, @@ -554,7 +555,7 @@ impl Compilation { } }; self.emit_asset( - filename.to_owned(), + filename.into(), CompilationAsset { source: Some(new_source), info: new_info, @@ -563,7 +564,7 @@ impl Compilation { Ok(()) } - pub fn emit_asset(&mut self, filename: String, asset: CompilationAsset) { + pub fn emit_asset(&mut self, filename: AssetFilename, asset: CompilationAsset) { tracing::trace!("Emit asset {}", filename); if let Some(mut original) = self.assets.remove(&filename) && let Some(original_source) = &original.source @@ -607,7 +608,7 @@ impl Compilation { } } - pub fn rename_asset(&mut self, filename: &str, new_name: String) { + pub fn rename_asset(&mut self, filename: &str, new_name: AssetFilename) { if let Some(asset) = self.assets.remove(filename) { self.assets.insert(new_name.clone(), asset); self.chunk_by_ukey.iter_mut().for_each(|(_, chunk)| { @@ -966,7 +967,7 @@ impl Compilation { self.extend_diagnostics(diagnostics); for file_manifest in manifest { - let filename = file_manifest.filename().to_string(); + let filename = AssetFilename::from(file_manifest.filename); let current_chunk = self.chunk_by_ukey.expect_get_mut(&chunk_ukey); current_chunk.set_rendered(true); @@ -990,10 +991,6 @@ impl Compilation { } } - // TODO: add code_generated_modules in render_runtime_modules - for (identifier, _) in self.runtime_modules.iter() { - self.code_generated_modules.insert(*identifier); - } Ok(()) } @@ -1843,6 +1840,9 @@ impl Compilation { Ok((*runtime_module_identifier, source.clone())) }) .collect::>()?; + self + .code_generated_modules + .extend(self.runtime_modules.keys().copied()); Ok(()) } @@ -2021,198 +2021,6 @@ impl Compilation { } } -pub type CompilationAssets = HashMap; - -#[derive(Debug, Clone)] -pub struct CompilationAsset { - pub source: Option, - pub info: AssetInfo, -} - -impl From for CompilationAsset { - fn from(value: BoxSource) -> Self { - Self::new(Some(value), Default::default()) - } -} - -impl CompilationAsset { - pub fn new(source: Option, info: AssetInfo) -> Self { - Self { source, info } - } - - pub fn get_source(&self) -> Option<&BoxSource> { - self.source.as_ref() - } - - pub fn get_source_mut(&mut self) -> Option<&mut BoxSource> { - self.source.as_mut() - } - - pub fn set_source(&mut self, source: Option) { - self.source = source; - } - - pub fn get_info(&self) -> &AssetInfo { - &self.info - } - - pub fn get_info_mut(&mut self) -> &mut AssetInfo { - &mut self.info - } - - pub fn set_info(&mut self, info: AssetInfo) { - self.info = info; - } -} - -#[derive(Debug, Default, Clone)] -pub struct AssetInfo { - /// if the asset can be long term cached forever (contains a hash) - pub immutable: Option, - /// whether the asset is minimized - pub minimized: Option, - /// the value(s) of the full hash used for this asset - pub full_hash: HashSet, - /// the value(s) of the chunk hash used for this asset - pub chunk_hash: HashSet, - /// the value(s) of the module hash used for this asset - // pub module_hash: - /// the value(s) of the content hash used for this asset - pub content_hash: HashSet, - /// when asset was created from a source file (potentially transformed), the original filename relative to compilation context - pub source_filename: Option, - /// when asset was created from a source file (potentially transformed), it should be flagged as copied - pub copied: Option, - /// size in bytes, only set after asset has been emitted - // pub size: f64, - /// when asset is only used for development and doesn't count towards user-facing assets - pub development: Option, - /// when asset ships data for updating an existing application (HMR) - pub hot_module_replacement: Option, - /// when asset is javascript and an ESM - pub javascript_module: Option, - /// related object to other assets, keyed by type of relation (only points from parent to child) - pub related: AssetInfoRelated, - /// the asset version, emit can be skipped when both filename and version are the same - /// An empty string means no version, it will always emit - pub version: String, - /// unused local idents of the chunk - pub css_unused_idents: Option>, - /// Webpack: AssetInfo = KnownAssetInfo & Record - /// But Napi.rs does not support Intersectiont types. This is a hack to store the additional fields - /// in the rust struct and have the Js side to reshape and align with webpack. - /// Related: packages/rspack/src/Compilation.ts - pub extras: serde_json::Map, - /// whether this asset is over the size limit - pub is_over_size_limit: Option, -} - -impl AssetInfo { - pub fn with_minimized(mut self, v: Option) -> Self { - self.minimized = v; - self - } - - pub fn with_development(mut self, v: Option) -> Self { - self.development = v; - self - } - - pub fn with_hot_module_replacement(mut self, v: Option) -> Self { - self.hot_module_replacement = v; - self - } - - pub fn with_related(mut self, v: AssetInfoRelated) -> Self { - self.related = v; - self - } - - pub fn with_content_hashes(mut self, v: HashSet) -> Self { - self.content_hash = v; - self - } - - pub fn with_version(mut self, v: String) -> Self { - self.version = v; - self - } - - pub fn set_full_hash(&mut self, v: String) { - self.full_hash.insert(v); - } - - pub fn set_content_hash(&mut self, v: String) { - self.content_hash.insert(v); - } - - pub fn set_chunk_hash(&mut self, v: String) { - self.chunk_hash.insert(v); - } - - pub fn set_immutable(&mut self, v: Option) { - self.immutable = v; - } - - pub fn set_source_filename(&mut self, v: String) { - self.source_filename = Some(v); - } - - pub fn set_javascript_module(&mut self, v: bool) { - self.javascript_module = Some(v); - } - - pub fn set_css_unused_idents(&mut self, v: HashSet) { - self.css_unused_idents = Some(v); - } - - pub fn set_is_over_size_limit(&mut self, v: bool) { - self.is_over_size_limit = Some(v); - } - // another should have high priority than self - // self = { immutable:true} - // merge_another_asset({immutable: false}) - // self == { immutable: false} - // align with https://github.com/webpack/webpack/blob/899f06934391baede59da3dcd35b5ef51c675dbe/lib/Compilation.js#L4554 - pub fn merge_another_asset(&mut self, another: AssetInfo) { - // "another" first fields - self.minimized = another.minimized; - - self.source_filename = another.source_filename.or(self.source_filename.take()); - self.version = another.version; - self.related.merge_another(another.related); - - // merge vec fields - self.chunk_hash.extend(another.chunk_hash); - self.content_hash.extend(another.content_hash); - self.extras.extend(another.extras); - // self.full_hash.extend(another.full_hash.iter().cloned()); - // self.module_hash.extend(another.module_hash.iter().cloned()); - - // old first fields or truthy first fields - self.javascript_module = another.javascript_module.or(self.javascript_module.take()); - self.immutable = another.immutable.or(self.immutable); - self.development = another.development.or(self.development); - self.hot_module_replacement = another - .hot_module_replacement - .or(self.hot_module_replacement); - self.is_over_size_limit = another.is_over_size_limit.or(self.is_over_size_limit); - } -} - -#[derive(Debug, Default, Clone)] -pub struct AssetInfoRelated { - pub source_map: Option, -} - -impl AssetInfoRelated { - pub fn merge_another(&mut self, another: AssetInfoRelated) { - if let Some(source_map) = another.source_map { - self.source_map = Some(source_map); - } - } -} - /// level order, the impl is different from webpack, since we can't iterate a set and mutate it at /// the same time. pub fn assign_depths( @@ -2287,7 +2095,7 @@ pub fn set_depth_if_lower( #[derive(Debug, Clone)] pub struct RenderManifestEntry { pub source: BoxSource, - filename: String, + pub filename: AssetFilename, pub info: AssetInfo, // pub identifier: String, // hash?: string; @@ -2298,7 +2106,7 @@ pub struct RenderManifestEntry { impl RenderManifestEntry { pub fn new( source: BoxSource, - filename: String, + filename: AssetFilename, info: AssetInfo, auxiliary: bool, has_filename: bool, @@ -2316,10 +2124,6 @@ impl RenderManifestEntry { &self.source } - pub fn filename(&self) -> &str { - &self.filename - } - pub fn has_filename(&self) -> bool { self.has_filename } diff --git a/crates/rspack_core/src/compiler/mod.rs b/crates/rspack_core/src/compiler/mod.rs index 074e0f72e8d..0adbde65419 100644 --- a/crates/rspack_core/src/compiler/mod.rs +++ b/crates/rspack_core/src/compiler/mod.rs @@ -1,7 +1,9 @@ +mod assets; mod compilation; -mod hmr; mod make; mod module_executor; +mod rebuild; + use std::sync::Arc; use rspack_error::Result; @@ -13,9 +15,10 @@ use rspack_sources::BoxSource; use rustc_hash::FxHashMap as HashMap; use tracing::instrument; +pub use self::assets::*; pub use self::compilation::*; -pub use self::hmr::{collect_changed_modules, CompilationRecords}; pub use self::module_executor::{ExecuteModuleId, ExecutedRuntimeModule, ModuleExecutor}; +pub use self::rebuild::{collect_changed_modules, CompilationRecords}; use crate::incremental::IncrementalPasses; use crate::old_cache::Cache as OldCache; use crate::{ @@ -62,7 +65,7 @@ pub struct Compiler { pub old_cache: Arc, /// emitted asset versions /// the key of HashMap is filename, the value of HashMap is version - pub emitted_asset_versions: HashMap, + pub emitted_asset_versions: HashMap, } impl Compiler { @@ -271,8 +274,8 @@ impl Compiler { .iter() .filter_map(|(filename, _version)| { if !assets.contains_key(filename) { - let filename = filename.to_owned(); Some(async { + let filename = filename.as_str(); let filename = Utf8Path::new(&self.options.output.path).join(filename); let _ = self.output_filesystem.remove_file(&filename).await; }) @@ -304,7 +307,7 @@ impl Compiler { .incremental .contains(IncrementalPasses::EMIT_ASSETS) { - new_emitted_asset_versions.insert(filename.to_string(), asset.info.version.clone()); + new_emitted_asset_versions.insert(filename.clone(), asset.info.version.clone()); } if let Some(old_version) = self.emitted_asset_versions.get(filename) { @@ -396,7 +399,7 @@ impl Compiler { if need_write { self.output_filesystem.write(&file_path, &content).await?; - self.compilation.emitted_assets.insert(filename.to_string()); + self.compilation.emitted_assets.insert(filename.into()); } let info = AssetEmittedInfo { diff --git a/crates/rspack_core/src/compiler/module_executor/execute.rs b/crates/rspack_core/src/compiler/module_executor/execute.rs index 2c00f82fb16..c819074f34c 100644 --- a/crates/rspack_core/src/compiler/module_executor/execute.rs +++ b/crates/rspack_core/src/compiler/module_executor/execute.rs @@ -7,6 +7,7 @@ use rustc_hash::FxHashMap as HashMap; use rustc_hash::FxHashSet as HashSet; use tokio::sync::oneshot::Sender; +use crate::AssetFilename; use crate::{ compiler::make::repair::MakeTaskContext, utils::task_loop::{Task, TaskResult, TaskType}, @@ -37,7 +38,7 @@ pub struct ExecuteModuleResult { pub missing_dependencies: HashSet, pub build_dependencies: HashSet, pub code_generated_modules: IdentifierSet, - pub assets: HashSet, + pub assets: HashSet, pub id: ExecuteModuleId, } @@ -260,7 +261,7 @@ impl Task for ExecuteTask { { let filename = filename.filename(); compilation.emit_asset( - filename.to_owned(), + filename.into(), CompilationAsset::new(Some(source.clone()), asset_info.inner().clone()), ); } @@ -281,7 +282,7 @@ impl Task for ExecuteTask { module_assets .values() .flat_map(|m| m.iter().map(|i| i.to_owned()).collect_vec()) - .collect::>(), + .collect::>(), ); } let executed_runtime_modules = runtime_modules diff --git a/crates/rspack_core/src/compiler/module_executor/mod.rs b/crates/rspack_core/src/compiler/module_executor/mod.rs index e9954aa685b..ad720d57872 100644 --- a/crates/rspack_core/src/compiler/module_executor/mod.rs +++ b/crates/rspack_core/src/compiler/module_executor/mod.rs @@ -19,6 +19,7 @@ use self::{ overwrite::OverwriteTask, }; use super::make::{repair::MakeTaskContext, update_module_graph, MakeArtifact, MakeParam}; +use super::AssetFilename; use crate::incremental::Mutation; use crate::{ task_loop::run_task_loop_with_event, Compilation, CompilationAsset, Context, Dependency, @@ -32,8 +33,8 @@ pub struct ModuleExecutor { event_sender: Option>, stop_receiver: Option>, - assets: DashMap, - module_assets: IdentifierDashMap>, + assets: DashMap, + module_assets: IdentifierDashMap>, code_generated_modules: IdentifierDashSet, module_code_generated_modules: IdentifierDashMap, pub executed_runtime_modules: IdentifierDashMap, diff --git a/crates/rspack_core/src/compiler/hmr.rs b/crates/rspack_core/src/compiler/rebuild.rs similarity index 100% rename from crates/rspack_core/src/compiler/hmr.rs rename to crates/rspack_core/src/compiler/rebuild.rs diff --git a/crates/rspack_core/src/stats/mod.rs b/crates/rspack_core/src/stats/mod.rs index ddf0bfed057..a803b4b1253 100644 --- a/crates/rspack_core/src/stats/mod.rs +++ b/crates/rspack_core/src/stats/mod.rs @@ -48,9 +48,8 @@ impl<'compilation> Stats<'compilation> { impl Stats<'_> { pub fn get_assets(&self) -> (Vec, Vec) { - let mut compilation_file_to_chunks: HashMap<&String, Vec<&Chunk>> = HashMap::default(); - let mut compilation_file_to_auxiliary_chunks: HashMap<&String, Vec<&Chunk>> = - HashMap::default(); + let mut compilation_file_to_chunks: HashMap<&str, Vec<&Chunk>> = HashMap::default(); + let mut compilation_file_to_auxiliary_chunks: HashMap<&str, Vec<&Chunk>> = HashMap::default(); for chunk in self.compilation.chunk_by_ukey.values() { for file in chunk.files() { let chunks = compilation_file_to_chunks.entry(file).or_default(); @@ -65,7 +64,7 @@ impl Stats<'_> { } } - let mut assets: HashMap<&String, StatsAsset> = self + let mut assets: HashMap<&str, StatsAsset> = self .compilation .assets() .par_iter() @@ -75,14 +74,14 @@ impl Stats<'_> { if let Some(source_map) = &asset.info.related.source_map { related.push(StatsAssetInfoRelated { name: "sourceMap".into(), - value: [source_map.clone()].into(), + value: vec![source_map.to_string()], }) } ( - name, + name.as_str(), StatsAsset { r#type: "asset", - name: name.clone(), + name: name.to_string(), size: source.size() as f64, chunks: Vec::new(), chunk_names: Vec::new(), @@ -112,7 +111,7 @@ impl Stats<'_> { .collect::>(); for asset in self.compilation.assets().values() { if let Some(source_map) = &asset.get_info().related.source_map { - assets.remove(source_map); + assets.remove(source_map.as_str()); } } assets.par_iter_mut().for_each(|(name, asset)| { @@ -267,7 +266,7 @@ impl Stats<'_> { .par_bridge() .map(|c| -> Result<_> { let files: Vec<_> = { - let mut vec = c.files().iter().cloned().collect::>(); + let mut vec = c.files().iter().map(|f| f.to_string()).collect::>(); vec.sort_unstable(); vec }; @@ -277,7 +276,11 @@ impl Stats<'_> { .into_iter() .collect::(); - let mut auxiliary_files = c.auxiliary_files().iter().cloned().collect::>(); + let mut auxiliary_files = c + .auxiliary_files() + .iter() + .map(|f| f.to_string()) + .collect::>(); auxiliary_files.sort_unstable(); let chunk_modules = if options.chunk_modules { @@ -435,7 +438,7 @@ impl Stats<'_> { .map(|c| { let chunk = self.compilation.chunk_by_ukey.expect_get(c); chunk.files().par_iter().map(|file| StatsChunkGroupAsset { - name: file.clone(), + name: file.to_string(), size: get_asset_size(file, self.compilation), }) }) @@ -451,7 +454,7 @@ impl Stats<'_> { .auxiliary_files() .par_iter() .map(|file| StatsChunkGroupAsset { - name: file.clone(), + name: file.to_string(), size: get_asset_size(file, self.compilation), }) }) diff --git a/crates/rspack_core/src/stats/utils.rs b/crates/rspack_core/src/stats/utils.rs index 671a61e2ee3..85496551fa9 100644 --- a/crates/rspack_core/src/stats/utils.rs +++ b/crates/rspack_core/src/stats/utils.rs @@ -86,6 +86,7 @@ pub fn get_chunk_group_oreded_child_assets( .chunks .iter() .flat_map(|c| chunk_by_ukey.expect_get(c).files().clone()) + .map(|file| file.to_string()) .collect::>() }) .unique() diff --git a/crates/rspack_plugin_asset/src/lib.rs b/crates/rspack_plugin_asset/src/lib.rs index 0dcaada3eed..3cab581ddd0 100644 --- a/crates/rspack_plugin_asset/src/lib.rs +++ b/crates/rspack_plugin_asset/src/lib.rs @@ -595,7 +595,7 @@ async fn render_manifest( .inner(); RenderManifestEntry::new( source.clone(), - asset_filename.to_owned(), + asset_filename.into(), asset_info.to_owned(), true, true, diff --git a/crates/rspack_plugin_copy/src/lib.rs b/crates/rspack_plugin_copy/src/lib.rs index 45a08dffe3f..994910ab496 100644 --- a/crates/rspack_plugin_copy/src/lib.rs +++ b/crates/rspack_plugin_copy/src/lib.rs @@ -623,7 +623,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { copied_result.sort_unstable_by(|a, b| a.0.cmp(&b.0)); copied_result.into_iter().for_each(|(_priority, result)| { - if let Some(exist_asset) = compilation.assets_mut().get_mut(&result.filename) { + if let Some(exist_asset) = compilation.assets_mut().get_mut(result.filename.as_str()) { if !result.force { return; } @@ -645,7 +645,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { } compilation.emit_asset( - result.filename, + result.filename.into(), CompilationAsset { source: Some(Arc::new(result.source)), info: asset_info, @@ -722,7 +722,7 @@ fn set_info(target: &mut AssetInfo, info: Info) { if let Some(related) = info.related { target.related = AssetInfoRelated { - source_map: related.source_map, + source_map: related.source_map.map(Into::into), }; } diff --git a/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs b/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs index a0520d6c9a6..88ceedb3bf3 100644 --- a/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs +++ b/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs @@ -397,7 +397,7 @@ async fn render_manifest( } manifest.push(RenderManifestEntry::new( source.boxed(), - output_path, + output_path.into(), asset_info, false, false, diff --git a/crates/rspack_plugin_devtool/src/mapped_assets_cache.rs b/crates/rspack_plugin_devtool/src/mapped_assets_cache.rs index faf5b0c0ef8..9cd1acf1c82 100644 --- a/crates/rspack_plugin_devtool/src/mapped_assets_cache.rs +++ b/crates/rspack_plugin_devtool/src/mapped_assets_cache.rs @@ -1,12 +1,12 @@ use dashmap::DashMap; use futures::Future; -use rspack_core::CompilationAsset; +use rspack_core::{AssetFilename, CompilationAsset}; use rspack_error::{Error, Result}; use crate::MappedAsset; #[derive(Debug, Clone)] -pub struct MappedAssetsCache(DashMap); +pub struct MappedAssetsCache(DashMap); impl MappedAssetsCache { pub fn new() -> Self { @@ -15,17 +15,17 @@ impl MappedAssetsCache { pub async fn use_cache<'a, F, R>( &self, - assets: Vec<(&'a String, &'a CompilationAsset)>, + assets: Vec<(&'a AssetFilename, &'a CompilationAsset)>, map_assets: F, ) -> Result> where - F: FnOnce(Vec<(String, &'a CompilationAsset)>) -> R, + F: FnOnce(Vec<(AssetFilename, &'a CompilationAsset)>) -> R, R: Future, Error>> + Send + 'a, { let mut mapped_asstes: Vec = Vec::with_capacity(assets.len()); let mut vanilla_assets = Vec::with_capacity(assets.len()); for (filename, vanilla_asset) in assets { - if let Some((_, mapped_asset)) = self.0.remove(filename) { + if let Some((_, mapped_asset)) = self.0.remove(filename.as_str()) { if !vanilla_asset.info.version.is_empty() && vanilla_asset.info.version == mapped_asset.asset.1.info.version { @@ -33,7 +33,7 @@ impl MappedAssetsCache { continue; } } - vanilla_assets.push((filename.to_owned(), vanilla_asset)); + vanilla_assets.push((filename.clone(), vanilla_asset)); } mapped_asstes.extend(map_assets(vanilla_assets).await?); @@ -45,7 +45,7 @@ impl MappedAssetsCache { .. } = mapped_asset; if !asset.info.version.is_empty() { - self.0.insert(filename.to_owned(), mapped_asset.clone()); + self.0.insert(filename.clone(), mapped_asset.clone()); } } diff --git a/crates/rspack_plugin_devtool/src/source_map_dev_tool_plugin.rs b/crates/rspack_plugin_devtool/src/source_map_dev_tool_plugin.rs index 1f8b89cc0aa..3f2626be67d 100644 --- a/crates/rspack_plugin_devtool/src/source_map_dev_tool_plugin.rs +++ b/crates/rspack_plugin_devtool/src/source_map_dev_tool_plugin.rs @@ -9,6 +9,7 @@ use itertools::Itertools; use rayon::prelude::*; use regex::Regex; use rspack_collections::DatabaseItem; +use rspack_core::AssetFilename; use rspack_core::{ rspack_sources::{ConcatSource, MapOptions, RawSource, Source, SourceExt}, AssetInfo, Chunk, ChunkUkey, Compilation, CompilationAsset, CompilationProcessAssets, @@ -94,8 +95,8 @@ enum SourceMappingUrlCommentRef<'a> { #[derive(Debug, Clone)] pub(crate) struct MappedAsset { - pub(crate) asset: (String, CompilationAsset), - pub(crate) source_map: Option<(String, CompilationAsset)>, + pub(crate) asset: (AssetFilename, CompilationAsset), + pub(crate) source_map: Option<(AssetFilename, CompilationAsset)>, } #[plugin] @@ -168,14 +169,14 @@ impl SourceMapDevToolPlugin { async fn map_assets( &self, compilation: &Compilation, - file_to_chunk: &HashMap<&String, &Chunk>, - raw_assets: Vec<(String, &CompilationAsset)>, + file_to_chunk: &HashMap<&str, &Chunk>, + raw_assets: Vec<(AssetFilename, &CompilationAsset)>, ) -> Result> { let output_options = &compilation.options.output; let map_options = MapOptions::new(self.columns); let matches = if let Some(test) = &self.test { - let features = raw_assets.iter().map(|(file, _)| test(file.to_owned())); + let features = raw_assets.iter().map(|(file, _)| test(file.to_string())); join_all(features) .await .into_iter() @@ -327,7 +328,7 @@ impl SourceMapDevToolPlugin { for (filename, _asset, source_map) in mapped_sources.iter_mut() { if let Some(source_map) = source_map { - source_map.set_file(Some(filename.clone())); + source_map.set_file(Some(filename.to_string())); let sources = source_map.sources_mut(); for source in sources { @@ -391,19 +392,17 @@ impl SourceMapDevToolPlugin { }; if let Some(source_map_filename_config) = &self.source_map_filename { - let chunk = file_to_chunk.get(&filename); + let chunk = file_to_chunk.get(filename.as_str()); let source_type = if css_extension_detected { &SourceType::Css } else { &SourceType::JavaScript }; let filename = match &self.file_context { - Some(file_context) => Cow::Owned( - relative(Path::new(file_context), Path::new(&filename)) - .to_string_lossy() - .to_string(), - ), - None => Cow::Borrowed(&filename), + Some(file_context) => relative(Path::new(file_context), Path::new(filename.as_str())) + .to_string_lossy() + .into(), + None => filename, }; let data = PathData::default().filename(&filename); let data = match chunk { @@ -421,9 +420,10 @@ impl SourceMapDevToolPlugin { ), None => data, }; - let source_map_filename = compilation + let source_map_filename: AssetFilename = compilation .get_asset_path(source_map_filename_config, data) - .always_ok(); + .always_ok() + .into(); if let Some(current_source_mapping_url_comment) = current_source_mapping_url_comment { let source_map_url = if let Some(public_path) = &self.public_path { @@ -431,11 +431,11 @@ impl SourceMapDevToolPlugin { } else { let mut file_path = PathBuf::new(); file_path.push(Component::RootDir); - file_path.extend(Path::new(filename.as_ref()).components()); + file_path.extend(Path::new(filename.as_str()).components()); let mut source_map_path = PathBuf::new(); source_map_path.push(Component::RootDir); - source_map_path.extend(Path::new(&source_map_filename).components()); + source_map_path.extend(Path::new(source_map_filename.as_str()).components()); relative( #[allow(clippy::unwrap_used)] @@ -474,7 +474,7 @@ impl SourceMapDevToolPlugin { asset.source = Some(source.clone()); } let mut source_map_asset_info = AssetInfo::default().with_development(Some(true)); - if let Some(asset) = compilation.assets().get(filename.as_ref()) { + if let Some(asset) = compilation.assets().get(filename.as_str()) { // set source map asset version to be the same as the target asset source_map_asset_info.version = asset.info.version.clone(); } @@ -483,7 +483,7 @@ impl SourceMapDevToolPlugin { source_map_asset_info, ); Ok(MappedAsset { - asset: (filename.to_string(), asset), + asset: (filename, asset), source_map: Some((source_map_filename, source_map_asset)), }) } else { @@ -530,7 +530,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { let logger = compilation.get_logger("rspack.SourceMapDevToolPlugin"); // use to read - let mut file_to_chunk: HashMap<&String, &Chunk> = HashMap::default(); + let mut file_to_chunk: HashMap<&str, &Chunk> = HashMap::default(); // use to write let mut file_to_chunk_ukey: HashMap = HashMap::default(); for chunk in compilation.chunk_by_ukey.values() { @@ -571,7 +571,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { } } - let chunk_ukey = file_to_chunk_ukey.get(&source_filename); + let chunk_ukey = file_to_chunk_ukey.get(source_filename.as_str()); compilation.emit_asset(source_filename, source_asset); if let Some((source_map_filename, source_map_asset)) = source_map { compilation.emit_asset(source_map_filename.to_owned(), source_map_asset); diff --git a/crates/rspack_plugin_dll/src/lib_manifest_plugin.rs b/crates/rspack_plugin_dll/src/lib_manifest_plugin.rs index 21df8564541..84fb0c045cd 100644 --- a/crates/rspack_plugin_dll/src/lib_manifest_plugin.rs +++ b/crates/rspack_plugin_dll/src/lib_manifest_plugin.rs @@ -173,7 +173,7 @@ async fn emit(&self, compilation: &mut Compilation) -> Result<()> { let asset = Arc::new(RawSource::from(manifest_json)) as BoxSource; - manifests.insert(target_path, asset.into()); + manifests.insert(target_path.into(), asset.into()); } for (filename, asset) in manifests { diff --git a/crates/rspack_plugin_extract_css/src/plugin.rs b/crates/rspack_plugin_extract_css/src/plugin.rs index 9ecc6a9f2cb..b61929fdc3e 100644 --- a/crates/rspack_plugin_extract_css/src/plugin.rs +++ b/crates/rspack_plugin_extract_css/src/plugin.rs @@ -411,7 +411,7 @@ impl PluginCssExtract { Ok(( RenderManifestEntry::new( Arc::new(external_source), - filename, + filename.into(), AssetInfo::default(), false, false, @@ -632,7 +632,7 @@ despite it was not able to fulfill desired ordering with these modules:\n{}", .join("\n") ), ) - .with_file(Some(render_result.filename().to_owned().into())) + .with_file(Some(render_result.filename.to_string().into())) .with_chunk(Some(chunk_ukey.as_u32())) })); } diff --git a/crates/rspack_plugin_hmr/src/lib.rs b/crates/rspack_plugin_hmr/src/lib.rs index 7fac55bc58c..61aef1f58d7 100644 --- a/crates/rspack_plugin_hmr/src/lib.rs +++ b/crates/rspack_plugin_hmr/src/lib.rs @@ -8,7 +8,7 @@ use rspack_collections::{DatabaseItem, IdentifierSet, UkeyMap}; use rspack_core::{ collect_changed_modules, rspack_sources::{RawSource, SourceExt}, - ApplyContext, AssetInfo, Chunk, ChunkKind, ChunkUkey, Compilation, + ApplyContext, AssetFilename, AssetInfo, Chunk, ChunkKind, ChunkUkey, Compilation, CompilationAdditionalTreeRuntimeRequirements, CompilationAsset, CompilationParams, CompilationProcessAssets, CompilationRecords, CompilerCompilation, CompilerOptions, DependencyType, LoaderContext, ModuleType, NormalModuleFactoryParser, NormalModuleLoader, @@ -88,7 +88,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { let mut updated_modules: IdentifierSet = Default::default(); let mut updated_runtime_modules: IdentifierSet = Default::default(); let mut completely_removed_modules: HashSet = Default::default(); - let mut updated_chunks: UkeyMap> = Default::default(); + let mut updated_chunks: UkeyMap> = Default::default(); for (old_uri, (old_hash, old_module_id)) in &old_all_modules { if let Some((now_hash, _)) = now_all_modules.get(old_uri) { @@ -258,7 +258,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { for entry in manifest { let filename = if entry.has_filename() { - entry.filename().to_string() + entry.filename } else { compilation .get_path( @@ -273,6 +273,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { ), ) .always_ok() + .into() }; let asset = CompilationAsset::new( Some(entry.source), @@ -328,7 +329,8 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { .map(|hash| hash.rendered(compilation.options.output.hash_digest_length)), ), ) - .always_ok(); + .always_ok() + .into(); compilation.emit_asset( filename, CompilationAsset::new( diff --git a/crates/rspack_plugin_html/src/asset.rs b/crates/rspack_plugin_html/src/asset.rs index 8777f07b657..fecc2077c55 100644 --- a/crates/rspack_plugin_html/src/asset.rs +++ b/crates/rspack_plugin_html/src/asset.rs @@ -65,7 +65,7 @@ impl HtmlPluginAssets { .map(|entry_name| compilation.entrypoint_by_name(entry_name)) .flat_map(|entry| entry.get_files(&compilation.chunk_by_ukey)) .filter_map(|asset_name| { - let asset = compilation.assets().get(&asset_name).expect("TODO:"); + let asset = compilation.assets().get(asset_name).expect("TODO:"); if asset.info.hot_module_replacement.unwrap_or(false) || asset.info.development.unwrap_or(false) { diff --git a/crates/rspack_plugin_html/src/plugin.rs b/crates/rspack_plugin_html/src/plugin.rs index a1d33f0335e..9007c7f7723 100644 --- a/crates/rspack_plugin_html/src/plugin.rs +++ b/crates/rspack_plugin_html/src/plugin.rs @@ -2,8 +2,8 @@ use std::{path::PathBuf, sync::LazyLock}; use cow_utils::CowUtils; use rspack_core::{ - Compilation, CompilationId, CompilationProcessAssets, Filename, FilenameTemplate, NoFilenameFn, - Plugin, + AssetFilename, Compilation, CompilationId, CompilationProcessAssets, Filename, FilenameTemplate, + NoFilenameFn, Plugin, }; use rspack_error::{miette, Diagnostic, Result}; use rspack_hook::{plugin, plugin_hook}; @@ -210,7 +210,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { if let Some(favicon) = &config.favicon { match create_favicon_asset(favicon, config, compilation) { - Ok(favicon) => compilation.emit_asset(favicon.0, favicon.1), + Ok(favicon) => compilation.emit_asset(favicon.0.into(), favicon.1), Err(err) => { let error_msg = err.to_string(); compilation.push_diagnostic(Diagnostic::from(err)); @@ -226,7 +226,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { compilation, ); - compilation.emit_asset(html_asset.0.clone(), html_asset.1); + compilation.emit_asset(html_asset.0.as_str().into(), html_asset.1); let _ = hooks .after_emit diff --git a/crates/rspack_plugin_javascript/src/plugin/impl_plugin_for_js_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/impl_plugin_for_js_plugin.rs index 8b41e3d0a0f..7dcc3686d3c 100644 --- a/crates/rspack_plugin_javascript/src/plugin/impl_plugin_for_js_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/impl_plugin_for_js_plugin.rs @@ -274,7 +274,7 @@ async fn render_manifest( asset_info.set_javascript_module(compilation.options.output.module); manifest.push(RenderManifestEntry::new( source, - output_path, + output_path.into(), asset_info, false, false, diff --git a/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs index a3b5f012235..0c65328372e 100644 --- a/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/module_concatenation_plugin.rs @@ -10,10 +10,10 @@ use rspack_core::concatenated_module::{ is_esm_dep_like, ConcatenatedInnerModule, ConcatenatedModule, RootModuleContext, }; use rspack_core::{ - filter_runtime, merge_runtime, ApplyContext, Compilation, CompilationOptimizeChunkModules, - CompilerOptions, ExportInfoProvided, ExtendedReferencedExport, LibIdentOptions, Logger, Module, - ModuleExt, ModuleGraph, ModuleGraphModule, ModuleIdentifier, Plugin, PluginContext, - ProvidedExports, RuntimeCondition, RuntimeSpec, SourceType, + filter_runtime, merge_runtime, ApplyContext, AssetFilename, Compilation, + CompilationOptimizeChunkModules, CompilerOptions, ExportInfoProvided, ExtendedReferencedExport, + LibIdentOptions, Logger, Module, ModuleExt, ModuleGraph, ModuleGraphModule, ModuleIdentifier, + Plugin, PluginContext, ProvidedExports, RuntimeCondition, RuntimeSpec, SourceType, }; use rspack_error::Result; use rspack_hook::{plugin, plugin_hook}; @@ -618,7 +618,7 @@ impl ModuleConcatenationPlugin { config.runtime.clone(), compilation, ); - let new_module_assets: HashSet = + let new_module_assets: HashSet = modules_set.iter().fold(HashSet::default(), |mut acc, id| { acc.extend( compilation diff --git a/crates/rspack_plugin_lightning_css_minimizer/src/lib.rs b/crates/rspack_plugin_lightning_css_minimizer/src/lib.rs index 80148ae82b4..cfae8c5ec26 100644 --- a/crates/rspack_plugin_lightning_css_minimizer/src/lib.rs +++ b/crates/rspack_plugin_lightning_css_minimizer/src/lib.rs @@ -261,7 +261,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { let minimized_source = if let Some(mut source_map) = source_map { SourceMapSource::new(SourceMapSourceOptions { value: result.code, - name: filename, + name: filename.to_string(), source_map: SourceMap::from_json( &source_map .to_json(None) diff --git a/crates/rspack_plugin_real_content_hash/src/lib.rs b/crates/rspack_plugin_real_content_hash/src/lib.rs index 4d3602c5c9b..e6fc332a411 100644 --- a/crates/rspack_plugin_real_content_hash/src/lib.rs +++ b/crates/rspack_plugin_real_content_hash/src/lib.rs @@ -148,7 +148,7 @@ fn inner_impl(compilation: &mut Compilation) -> Result<()> { .expect("RealContentHashPlugin: should have new hash") }) .into_owned(); - let new_name = (name != new_name).then_some(new_name); + let new_name = (name != new_name).then(|| new_name.into()); Some((name.to_owned(), new_source.clone(), new_name)) }) .collect(); diff --git a/crates/rspack_plugin_size_limits/src/lib.rs b/crates/rspack_plugin_size_limits/src/lib.rs index 083b1710341..5211edae0b4 100644 --- a/crates/rspack_plugin_size_limits/src/lib.rs +++ b/crates/rspack_plugin_size_limits/src/lib.rs @@ -3,8 +3,8 @@ use std::{collections::HashMap, fmt::Debug}; use derivative::Derivative; use futures::future::BoxFuture; use rspack_core::{ - ApplyContext, ChunkGroup, ChunkGroupUkey, Compilation, CompilationAsset, CompilerAfterEmit, - CompilerOptions, Plugin, PluginContext, + ApplyContext, AssetFilename, ChunkGroup, ChunkGroupUkey, Compilation, CompilationAsset, + CompilerAfterEmit, CompilerOptions, Plugin, PluginContext, }; use rspack_error::{Diagnostic, Result}; use rspack_hook::{plugin, plugin_hook}; @@ -49,7 +49,7 @@ impl SizeLimitsPlugin { let mut size = 0.0; for filename in entrypoint.get_files(&compilation.chunk_by_ukey) { - let asset = compilation.assets().get(&filename); + let asset = compilation.assets().get(filename); if let Some(asset) = asset { if !self.asset_filter(&filename, asset).await { @@ -82,7 +82,7 @@ impl SizeLimitsPlugin { } fn add_assets_over_size_limit_warning( - detail: &[(&String, f64)], + detail: &[(&AssetFilename, f64)], limit: f64, hints: &str, diagnostics: &mut Vec, @@ -99,7 +99,7 @@ impl SizeLimitsPlugin { } fn add_entrypoints_over_size_limit_warning( - detail: &[(&String, f64, Vec)], + detail: &[(&String, f64, Vec<&AssetFilename>)], limit: f64, hints: &str, diagnostics: &mut Vec, @@ -136,7 +136,7 @@ async fn after_emit(&self, compilation: &mut Compilation) -> Result<()> { let hints = &self.options.hints; let max_asset_size = self.options.max_asset_size.unwrap_or(250000.0); let max_entrypoint_size = self.options.max_entrypoint_size.unwrap_or(250000.0); - let mut checked_assets: HashMap = HashMap::default(); + let mut checked_assets: HashMap = HashMap::default(); let mut checked_chunk_groups: HashMap = HashMap::default(); let mut assets_over_size_limit = vec![]; @@ -152,7 +152,7 @@ async fn after_emit(&self, compilation: &mut Compilation) -> Result<()> { let size = source.size() as f64; let is_over_size_limit = size > max_asset_size; - checked_assets.insert(name.to_owned(), is_over_size_limit); + checked_assets.insert(name.clone(), is_over_size_limit); if is_over_size_limit { assets_over_size_limit.push((name, size)); } @@ -171,7 +171,7 @@ async fn after_emit(&self, compilation: &mut Compilation) -> Result<()> { let mut files = vec![]; for filename in entry.get_files(&compilation.chunk_by_ukey) { - let asset = compilation.assets().get(&filename); + let asset = compilation.assets().get(filename); if let Some(asset) = asset { if self.asset_filter(&filename, asset).await { @@ -223,7 +223,7 @@ async fn after_emit(&self, compilation: &mut Compilation) -> Result<()> { } for (name, asset) in compilation.assets_mut() { - if let Some(checked) = checked_assets.get(name) { + if let Some(checked) = checked_assets.get(name.as_str()) { asset.info.set_is_over_size_limit(*checked) } } diff --git a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs index 743d58f1b60..6964c018d58 100644 --- a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs +++ b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs @@ -285,7 +285,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> { .into_iter() .for_each(|(_, comments)| { compilation.emit_asset( - comments.comments_file_name, + comments.comments_file_name.into(), CompilationAsset { source: Some(comments.source), info: AssetInfo { diff --git a/crates/rspack_plugin_wasm/src/wasm_plugin.rs b/crates/rspack_plugin_wasm/src/wasm_plugin.rs index 12264d4a8b7..03adb1f5e73 100644 --- a/crates/rspack_plugin_wasm/src/wasm_plugin.rs +++ b/crates/rspack_plugin_wasm/src/wasm_plugin.rs @@ -66,7 +66,7 @@ async fn render_manifest( .get(&m.identifier()) .map(|s| s.clone()) .expect("should have wasm_filename"); - RenderManifestEntry::new(source.clone(), output_path, asset_info, false, false) + RenderManifestEntry::new(source.clone(), output_path.into(), asset_info, false, false) }); Ok(result)