use anyhow::Context;
use fob_bundler::{
HookLoadArgs, HookLoadOutput, HookLoadReturn, ModuleType, Plugin, PluginContext,
};
use fob_graph::analysis::extractors::{ExtractedScript, Extractor, SvelteExtractor};
use std::borrow::Cow;
#[derive(Debug, Clone, Default)]
pub struct FobSveltePlugin {
}
impl FobSveltePlugin {
pub fn new() -> Self {
Self::default()
}
}
impl Plugin for FobSveltePlugin {
fn name(&self) -> Cow<'static, str> {
"fob-svelte".into()
}
fn register_hook_usage(&self) -> fob_bundler::HookUsage {
use fob_bundler::HookUsage;
HookUsage::Load
}
fn load(
&self,
_ctx: &PluginContext,
args: &HookLoadArgs<'_>,
) -> impl std::future::Future<Output = HookLoadReturn> + Send {
let id = args.id.to_string();
async move {
if !id.ends_with(".svelte") {
return Ok(None);
}
let source = std::fs::read_to_string(&id)
.with_context(|| format!("Failed to read Svelte file: {}", id))?;
let scripts = SvelteExtractor
.extract(&source)
.with_context(|| format!("Failed to parse Svelte file: {}", id))?;
if scripts.is_empty() {
return Ok(Some(HookLoadOutput {
code: "export default {}".into(),
module_type: Some(ModuleType::Js),
..Default::default()
}));
}
let (combined_code, module_type) = combine_scripts(&scripts);
Ok(Some(HookLoadOutput {
code: combined_code.into(),
module_type: Some(module_type),
..Default::default()
}))
}
}
}
fn combine_scripts(scripts: &[ExtractedScript]) -> (String, ModuleType) {
use fob_graph::analysis::extractors::ScriptContext;
if scripts.len() == 1 {
let script = &scripts[0];
return (
script.source_text.to_string(),
determine_module_type(script.lang),
);
}
let mut module_script = None;
let mut instance_script = None;
for script in scripts {
match script.context {
ScriptContext::SvelteModule => module_script = Some(script),
ScriptContext::SvelteComponent => instance_script = Some(script),
_ => {} }
}
let mut combined = String::new();
let mut detected_lang = "js";
if let Some(module) = module_script {
combined.push_str(module.source_text);
detected_lang = module.lang;
}
if let Some(instance) = instance_script {
if !combined.is_empty() {
combined.push_str("\n\n"); }
combined.push_str(instance.source_text);
detected_lang = choose_stronger_lang(detected_lang, instance.lang);
}
(combined, determine_module_type(detected_lang))
}
fn determine_module_type(lang: &str) -> ModuleType {
match lang {
"ts" | "typescript" => ModuleType::Ts,
_ => ModuleType::Js,
}
}
fn choose_stronger_lang<'a>(lang1: &'a str, lang2: &'a str) -> &'a str {
let strength = |lang: &str| match lang {
"ts" | "typescript" => 2,
_ => 1,
};
if strength(lang1) >= strength(lang2) {
lang1
} else {
lang2
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_plugin_creation() {
let plugin = FobSveltePlugin::new();
assert_eq!(plugin.name(), "fob-svelte");
}
#[test]
fn test_plugin_default() {
let plugin = FobSveltePlugin::default();
assert_eq!(plugin.name(), "fob-svelte");
}
#[test]
fn test_determine_module_type() {
assert!(matches!(determine_module_type("js"), ModuleType::Js));
assert!(matches!(determine_module_type("ts"), ModuleType::Ts));
assert!(matches!(
determine_module_type("typescript"),
ModuleType::Ts
));
}
#[test]
fn test_choose_stronger_lang() {
assert_eq!(choose_stronger_lang("js", "ts"), "ts");
assert_eq!(choose_stronger_lang("ts", "js"), "ts");
assert_eq!(choose_stronger_lang("ts", "ts"), "ts");
}
#[test]
fn test_combine_single_script() {
use fob_graph::analysis::extractors::ScriptContext;
let scripts = vec![ExtractedScript::new(
"const x = 1;",
100,
ScriptContext::SvelteComponent,
"js",
)];
let (code, module_type) = combine_scripts(&scripts);
assert_eq!(code, "const x = 1;");
assert!(matches!(module_type, ModuleType::Js));
}
#[test]
fn test_combine_multiple_scripts() {
use fob_graph::analysis::extractors::ScriptContext;
let scripts = vec![
ExtractedScript::new(
"export const shared = 'data'",
50,
ScriptContext::SvelteModule,
"js",
),
ExtractedScript::new(
"let count: number = 0",
150,
ScriptContext::SvelteComponent,
"ts",
),
];
let (code, module_type) = combine_scripts(&scripts);
assert!(code.starts_with("export const shared = 'data'"));
assert!(code.contains("let count"));
assert!(matches!(module_type, ModuleType::Ts));
}
}