use crate::ast::make_hashed_ident;
use std::collections::BTreeMap;
use swc_core::ecma::ast::Ident;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportKind {
Static,
Dynamic,
Fetch,
}
impl ImportKind {
pub fn from_option(raw: Option<&str>) -> Option<Self> {
match raw {
Some("dynamic") => Some(ImportKind::Dynamic),
Some("fetch") => Some(ImportKind::Fetch),
Some(_) => Some(ImportKind::Static),
None => None,
}
}
fn ident_suffix(self) -> &'static str {
match self {
ImportKind::Static => "",
ImportKind::Dynamic => "_dyn",
ImportKind::Fetch => "_fetch",
}
}
pub fn is_dynamic_helper(self) -> bool {
!matches!(self, ImportKind::Static)
}
}
#[derive(Default)]
pub struct InjectedImports {
pub static_imports: BTreeMap<String, Ident>,
pub dynamic_imports: BTreeMap<String, Ident>,
}
impl InjectedImports {
pub fn ident_for(&mut self, key: &str, import_kind: ImportKind) -> Ident {
let map = match import_kind {
ImportKind::Static => &mut self.static_imports,
ImportKind::Dynamic | ImportKind::Fetch => &mut self.dynamic_imports,
};
if let Some(ident) = map.get(key) {
return ident.clone();
}
let ident = make_hashed_ident(key, import_kind.ident_suffix());
map.insert(key.to_string(), ident.clone());
ident
}
}