fob_plugin_vue/lib.rs
1//! Rolldown plugin for Vue Single File Components (SFC)
2//!
3//! This plugin extracts and processes `<script>` blocks from Vue SFCs, making them
4//! available to the bundler as JavaScript/TypeScript modules.
5//!
6//! ## Architecture
7//!
8//! ```text
9//! .vue file → load() hook → VueExtractor → Extract scripts → JavaScript/TypeScript → Rolldown
10//! ```
11//!
12//! ## Why the `load` hook?
13//!
14//! We use the `load` hook (not `transform`) because:
15//! - Vue SFCs aren't valid JavaScript/TypeScript that Rolldown can parse
16//! - We must intercept files before Rolldown's parser runs
17//! - The `load` hook is designed for custom file formats
18//! - We return extracted JavaScript with the appropriate `ModuleType`
19//!
20//! ## Handling Multiple Scripts
21//!
22//! Vue SFCs can have up to 2 script blocks:
23//! - One regular `<script>` block (Options API)
24//! - One `<script setup>` block (Composition API)
25//!
26//! When both exist, we combine them with `<script setup>` running first,
27//! as per Vue's execution semantics.
28//!
29//! ## Example Usage
30//!
31//! ```rust,no_run
32//! use fob_plugin_vue::FobVuePlugin;
33//! use std::sync::Arc;
34//!
35//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
36//! let plugin = Arc::new(FobVuePlugin::new());
37//! // Add to your Rolldown bundler configuration
38//! # Ok(())
39//! # }
40//! ```
41
42use anyhow::Context;
43use fob_bundler::{
44 HookLoadArgs, HookLoadOutput, HookLoadReturn, ModuleType, Plugin, PluginContext,
45};
46use fob_graph::analysis::extractors::{ExtractedScript, Extractor, VueExtractor};
47use std::borrow::Cow;
48
49/// Rolldown plugin that extracts JavaScript/TypeScript from Vue SFCs
50///
51/// # Features
52///
53/// - Supports both `<script>` and `<script setup>` blocks
54/// - TypeScript support via `lang="ts"` attribute
55/// - JSX/TSX support via `lang="jsx"` or `lang="tsx"`
56/// - Accurate source mapping for error reporting
57/// - Security: file size limits, tag count limits, no ReDoS vulnerabilities
58///
59/// # Security
60///
61/// The plugin enforces limits to prevent DoS attacks:
62/// - Max file size: 10MB
63/// - Max script tags: 100
64/// - Uses memchr (not regex) to avoid ReDoS
65/// - Never panics on malformed input
66#[derive(Debug, Clone, Default)]
67pub struct FobVuePlugin {
68 // Future: add configuration options here
69 // - Custom file size limits
70 // - Template compilation options
71 // - Source map generation settings
72}
73
74impl FobVuePlugin {
75 /// Creates a new Vue plugin with default settings
76 ///
77 /// # Example
78 ///
79 /// ```rust
80 /// use fob_plugin_vue::FobVuePlugin;
81 ///
82 /// let plugin = FobVuePlugin::new();
83 /// ```
84 pub fn new() -> Self {
85 Self::default()
86 }
87}
88
89impl Plugin for FobVuePlugin {
90 /// Returns the plugin name for debugging and logging
91 fn name(&self) -> Cow<'static, str> {
92 "fob-vue".into()
93 }
94
95 /// Declares which hooks this plugin uses
96 ///
97 /// This allows Rolldown to optimize by skipping unused hooks.
98 fn register_hook_usage(&self) -> fob_bundler::HookUsage {
99 use fob_bundler::HookUsage;
100 // We only use the load hook
101 HookUsage::Load
102 }
103
104 /// Load hook - intercepts `.vue` files and extracts JavaScript
105 ///
106 /// This is the core of the plugin. It:
107 /// 1. Checks if the file is a `.vue` file
108 /// 2. Reads the file from disk
109 /// 3. Parses and extracts script blocks
110 /// 4. Combines multiple scripts if needed
111 /// 5. Returns JavaScript/TypeScript to Rolldown
112 ///
113 /// # Returns
114 ///
115 /// - `Ok(Some(output))` - Successfully extracted JavaScript
116 /// - `Ok(None)` - Not a Vue file, let Rolldown handle it
117 /// - `Err(e)` - Parse error or I/O error
118 ///
119 /// # Script Combination
120 ///
121 /// When a Vue SFC has both `<script>` and `<script setup>`:
122 /// ```vue
123 /// <script>
124 /// export default { name: 'MyComponent' }
125 /// </script>
126 /// <script setup>
127 /// const count = ref(0)
128 /// </script>
129 /// ```
130 ///
131 /// We combine them as:
132 /// ```js
133 /// const count = ref(0) // <script setup> runs first
134 ///
135 /// export default { name: 'MyComponent' }
136 /// ```
137 ///
138 /// # Module Type Detection
139 ///
140 /// The `lang` attribute determines the module type:
141 /// - `lang="ts"` → TypeScript
142 /// - `lang="jsx"` → JSX
143 /// - `lang="tsx"` → TSX
144 /// - No lang or `lang="js"` → JavaScript
145 fn load(
146 &self,
147 _ctx: &PluginContext,
148 args: &HookLoadArgs<'_>,
149 ) -> impl std::future::Future<Output = HookLoadReturn> + Send {
150 // Capture data for async block
151 let id = args.id.to_string();
152
153 async move {
154 // Only handle .vue files
155 if !id.ends_with(".vue") {
156 return Ok(None);
157 }
158
159 // Read the Vue SFC source file
160 let source = std::fs::read_to_string(&id)
161 .with_context(|| format!("Failed to read Vue file: {}", id))?;
162
163 // Parse and extract script blocks
164 let scripts = VueExtractor
165 .extract(&source)
166 .with_context(|| format!("Failed to parse Vue file: {}", id))?;
167
168 // Handle no scripts case
169 if scripts.is_empty() {
170 // Return empty JavaScript module
171 return Ok(Some(HookLoadOutput {
172 code: "export default {}".into(),
173 module_type: Some(ModuleType::Js),
174 ..Default::default()
175 }));
176 }
177
178 // Combine scripts and determine module type
179 let (combined_code, module_type) = combine_scripts(&scripts);
180
181 // Return the extracted JavaScript/TypeScript
182 Ok(Some(HookLoadOutput {
183 code: combined_code.into(),
184 module_type: Some(module_type),
185 ..Default::default()
186 }))
187 }
188 }
189}
190
191/// Combines multiple script blocks and determines the appropriate module type.
192///
193/// # Algorithm
194///
195/// 1. If only one script: return it as-is with its module type
196/// 2. If multiple scripts: combine with `<script setup>` first (Vue semantics)
197/// 3. Module type priority: tsx > jsx > ts > js
198///
199/// # Examples
200///
201/// Single script:
202/// ```ignore
203/// scripts = [JavaScriptSource { source_text: "const x = 1", lang: "ts", ... }]
204/// → ("const x = 1", ModuleType::Ts)
205/// ```
206///
207/// Multiple scripts:
208/// ```ignore
209/// scripts = [
210/// JavaScriptSource { source_text: "export default {}", is_setup: false, ... },
211/// JavaScriptSource { source_text: "const x = 1", is_setup: true, ... },
212/// ]
213/// → ("const x = 1\n\nexport default {}", ModuleType::Js)
214/// ```
215fn combine_scripts(scripts: &[ExtractedScript]) -> (String, ModuleType) {
216 use fob_graph::analysis::extractors::ScriptContext;
217
218 // Single script case
219 if scripts.len() == 1 {
220 let script = &scripts[0];
221 return (
222 script.source_text.to_string(),
223 determine_module_type(script.lang),
224 );
225 }
226
227 // Multiple scripts: separate setup and regular scripts
228 let mut setup_script = None;
229 let mut regular_script = None;
230
231 for script in scripts {
232 match script.context {
233 ScriptContext::VueSetup => setup_script = Some(script),
234 ScriptContext::VueRegular => regular_script = Some(script),
235 _ => {} // Shouldn't happen for Vue
236 }
237 }
238
239 // Combine scripts (setup first, then regular)
240 let mut combined = String::new();
241 let mut detected_lang = "js";
242
243 if let Some(setup) = setup_script {
244 combined.push_str(setup.source_text);
245 detected_lang = setup.lang;
246 }
247
248 if let Some(regular) = regular_script {
249 if !combined.is_empty() {
250 combined.push_str("\n\n"); // Separate scripts with blank lines
251 }
252 combined.push_str(regular.source_text);
253
254 // Upgrade module type if regular script uses a "stronger" type
255 detected_lang = choose_stronger_lang(detected_lang, regular.lang);
256 }
257
258 (combined, determine_module_type(detected_lang))
259}
260
261/// Determines the Rolldown module type from a language identifier.
262///
263/// # Language Mapping
264///
265/// - "ts" or "typescript" → TypeScript
266/// - "jsx" → JSX
267/// - "tsx" → TSX
268/// - "js" or anything else → JavaScript
269fn determine_module_type(lang: &str) -> ModuleType {
270 match lang {
271 "ts" | "typescript" => ModuleType::Ts,
272 "jsx" => ModuleType::Jsx,
273 "tsx" => ModuleType::Tsx,
274 _ => ModuleType::Js,
275 }
276}
277
278/// Chooses the "stronger" language type for combined scripts.
279///
280/// Hierarchy: tsx > jsx > ts > js
281///
282/// This ensures we don't downgrade the module type when combining scripts.
283fn choose_stronger_lang<'a>(lang1: &'a str, lang2: &'a str) -> &'a str {
284 // Define language strength
285 let strength = |lang: &str| match lang {
286 "tsx" => 4,
287 "jsx" => 3,
288 "ts" | "typescript" => 2,
289 _ => 1,
290 };
291
292 if strength(lang1) >= strength(lang2) {
293 lang1
294 } else {
295 lang2
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 #[test]
304 fn test_plugin_creation() {
305 let plugin = FobVuePlugin::new();
306 assert_eq!(plugin.name(), "fob-vue");
307 }
308
309 #[test]
310 fn test_plugin_default() {
311 let plugin = FobVuePlugin::default();
312 assert_eq!(plugin.name(), "fob-vue");
313 }
314
315 #[test]
316 fn test_determine_module_type() {
317 assert!(matches!(determine_module_type("js"), ModuleType::Js));
318 assert!(matches!(determine_module_type("ts"), ModuleType::Ts));
319 assert!(matches!(determine_module_type("jsx"), ModuleType::Jsx));
320 assert!(matches!(determine_module_type("tsx"), ModuleType::Tsx));
321 assert!(matches!(
322 determine_module_type("typescript"),
323 ModuleType::Ts
324 ));
325 }
326
327 #[test]
328 fn test_choose_stronger_lang() {
329 assert_eq!(choose_stronger_lang("js", "ts"), "ts");
330 assert_eq!(choose_stronger_lang("ts", "tsx"), "tsx");
331 assert_eq!(choose_stronger_lang("jsx", "js"), "jsx");
332 assert_eq!(choose_stronger_lang("tsx", "ts"), "tsx");
333 assert_eq!(choose_stronger_lang("ts", "ts"), "ts");
334 }
335
336 #[test]
337 fn test_combine_single_script() {
338 use fob_graph::analysis::extractors::ScriptContext;
339 let scripts = vec![ExtractedScript::new(
340 "const x = 1;",
341 100,
342 ScriptContext::VueRegular,
343 "js",
344 )];
345 let (code, module_type) = combine_scripts(&scripts);
346 assert_eq!(code, "const x = 1;");
347 assert!(matches!(module_type, ModuleType::Js));
348 }
349
350 #[test]
351 fn test_combine_multiple_scripts() {
352 use fob_graph::analysis::extractors::ScriptContext;
353 let scripts = vec![
354 ExtractedScript::new("export default {}", 50, ScriptContext::VueRegular, "js"),
355 ExtractedScript::new("const count = ref(0)", 150, ScriptContext::VueSetup, "ts"),
356 ];
357 let (code, module_type) = combine_scripts(&scripts);
358 // Setup script should come first
359 assert!(code.starts_with("const count = ref(0)"));
360 assert!(code.contains("export default {}"));
361 // Should upgrade to TypeScript
362 assert!(matches!(module_type, ModuleType::Ts));
363 }
364}