use std::process::{Command, Stdio};
use camino::{Utf8Path, Utf8PathBuf};
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("Esbuild execution failed: {0}")]
Esbuild(String),
#[error("UTF-8 conversion error: {0}")]
Utf8(#[from] std::string::FromUtf8Error),
#[error("Build error: {0}")]
Build(#[from] crate::error::BuildError),
}
#[derive(Clone)]
pub struct Script {
pub path: Utf8PathBuf,
}
pub struct ScriptLoader<'a, G>
where
G: Send + Sync,
{
blueprint: &'a mut Blueprint<G>,
entry_globs: Vec<String>,
watch_globs: Vec<String>,
bundle: bool,
minify: bool,
}
impl<'a, G> ScriptLoader<'a, G>
where
G: Send + Sync + 'static,
{
fn new(blueprint: &'a mut Blueprint<G>) -> Self {
Self {
blueprint,
entry_globs: Vec::new(),
watch_globs: Vec::new(),
bundle: true,
minify: true,
}
}
pub fn entry(mut self, glob: impl Into<String>) -> Self {
self.entry_globs.push(glob.into());
self
}
pub fn watch(mut self, glob: impl Into<String>) -> Self {
self.watch_globs.push(glob.into());
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) -> Result<Many<Script>, HauchiwaError> {
let watch_globs = if self.watch_globs.is_empty() {
self.entry_globs.clone()
} 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_esbuild(&input.path, bundle, minify)?;
let hash = Hash32::hash(&data);
let path = store.save(&data, "js").map_err(ScriptError::Build)?;
Ok((hash, input.path, Script { path }))
})?;
Ok(self.blueprint.add_task_fine(task))
}
}
impl<G> Blueprint<G>
where
G: Send + Sync + 'static,
{
pub fn load_js(&mut self) -> ScriptLoader<'_, G> {
ScriptLoader::new(self)
}
}
fn compile_esbuild(file: &Utf8Path, bundle: bool, minify: bool) -> Result<Vec<u8>, ScriptError> {
let mut cmd = Command::new("esbuild");
cmd.arg(file.as_str()).arg("--format=esm");
if bundle {
cmd.arg("--bundle");
}
if minify {
cmd.arg("--minify");
}
let output = cmd
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.output()?;
if !output.status.success() {
return Err(ScriptError::Esbuild(String::from_utf8(output.stdout)?));
}
Ok(output.stdout)
}