vika-cli 1.4.0

Generate TypeScript types, Zod schemas, and Fetch-based API clients from OpenAPI/Swagger specifications
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use crate::config::model::{Config, SpecEntry};
use crate::error::Result;
use crate::formatter::FormatterManager;
use crate::generator::api_client::generate_api_client_with_registry_and_engine_and_spec;
use crate::generator::module_selector::select_modules;
use crate::generator::swagger_parser::filter_common_schemas;
use crate::generator::ts_typings::generate_typings_with_registry_and_engine_and_spec;
use crate::generator::writer::write_api_client_with_options;
use crate::generator::zod_schema::generate_zod_schemas_with_registry_and_engine_and_spec;
use crate::progress::ProgressReporter;
use std::path::PathBuf;

/// Statistics for a single spec generation run
#[derive(Debug, Clone)]
pub struct GenerationStats {
    pub spec_name: String,
    pub modules_generated: usize,
    pub files_generated: usize,
    pub modules: Vec<String>,
}

/// Hook generator type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookType {
    ReactQuery,
    Swr,
}

/// Options for generation
pub struct GenerateOptions {
    pub use_cache: bool,
    pub use_backup: bool,
    pub use_force: bool,
    pub verbose: bool,
    pub hook_type: Option<HookType>,
}

/// Generate code for a single spec
pub async fn run_single_spec(
    spec: &SpecEntry,
    config: &Config,
    options: &GenerateOptions,
) -> Result<GenerationStats> {
    let mut progress = ProgressReporter::new(options.verbose);
    // Always use spec name (even for single spec)
    let spec_name = Some(spec.name.as_str());

    progress.start_spinner(&format!("Fetching spec from: {}", spec.path));
    let parsed = crate::generator::swagger_parser::fetch_and_parse_spec_with_cache_and_name(
        &spec.path,
        options.use_cache,
        Some(&spec.name),
    )
    .await?;
    progress.finish_spinner(&format!(
        "Parsed spec with {} modules",
        parsed.modules.len()
    ));

    // Use spec-specific configs (required per spec)
    let schemas_config = &spec.schemas;
    let apis_config = &spec.apis;
    let modules_config = &spec.modules;

    // Filter out ignored modules (using spec-specific or global)
    let available_modules: Vec<String> = parsed
        .modules
        .iter()
        .filter(|m| !modules_config.ignore.contains(m))
        .cloned()
        .collect();

    if available_modules.is_empty() {
        return Err(crate::error::GenerationError::NoModulesAvailable.into());
    }

    // Use pre-selected modules from config if available, otherwise prompt interactively
    let selected_modules = if !modules_config.selected.is_empty() {
        // Validate that all selected modules are available
        let valid_selected: Vec<String> = modules_config
            .selected
            .iter()
            .filter(|m| available_modules.contains(m))
            .cloned()
            .collect();

        if valid_selected.is_empty() {
            return Err(crate::error::GenerationError::NoModulesSelected.into());
        }

        valid_selected
    } else {
        // Select modules interactively (using spec-specific or global ignore list)
        select_modules(&available_modules, &modules_config.ignore)?
    };

    // Filter common schemas based on selected modules only
    let (filtered_module_schemas, common_schemas) =
        filter_common_schemas(&parsed.module_schemas, &selected_modules);

    // Generate code for each module (using spec-specific or global output directories)
    let schemas_dir = PathBuf::from(&schemas_config.output);
    let apis_dir = PathBuf::from(&apis_config.output);
    let _root_dir = PathBuf::from(&config.root_dir);

    // Get hooks config (use defaults if not specified)
    let hooks_config = spec.hooks.clone().unwrap_or_default();

    // Runtime client is generated once at root_dir level (handled in generate.rs)

    let mut total_files = 0;

    // Generate common module first if there are shared schemas
    if !common_schemas.is_empty() {
        progress.start_spinner("Generating common schemas...");

        // Shared enum registry to ensure consistent naming between TypeScript and Zod
        let mut shared_enum_registry = std::collections::HashMap::new();

        // Initialize template engine
        let project_root = std::env::current_dir().ok();
        let template_engine =
            crate::templates::engine::TemplateEngine::new(project_root.as_deref())?;

        // Generate TypeScript typings for common schemas
        // Pass empty common_schemas list so common schemas don't prefix themselves with "Common."
        let common_types = generate_typings_with_registry_and_engine_and_spec(
            &parsed.openapi,
            &parsed.schemas,
            &common_schemas,
            &mut shared_enum_registry,
            &[], // Empty list - common schemas shouldn't prefix themselves
            Some(&template_engine),
            spec_name,
        )?;

        // Generate Zod schemas for common schemas (using same registry)
        // Pass empty common_schemas list so common schemas don't prefix themselves with "Common."
        let common_zod_schemas = generate_zod_schemas_with_registry_and_engine_and_spec(
            &parsed.openapi,
            &parsed.schemas,
            &common_schemas,
            &mut shared_enum_registry,
            &[], // Empty list - common schemas shouldn't prefix themselves
            Some(&template_engine),
            spec_name,
        )?;

        // Write common schemas
        use crate::generator::writer::write_schemas_with_module_mapping;
        let common_files = write_schemas_with_module_mapping(
            &schemas_dir,
            "common",
            &common_types,
            &common_zod_schemas,
            spec_name,
            options.use_backup,
            options.use_force,
            Some(&filtered_module_schemas),
            &common_schemas,
        )?;
        total_files += common_files.len();
        progress.finish_spinner(&format!(
            "Generated {} common schema files",
            common_files.len()
        ));
    }

    for module in &selected_modules {
        progress.start_spinner(&format!("Generating code for module: {}", module));

        // Get operations for this module
        let operations = parsed
            .operations_by_tag
            .get(module)
            .cloned()
            .unwrap_or_default();

        if operations.is_empty() {
            progress.warning(&format!("No operations found for module: {}", module));
            continue;
        }

        // Get schema names used by this module (from filtered schemas)
        let module_schema_names = filtered_module_schemas
            .get(module)
            .cloned()
            .unwrap_or_default();

        // Initialize template engine
        let project_root = std::env::current_dir().ok();
        let template_engine =
            crate::templates::engine::TemplateEngine::new(project_root.as_deref())?;

        // Shared enum registry to ensure consistent naming between TypeScript and Zod
        let mut shared_enum_registry = std::collections::HashMap::new();

        // Generate TypeScript typings
        let types = if !module_schema_names.is_empty() {
            generate_typings_with_registry_and_engine_and_spec(
                &parsed.openapi,
                &parsed.schemas,
                &module_schema_names,
                &mut shared_enum_registry,
                &common_schemas,
                Some(&template_engine),
                spec_name,
            )?
        } else {
            Vec::new()
        };

        // Generate Zod schemas (using same registry)
        let zod_schemas = if !module_schema_names.is_empty() {
            generate_zod_schemas_with_registry_and_engine_and_spec(
                &parsed.openapi,
                &parsed.schemas,
                &module_schema_names,
                &mut shared_enum_registry,
                &common_schemas,
                Some(&template_engine),
                spec_name,
            )?
        } else {
            Vec::new()
        };

        // Generate query params types and Zod schemas
        // Pass existing types and zod schemas to avoid duplicates
        use crate::generator::query_params::{
            generate_query_params_for_module, QueryParamsContext,
        };
        let query_params_result = generate_query_params_for_module(QueryParamsContext {
            openapi: &parsed.openapi,
            operations: &operations,
            enum_registry: &mut shared_enum_registry,
            template_engine: Some(&template_engine),
            spec_name,
            existing_types: &types,
            existing_zod_schemas: &zod_schemas,
        })?;

        // Generate API client (using same enum registry as schemas)
        let api_result = generate_api_client_with_registry_and_engine_and_spec(
            &parsed.openapi,
            &operations,
            module,
            &common_schemas,
            &mut shared_enum_registry,
            Some(&template_engine),
            spec_name,
            Some(&config.root_dir),
            Some(&apis_config.output),
            Some(&schemas_config.output),
        )?;

        // Response types are written to API files, not schema files
        // Combine schema types with query params types
        let mut all_types = types;
        all_types.extend(query_params_result.types);

        // Combine Zod schemas with query params Zod schemas
        let mut all_zod_schemas = zod_schemas;
        all_zod_schemas.extend(query_params_result.zod_schemas);

        // Write schemas (with backup and conflict detection)
        // Pass module_schemas mapping to enable cross-module enum imports
        use crate::generator::writer::write_schemas_with_module_mapping;
        let schema_files = write_schemas_with_module_mapping(
            &schemas_dir,
            module,
            &all_types,
            &all_zod_schemas,
            spec_name,
            options.use_backup,
            options.use_force,
            Some(&filtered_module_schemas),
            &common_schemas,
        )?;
        total_files += schema_files.len();

        // Write API client (with backup and conflict detection)
        let api_files = write_api_client_with_options(
            &apis_dir,
            module,
            &api_result.functions,
            spec_name,
            options.use_backup,
            options.use_force,
        )?;
        total_files += api_files.len();

        // Determine hook type: options.hook_type (from CLI) takes precedence,
        // otherwise check spec's hooks.library config
        let hook_type = options.hook_type.or_else(|| {
            hooks_config
                .library
                .as_ref()
                .and_then(|lib| match lib.as_str() {
                    "react-query" => Some(HookType::ReactQuery),
                    "swr" => Some(HookType::Swr),
                    _ => None,
                })
        });

        // Generate hooks if requested
        if let Some(hook_type) = hook_type {
            progress.start_spinner(&format!("Generating hooks for module: {}", module));

            // Generate query keys first (hooks depend on them)
            use crate::generator::query_keys::generate_query_keys;
            let query_keys_context = generate_query_keys(&operations, module, spec_name);

            // Render query keys template
            let query_keys_content = template_engine.render(
                crate::templates::registry::TemplateId::QueryKeys,
                &query_keys_context,
            )?;

            // Write query keys file using configured output directory
            // Note: output_dir already includes spec_name if needed (from config), just like schemas/apis
            let query_keys_output = PathBuf::from(&hooks_config.query_keys_output);

            use crate::generator::writer::write_query_keys_with_options;
            write_query_keys_with_options(
                &query_keys_output,
                module,
                &query_keys_content,
                spec_name,
                options.use_backup,
                options.use_force,
            )?;
            total_files += 1;

            // Generate hooks based on type
            let hooks = match hook_type {
                HookType::ReactQuery => {
                    use crate::generator::hooks::react_query::generate_react_query_hooks;
                    generate_react_query_hooks(
                        &parsed.openapi,
                        &operations,
                        module,
                        spec_name,
                        &common_schemas,
                        &mut shared_enum_registry,
                        &template_engine,
                        Some(&apis_config.output),
                        Some(&schemas_config.output),
                        Some(&hooks_config.output),
                        Some(&hooks_config.query_keys_output),
                    )?
                }
                HookType::Swr => {
                    use crate::generator::hooks::swr::generate_swr_hooks;
                    generate_swr_hooks(
                        &parsed.openapi,
                        &operations,
                        module,
                        spec_name,
                        &common_schemas,
                        &mut shared_enum_registry,
                        &template_engine,
                        Some(&apis_config.output),
                        Some(&schemas_config.output),
                        Some(&hooks_config.output),
                        Some(&hooks_config.query_keys_output),
                    )?
                }
            };

            // Write hooks files using configured output directory
            // Note: output_dir already includes spec_name if needed (from config), just like schemas/apis
            let hooks_output = PathBuf::from(&hooks_config.output);

            use crate::generator::writer::write_hooks_with_options;
            let hook_files = write_hooks_with_options(
                &hooks_output,
                module,
                &hooks,
                spec_name,
                options.use_backup,
                options.use_force,
            )?;
            total_files += hook_files.len();

            progress.finish_spinner(&format!(
                "Generated {} hook files for module: {}",
                hook_files.len(),
                module
            ));
        }

        progress.finish_spinner(&format!(
            "Generated {} files for module: {}",
            schema_files.len() + api_files.len(),
            module
        ));
    }

    // Format all generated files with prettier/biome if available
    let mut all_generated_files = Vec::new();

    // Collect schema files recursively
    if schemas_dir.exists() {
        collect_ts_files(&schemas_dir, &mut all_generated_files)?;
    }

    // Collect API files recursively
    if apis_dir.exists() {
        collect_ts_files(&apis_dir, &mut all_generated_files)?;
    }

    // Collect hook files recursively if hooks were generated
    if options.hook_type.is_some() {
        let root_dir = std::env::current_dir().ok();
        let hooks_dir = if let Some(ref root) = root_dir {
            if let Some(spec) = spec_name {
                root.join("src").join("hooks").join(spec)
            } else {
                root.join("src").join("hooks")
            }
        } else {
            PathBuf::from("src/hooks")
        };
        if hooks_dir.exists() {
            collect_ts_files(&hooks_dir, &mut all_generated_files)?;
        }

        // Collect query keys files
        let query_keys_dir = if let Some(ref root) = root_dir {
            if let Some(spec) = spec_name {
                root.join("src").join("query-keys").join(spec)
            } else {
                root.join("src").join("query-keys")
            }
        } else {
            PathBuf::from("src/query-keys")
        };
        if query_keys_dir.exists() {
            collect_ts_files(&query_keys_dir, &mut all_generated_files)?;
        }
    }

    // Format files if formatter is available
    if !all_generated_files.is_empty() {
        // Get current directory to resolve relative paths
        let current_dir =
            std::env::current_dir().map_err(|e| crate::error::FileSystemError::ReadFileFailed {
                path: ".".to_string(),
                source: e,
            })?;

        // Resolve to absolute paths
        let schemas_dir_abs = if schemas_dir.is_absolute() {
            schemas_dir.clone()
        } else {
            current_dir.join(&schemas_dir)
        };
        let apis_dir_abs = if apis_dir.is_absolute() {
            apis_dir.clone()
        } else {
            current_dir.join(&apis_dir)
        };

        let output_base = schemas_dir_abs
            .parent()
            .and_then(|p| p.parent())
            .or_else(|| apis_dir_abs.parent().and_then(|p| p.parent()));

        let formatter = if let Some(base_dir) = output_base {
            FormatterManager::detect_formatter_from_dir(base_dir)
                .or_else(FormatterManager::detect_formatter)
        } else {
            FormatterManager::detect_formatter()
        };

        if let Some(formatter) = formatter {
            progress.start_spinner("Formatting generated files...");
            let original_dir = std::env::current_dir().map_err(|e| {
                crate::error::FileSystemError::ReadFileFailed {
                    path: ".".to_string(),
                    source: e,
                }
            })?;

            if let Some(output_base) = output_base {
                // Ensure output_base is not empty
                if output_base.as_os_str().is_empty() {
                    // Fallback: use current directory
                    FormatterManager::format_files(&all_generated_files, formatter)?;
                } else {
                    std::env::set_current_dir(output_base).map_err(|e| {
                        crate::error::FileSystemError::ReadFileFailed {
                            path: output_base.display().to_string(),
                            source: e,
                        }
                    })?;

                    let relative_files: Vec<PathBuf> = all_generated_files
                        .iter()
                        .filter_map(|p| {
                            p.strip_prefix(output_base)
                                .ok()
                                .map(|p| p.to_path_buf())
                                .filter(|p| !p.as_os_str().is_empty())
                        })
                        .collect();

                    if !relative_files.is_empty() {
                        let result = FormatterManager::format_files(&relative_files, formatter);

                        std::env::set_current_dir(&original_dir).map_err(|e| {
                            crate::error::FileSystemError::ReadFileFailed {
                                path: original_dir.display().to_string(),
                                source: e,
                            }
                        })?;

                        result?;

                        // Update metadata for formatted files to reflect formatted content hash (batch update)
                        use crate::generator::writer::batch_update_file_metadata_from_disk;
                        if let Err(e) = batch_update_file_metadata_from_disk(&all_generated_files) {
                            // Log but don't fail - metadata update is best effort
                            progress.warning(&format!("Failed to update metadata: {}", e));
                        }
                    } else {
                        std::env::set_current_dir(&original_dir).map_err(|e| {
                            crate::error::FileSystemError::ReadFileFailed {
                                path: original_dir.display().to_string(),
                                source: e,
                            }
                        })?;
                    }
                }
            } else {
                FormatterManager::format_files(&all_generated_files, formatter)?;

                // Update metadata for formatted files to reflect formatted content hash (batch update)
                use crate::generator::writer::batch_update_file_metadata_from_disk;
                if let Err(e) = batch_update_file_metadata_from_disk(&all_generated_files) {
                    // Log but don't fail - metadata update is best effort
                    progress.warning(&format!("Failed to update metadata: {}", e));
                }
            }
            progress.finish_spinner("Files formatted");
        }
    }

    Ok(GenerationStats {
        spec_name: spec.name.clone(),
        modules_generated: selected_modules.len(),
        files_generated: total_files,
        modules: selected_modules,
    })
}

/// Generate code for multiple specs sequentially
pub async fn run_all_specs(
    specs: &[SpecEntry],
    config: &Config,
    options: &GenerateOptions,
) -> Result<Vec<GenerationStats>> {
    let mut stats = Vec::new();
    for spec in specs {
        let result = run_single_spec(spec, config, options).await?;
        stats.push(result);
    }
    Ok(stats)
}

fn collect_ts_files(dir: &std::path::Path, files: &mut Vec<PathBuf>) -> Result<()> {
    if dir.is_dir() {
        for entry in
            std::fs::read_dir(dir).map_err(|e| crate::error::FileSystemError::ReadFileFailed {
                path: dir.display().to_string(),
                source: e,
            })?
        {
            let entry = entry.map_err(|e| crate::error::FileSystemError::ReadFileFailed {
                path: dir.display().to_string(),
                source: e,
            })?;
            let path = entry.path();
            // Skip if path is empty or invalid
            if path.as_os_str().is_empty() {
                continue;
            }
            if path.is_dir() {
                collect_ts_files(&path, files)?;
            } else if path.extension().and_then(|s| s.to_str()) == Some("ts") {
                files.push(path);
            }
        }
    }
    Ok(())
}