tauri-typegen 0.5.0

A rust crate that automatically generates TypeScript models and bindings from your Tauri commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
pub mod dependency_resolver;
pub mod generation_cache;
pub mod output_manager;
pub mod project_scanner;

use crate::analysis::CommandAnalyzer;
use crate::generators::create_generator;
use crate::interface::config::{ConfigError, GenerateConfig};
use crate::interface::output::{Logger, ProgressReporter};
use std::path::Path;

pub use dependency_resolver::*;
pub use generation_cache::*;
pub use output_manager::*;
pub use project_scanner::*;

/// Build-time code generation orchestrator.
///
/// Integrates TypeScript binding generation into Rust build scripts.
/// This allows automatic regeneration of bindings whenever the Rust code changes.
pub struct BuildSystem {
    logger: Logger,
}

impl BuildSystem {
    /// Create a new build system instance.
    ///
    /// # Arguments
    ///
    /// * `verbose` - Enable verbose output
    /// * `debug` - Enable debug logging
    pub fn new(verbose: bool, debug: bool) -> Self {
        Self {
            logger: Logger::new(verbose, debug),
        }
    }

    /// Generate TypeScript bindings at build time.
    ///
    /// This is the recommended way to integrate tauri-typegen into your build process.
    /// Call this from your `src-tauri/build.rs` file to automatically generate bindings
    /// whenever you run `cargo build` or `cargo tauri dev`.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if generation fails.
    ///
    /// # Example
    ///
    /// In `src-tauri/build.rs`:
    ///
    /// ```rust,ignore
    /// fn main() {
    ///     // Generate TypeScript bindings before build
    ///     tauri_typegen::BuildSystem::generate_at_build_time()
    ///         .expect("Failed to generate TypeScript bindings");
    ///
    ///     tauri_build::build()
    /// }
    /// ```
    ///
    /// # Configuration
    ///
    /// Reads configuration from `tauri.conf.json` in the project root.
    /// If no configuration is found, uses default settings with vanilla TypeScript output.
    pub fn generate_at_build_time() -> Result<(), Box<dyn std::error::Error>> {
        let build_system = Self::new(false, false);
        build_system.run_generation()
    }

    /// Run the complete generation process
    pub fn run_generation(&self) -> Result<(), Box<dyn std::error::Error>> {
        let mut reporter = ProgressReporter::new(self.logger.clone(), 5);

        reporter.start_step("Detecting Tauri project");
        let project_scanner = ProjectScanner::new();
        let project_info = match project_scanner.detect_project()? {
            Some(info) => {
                reporter.complete_step(Some(&format!(
                    "Found project at {}",
                    info.root_path.display()
                )));
                info
            }
            None => {
                reporter.complete_step(Some("No Tauri project detected, skipping generation"));
                return Ok(());
            }
        };

        reporter.start_step("Loading configuration");
        let config = self.load_configuration(&project_info)?;
        reporter.complete_step(Some(&format!(
            "Using {} validation with output to {}",
            config.validation_library, config.output_path
        )));

        reporter.start_step("Setting up build dependencies");
        self.setup_build_dependencies(&config)?;
        reporter.complete_step(None);

        reporter.start_step("Analyzing and generating bindings");
        let generated_files = self.generate_bindings(&config)?;
        reporter.complete_step(Some(&format!("Generated {} files", generated_files.len())));

        reporter.start_step("Managing output");
        let mut output_manager = OutputManager::new(&config.output_path);
        output_manager.finalize_generation(&generated_files)?;
        reporter.complete_step(None);

        reporter.finish(&format!(
            "Successfully generated TypeScript bindings for {} commands",
            generated_files.len()
        ));

        Ok(())
    }

    fn load_configuration(
        &self,
        project_info: &ProjectInfo,
    ) -> Result<GenerateConfig, ConfigError> {
        // Try to load from tauri.conf.json first
        if let Some(tauri_config_path) = &project_info.tauri_config_path {
            if tauri_config_path.exists() {
                match GenerateConfig::from_tauri_config(tauri_config_path) {
                    Ok(Some(config)) => {
                        self.logger
                            .debug("Loaded configuration from tauri.conf.json");
                        return Ok(config);
                    }
                    Ok(None) => {}
                    Err(e) => {
                        self.logger.warning(&format!(
                            "Failed to load config from tauri.conf.json: {}. Using defaults.",
                            e
                        ));
                    }
                }
            }
        }

        // Try standalone config file
        let standalone_config = project_info.root_path.join("typegen.json");
        if standalone_config.exists() {
            match GenerateConfig::from_file(&standalone_config) {
                Ok(config) => {
                    self.logger.debug("Loaded configuration from typegen.json");
                    return Ok(config);
                }
                Err(e) => {
                    self.logger.warning(&format!(
                        "Failed to load config from typegen.json: {}. Using defaults.",
                        e
                    ));
                }
            }
        }

        // Use defaults
        self.logger.debug("Using default configuration");
        Ok(GenerateConfig::default())
    }

    fn setup_build_dependencies(
        &self,
        config: &GenerateConfig,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Set up cargo rerun directives
        println!("cargo:rerun-if-changed={}", config.project_path);

        // Watch for changes in configuration files
        if Path::new("tauri.conf.json").exists() {
            println!("cargo:rerun-if-changed=tauri.conf.json");
        }
        if Path::new("typegen.json").exists() {
            println!("cargo:rerun-if-changed=typegen.json");
        }

        // Watch output directory for cleanup detection
        if Path::new(&config.output_path).exists() {
            println!("cargo:rerun-if-changed={}", config.output_path);
        }

        Ok(())
    }

    fn generate_bindings(
        &self,
        config: &GenerateConfig,
    ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let mut analyzer = CommandAnalyzer::new();
        let commands = analyzer.analyze_project(&config.project_path)?;

        if commands.is_empty() {
            self.logger
                .info("No Tauri commands found. Skipping generation.");
            return Ok(vec![]);
        }

        // Check cache to see if regeneration is needed (unless force is set)
        let discovered_structs = analyzer.get_discovered_structs();
        if config.should_force() {
            self.logger.verbose("Force flag set, regenerating bindings");
        } else {
            match GenerationCache::needs_regeneration(
                &config.output_path,
                &commands,
                discovered_structs,
                config,
            ) {
                Ok(false) => {
                    self.logger
                        .verbose("Cache hit - no changes detected, skipping generation");
                    // Return list of existing files without regenerating
                    let output_manager = OutputManager::new(&config.output_path);
                    if let Ok(metadata) = output_manager.get_generation_metadata() {
                        return Ok(metadata.files.iter().map(|f| f.name.clone()).collect());
                    }
                    // If we can't get existing files, fall through to regenerate
                    self.logger
                        .debug("Could not get existing file list, regenerating");
                }
                Ok(true) => {
                    self.logger
                        .verbose("Cache miss - changes detected, regenerating");
                }
                Err(e) => {
                    self.logger
                        .debug(&format!("Cache check failed: {}, regenerating", e));
                }
            }
        }

        let validation = match config.validation_library.as_str() {
            "zod" | "none" => Some(config.validation_library.clone()),
            _ => return Err("Invalid validation library. Use 'zod' or 'none'".into()),
        };

        let mut generator = create_generator(validation);
        let generated_files = generator.generate_models(
            &commands,
            discovered_structs,
            &config.output_path,
            &analyzer,
            config,
        )?;

        // Generate dependency visualization if requested
        if config.should_visualize_deps() {
            self.generate_dependency_visualization(&analyzer, &commands, &config.output_path)?;
        }

        // Save cache after successful generation
        let cache = GenerationCache::new(&commands, discovered_structs, config)?;
        if let Err(e) = cache.save(&config.output_path) {
            self.logger
                .warning(&format!("Failed to save generation cache: {}", e));
        }

        Ok(generated_files)
    }

    fn generate_dependency_visualization(
        &self,
        analyzer: &CommandAnalyzer,
        commands: &[crate::models::CommandInfo],
        output_path: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        use std::fs;

        self.logger.debug("Generating dependency visualization");

        let text_viz = analyzer.visualize_dependencies(commands);
        let viz_file_path = Path::new(output_path).join("dependency-graph.txt");
        fs::write(&viz_file_path, text_viz)?;

        let dot_viz = analyzer.generate_dot_graph(commands);
        let dot_file_path = Path::new(output_path).join("dependency-graph.dot");
        fs::write(&dot_file_path, dot_viz)?;

        self.logger.verbose(&format!(
            "Generated dependency graphs: {} and {}",
            viz_file_path.display(),
            dot_file_path.display()
        ));

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_build_system_creation() {
        let build_system = BuildSystem::new(true, false);
        assert!(build_system
            .logger
            .should_log(crate::interface::output::LogLevel::Verbose));
    }

    #[test]
    fn test_load_default_configuration() {
        let temp_dir = TempDir::new().unwrap();
        let project_info = ProjectInfo {
            root_path: temp_dir.path().to_path_buf(),
            src_tauri_path: temp_dir.path().join("src-tauri"),
            tauri_config_path: None,
        };

        let build_system = BuildSystem::new(false, false);
        let config = build_system.load_configuration(&project_info).unwrap();

        assert_eq!(config.validation_library, "none");
        assert_eq!(config.project_path, "./src-tauri");
    }

    #[test]
    fn test_load_configuration_from_tauri_config() {
        let temp_dir = TempDir::new().unwrap();
        let tauri_config_path = temp_dir.path().join("tauri.conf.json");

        // Create the project path directory so validation passes
        let custom_src_path = temp_dir.path().join("custom-src");
        std::fs::create_dir_all(&custom_src_path).unwrap();

        // Create a tauri.conf.json with typegen plugin configuration
        let config_content = format!(
            r#"{{
            "plugins": {{
                "typegen": {{
                    "projectPath": "{}",
                    "outputPath": "./custom-output",
                    "validationLibrary": "zod"
                }}
            }}
        }}"#,
            custom_src_path.to_string_lossy()
        );
        std::fs::write(&tauri_config_path, &config_content).unwrap();

        let project_info = ProjectInfo {
            root_path: temp_dir.path().to_path_buf(),
            src_tauri_path: temp_dir.path().join("src-tauri"),
            tauri_config_path: Some(tauri_config_path),
        };

        let build_system = BuildSystem::new(false, false);
        let config = build_system.load_configuration(&project_info).unwrap();

        assert_eq!(config.validation_library, "zod");
        assert_eq!(config.output_path, "./custom-output");
    }

    #[test]
    fn test_load_configuration_from_standalone_file() {
        let temp_dir = TempDir::new().unwrap();
        let typegen_config_path = temp_dir.path().join("typegen.json");

        // Create a project path that exists for validation
        let project_path = temp_dir.path().join("src-tauri");
        std::fs::create_dir_all(&project_path).unwrap();

        // Create a standalone typegen.json configuration
        let config_content = format!(
            r#"{{
            "project_path": "{}",
            "output_path": "./standalone-output",
            "validation_library": "zod"
        }}"#,
            project_path.to_string_lossy()
        );
        std::fs::write(&typegen_config_path, config_content).unwrap();

        let project_info = ProjectInfo {
            root_path: temp_dir.path().to_path_buf(),
            src_tauri_path: project_path.clone(),
            tauri_config_path: None,
        };

        let build_system = BuildSystem::new(false, false);
        let config = build_system.load_configuration(&project_info).unwrap();

        assert_eq!(config.validation_library, "zod");
        assert_eq!(config.output_path, "./standalone-output");
    }

    #[test]
    fn test_load_configuration_falls_back_on_invalid_tauri_config() {
        let temp_dir = TempDir::new().unwrap();
        let tauri_config_path = temp_dir.path().join("tauri.conf.json");

        // Create an invalid tauri.conf.json (no typegen section)
        let config_content = r#"{"build": {}}"#;
        std::fs::write(&tauri_config_path, config_content).unwrap();

        let project_info = ProjectInfo {
            root_path: temp_dir.path().to_path_buf(),
            src_tauri_path: temp_dir.path().join("src-tauri"),
            tauri_config_path: Some(tauri_config_path),
        };

        let build_system = BuildSystem::new(false, false);
        let config = build_system.load_configuration(&project_info).unwrap();

        // Should fall back to defaults
        assert_eq!(config.validation_library, "none");
        assert_eq!(config.project_path, "./src-tauri");
    }

    #[test]
    fn test_build_system_with_verbose_logging() {
        let build_system = BuildSystem::new(true, true);
        assert!(build_system
            .logger
            .should_log(crate::interface::output::LogLevel::Verbose));
        assert!(build_system
            .logger
            .should_log(crate::interface::output::LogLevel::Debug));
    }

    #[test]
    fn test_build_system_without_verbose_logging() {
        let build_system = BuildSystem::new(false, false);
        assert!(!build_system
            .logger
            .should_log(crate::interface::output::LogLevel::Verbose));
        assert!(!build_system
            .logger
            .should_log(crate::interface::output::LogLevel::Debug));
    }
}