use camino::Utf8Path;
use glob::Pattern;
use rolldown::{BundlerOptions, CodeSplittingMode, InputItem, RawMinifyOptions};
use thiserror::Error;
use crate::core::Hash32;
use crate::{Blueprint, engine::Many, error::HauchiwaError, loader::GlobBundle};
#[derive(Debug, Error)]
pub enum ScriptError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Rolldown execution failed: {0}")]
Rolldown(String),
#[error("UTF-8 conversion error: {0}")]
Utf8(#[from] std::string::FromUtf8Error),
#[error("Build error: {0}")]
Build(#[from] crate::error::BuildError),
}
pub struct ScriptLoader<'a, G>
where
G: Send + Sync,
{
blueprint: &'a mut Blueprint<G>,
entry_globs: Vec<String>,
entry_patterns: Vec<Pattern>,
watch_globs: Vec<Pattern>,
bundle: bool,
minify: bool,
}
impl<'a, G> ScriptLoader<'a, G>
where
G: Send + Sync + 'static,
{
pub(crate) fn new(blueprint: &'a mut Blueprint<G>) -> Self {
Self {
blueprint,
entry_globs: Vec::new(),
entry_patterns: Vec::new(),
watch_globs: Vec::new(),
bundle: true,
minify: true,
}
}
pub fn entry(mut self, glob: impl Into<String>) -> Result<Self, HauchiwaError> {
let glob = glob.into();
let pattern = Pattern::new(&glob)?;
self.entry_globs.push(glob);
self.entry_patterns.push(pattern);
Ok(self)
}
pub fn watch(mut self, glob: impl Into<String>) -> Result<Self, HauchiwaError> {
let glob = glob.into();
let pattern = Pattern::new(&glob)?;
self.watch_globs.push(pattern);
Ok(self)
}
pub fn bundle(mut self, bundle: bool) -> Self {
self.bundle = bundle;
self
}
pub fn minify(mut self, minify: bool) -> Self {
self.minify = minify;
self
}
pub fn register(self) -> Many<super::Script> {
let watch_globs = if self.watch_globs.is_empty() {
self.entry_patterns
} else {
self.watch_globs
};
let bundle = self.bundle;
let minify = self.minify;
let task = GlobBundle::new(self.entry_globs, watch_globs, move |_, store, input| {
let data = compile_rolldown(&input.path, bundle, minify)?;
let hash = Hash32::hash(&data);
let path = store.save(&data, "js").map_err(ScriptError::Build)?;
Ok((hash, input.path, super::Script { path }))
});
self.blueprint.add_task_fine(task)
}
}
impl<G> Blueprint<G>
where
G: Send + Sync + 'static,
{
pub fn load_rolldown(&mut self) -> ScriptLoader<'_, G> {
ScriptLoader::new(self)
}
}
fn compile_rolldown(file: &Utf8Path, _bundle: bool, minify: bool) -> Result<Vec<u8>, ScriptError> {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(async {
let options = BundlerOptions {
input: Some(vec![InputItem {
name: Some(file.to_string()),
import: file.to_string(),
}]),
minify: Some(RawMinifyOptions::Bool(minify)),
code_splitting: Some(CodeSplittingMode::Bool(false)),
..Default::default()
};
let mut bundler =
rolldown::Bundler::new(options).map_err(|e| ScriptError::Rolldown(e.to_string()))?;
let output = bundler
.generate()
.await
.map_err(|e| ScriptError::Rolldown(e.to_string()))?;
if let Some(chunk) = output.assets.into_iter().next() {
return Ok(chunk.content_as_bytes().to_vec());
}
Err(ScriptError::Rolldown("No output chunks generated".into()))
})
}