use std::path::{Path, PathBuf};
use color_eyre::eyre::eyre;
use swc_common::{
SourceMap,
errors::{ColorConfig, Handler},
sync::Lrc,
};
use swc_ecma_ast::EsVersion;
use swc_ecma_parser::{Parser, StringInput, Syntax, TsSyntax, lexer::Lexer};
pub struct Bundler {
root_dir: PathBuf,
cm: Lrc<SourceMap>,
handler: Handler,
}
impl Bundler {
pub fn new(root_dir: PathBuf) -> Self {
let cm = Lrc::<SourceMap>::default();
Bundler {
root_dir,
cm: cm.clone(),
handler: Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(cm)),
}
}
pub fn bundle(&self, entrypoint: impl AsRef<Path>) -> color_eyre::Result<()> {
let mut path = self.root_dir.clone();
path.push(entrypoint);
let fm = self.cm.load_file(&path)?;
let lexer = Lexer::new(
Syntax::Typescript(TsSyntax::default()),
EsVersion::latest(),
StringInput::from(&*fm),
None,
);
let mut parser = Parser::new_from(lexer);
for e in parser.take_errors() {
e.into_diagnostic(&self.handler).emit();
}
let module = parser.parse_module().map_err(|e| {
e.into_diagnostic(&self.handler).emit();
eyre!("couldn't parse {}", fm.name)
})?;
dbg!(module);
Ok(())
}
}