1use std::path::Path;
2
3use rolldown::{Bundler, BundlerOptions};
4use rolldown_common::Output;
5
6use super::{Asset, Environment, LayeredContext, MediaType, ProcessesAssets, ProcessingError};
7
8pub struct JsBundleProcessor {
27 minify: bool,
29}
30
31impl JsBundleProcessor {
32 pub fn new(minify: bool) -> Self {
34 Self { minify }
35 }
36}
37
38impl JsBundleProcessor {
39 fn bundle_js(&self, entry_path: &Path) -> Result<String, ProcessingError> {
43 let file_name = entry_path
45 .file_name()
46 .ok_or_else(|| ProcessingError::Compilation {
47 message: format!(
48 "Invalid entry path '{}': must be a file path, not a directory or root",
49 entry_path.display()
50 )
51 .into(),
52 })?;
53
54 let cwd = entry_path
57 .parent()
58 .filter(|p| !p.as_os_str().is_empty())
59 .map(|p| {
60 if p.is_absolute() {
61 p.to_path_buf()
62 } else {
63 std::env::current_dir().unwrap_or_default().join(p)
64 }
65 });
66
67 let input_path = format!("./{}", file_name.to_string_lossy());
68
69 let options = BundlerOptions {
71 input: Some(vec![input_path.into()]),
72 cwd,
73 minify: if self.minify {
74 Some(rolldown::RawMinifyOptions::Bool(true))
75 } else {
76 None
77 },
78 ..Default::default()
79 };
80
81 let rt = tokio::runtime::Runtime::new().map_err(|e| ProcessingError::Compilation {
85 message: format!("Failed to create async runtime: {}", e).into(),
86 })?;
87
88 rt.block_on(async {
90 let mut bundler = Bundler::new(options).map_err(|e| ProcessingError::Compilation {
91 message: format!("Failed to create bundler: {:?}", e).into(),
92 })?;
93
94 let output = bundler
95 .generate()
96 .await
97 .map_err(|e| ProcessingError::Compilation {
98 message: format!("Bundling failed: {:?}", e).into(),
99 })?;
100
101 for asset in output.assets {
103 if let Output::Chunk(chunk) = asset {
104 return Ok(chunk.code.clone());
105 }
106 }
107
108 Err(ProcessingError::Compilation {
109 message: "Bundling produced no output chunks".into(),
110 })
111 })
112 }
113}
114
115impl ProcessesAssets for JsBundleProcessor {
116 fn process(
117 &self,
118 _env: &Environment,
119 _context: &LayeredContext,
120 asset: &mut Asset,
121 ) -> Result<bool, ProcessingError> {
122 if *asset.media_type() != MediaType::JavaScript {
124 return Ok(false);
125 }
126
127 tracing::trace!("js_bundle: {}", asset.path());
128
129 let entry_path_str = asset.path().clone();
131 let entry_path = Path::new(entry_path_str.as_str());
132
133 let bundled_code = self.bundle_js(entry_path)?;
135
136 asset.replace_with_text(bundled_code.into(), MediaType::JavaScript);
138
139 Ok(true)
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146 use crate::proc::LayeredContext;
147
148 #[test]
149 fn skips_non_javascript_assets() {
150 let processor = JsBundleProcessor { minify: false };
151
152 let mut css_asset = Asset::new("style.css".into(), "body {}".as_bytes().to_vec());
154
155 let modified = processor
157 .process(
158 &Environment::test(),
159 &LayeredContext::from_flat(Default::default()),
160 &mut css_asset,
161 )
162 .unwrap();
163 assert!(!modified);
164 }
165
166 #[test]
167 fn bundles_javascript() {
168 let processor = JsBundleProcessor { minify: false };
169
170 let mut js_asset = Asset::new("test/js_bundle/entry.js".into(), "".as_bytes().to_vec());
172
173 let result = processor.process(
175 &Environment::test(),
176 &LayeredContext::from_flat(Default::default()),
177 &mut js_asset,
178 );
179 assert!(result.is_ok());
180
181 let bundled = js_asset.as_text().unwrap();
184 assert!(bundled.contains("Hello from bundled JavaScript!"));
185 assert!(bundled.contains("greet"));
186 assert!(bundled.contains("1.0.0"));
189 assert!(bundled.contains("formatMessage"));
190 }
191}