use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;
use super::args::Cli;
use super::daemon::{execute, script_label};
pub fn run_file(cli: &Cli, path: &PathBuf, user_args: &[String]) -> Result<()> {
let source = fs::read_to_string(path).with_context(|| format!("reading {path:?}"))?;
let label = script_label(path);
let js_source = maybe_transpile_ts(&source, path)?;
if cli.internal_worker {
return super::worker::execute(cli, &js_source, &label, user_args);
}
execute(cli, &js_source, &label, user_args)
}
pub fn run_source(cli: &Cli, source: &str, user_args: &[String]) -> Result<()> {
if cli.internal_worker {
return super::worker::execute(cli, source, "[eval]", &[]);
}
execute(cli, source, "[eval]", user_args)
}
#[cfg(feature = "ts")]
fn maybe_transpile_ts(source: &str, path: &std::path::Path) -> Result<String> {
if crate::ts::is_typescript(path) {
return crate::ts::transpile(source, path).map_err(|e| anyhow::anyhow!("{e}"));
}
crate::ts::lower_esm_js(source, path).map_err(|e| anyhow::anyhow!("{e}"))
}
#[cfg(not(feature = "ts"))]
fn maybe_transpile_ts(source: &str, path: &std::path::Path) -> Result<String> {
let ext = path
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
if matches!(
ext.as_deref(),
Some("ts") | Some("mts") | Some("cts") | Some("tsx")
) {
anyhow::bail!(
"burn: TypeScript support requires the `ts` cargo feature (rebuild with `cargo install afterburner --features ts`). \
File: {}",
path.display()
);
}
Ok(source.to_string())
}