evenframe 0.1.6

A unified framework for TypeScript type generation and database schema synchronization
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
//! Typesync command - generates TypeScript types and schemas.

use crate::cli::{Cli, TypeFormat, TypesyncArgs, TypesyncCommands};
use crate::config_builders;
use evenframe_core::{
    config::EvenframeConfig,
    error::Result,
    types::ForeignTypeRegistry,
    typesync::{
        arktype::generate_arktype_type_string,
        config::{FileNamingConvention, OutputMode},
        effect::{generate_effect_schema_for_types, generate_effect_schema_string},
        file_grouping::{FileOutputPlan, compute_file_grouping},
        flatbuffers::generate_flatbuffers_schema_string,
        import_resolver::{
            barrel_filename, format_imports, generate_barrel_file, resolve_imports,
            type_name_to_filename,
        },
        macroforge::{
            compute_extra_imports, compute_macro_import_line, generate_macroforge_for_types,
            generate_macroforge_type_string,
        },
        protobuf::generate_protobuf_schema_string,
    },
};
use std::collections::BTreeSet;
use std::path::Path;
use tracing::{debug, error, info, warn};

/// Runs the typesync command.
pub async fn run(_cli: &Cli, args: TypesyncArgs) -> Result<()> {
    info!("Starting type generation");

    // Load configuration
    let config = match EvenframeConfig::new() {
        Ok(cfg) => {
            info!("Configuration loaded successfully");
            cfg
        }
        Err(e) => {
            error!("Failed to load configuration: {}", e);
            return Err(e);
        }
    };

    // Build all configs and filter to typesync-eligible types
    let build_config = config_builders::BuildConfig::from_toml()?;
    let (enums, tables, objects) = config_builders::build_all_configs(&build_config)?;
    let (enums, tables, objects) = config_builders::filter_for_typesync(enums, tables, objects);
    let structs = config_builders::merge_tables_and_objects(&tables, &objects);
    let registry = ForeignTypeRegistry::from_config(&config.general.foreign_types);

    info!(
        "Found {} enums, {} tables, {} objects",
        enums.len(),
        tables.len(),
        objects.len()
    );

    // Determine output mode: CLI flag overrides config.
    let output_mode = if args.per_file {
        OutputMode::PerFile
    } else {
        config.typesync.output.mode
    };
    let barrel_file = config.typesync.output.barrel_file;
    let file_naming = config.typesync.output.file_naming;
    let file_extension = &config.typesync.output.file_extension;
    let array_style = config.typesync.output.array_style;

    // Handle subcommands for specific formats
    if let Some(cmd) = args.command {
        match cmd {
            TypesyncCommands::Arktype(arktype_args) => {
                let output_path = arktype_args
                    .output
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_else(|| format!("{}arktype.ts", config.typesync.output_path));
                if output_mode == OutputMode::PerFile {
                    warn!(
                        "ArkType does not support per-file output (scope requires all types in one file). Falling back to single-file mode."
                    );
                }
                generate_arktype(&structs, &enums, &output_path, &registry)?;
            }
            TypesyncCommands::Effect(effect_args) => {
                let output_path = effect_args
                    .output
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_else(|| format!("{}bindings.ts", config.typesync.output_path));
                match output_mode {
                    OutputMode::Single => {
                        generate_effect(&structs, &enums, &output_path, &registry)?
                    }
                    OutputMode::PerFile => generate_effect_per_file(EffectPerFileArgs {
                        structs: &structs,
                        enums: &enums,
                        base_output_path: &config.typesync.output_path,
                        subdir: "effect",
                        barrel_file,
                        naming: file_naming,
                        file_ext: file_extension,
                        registry: &registry,
                    })?,
                }
            }
            TypesyncCommands::Macroforge(macroforge_args) => {
                let output_path = macroforge_args
                    .output
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_else(|| format!("{}macroforge.ts", config.typesync.output_path));
                match output_mode {
                    OutputMode::Single => {
                        generate_macroforge(&structs, &enums, &output_path, array_style, &registry)?
                    }
                    OutputMode::PerFile => generate_macroforge_per_file(MacroforgePerFileArgs {
                        structs: &structs,
                        enums: &enums,
                        base_output_path: &config.typesync.output_path,
                        barrel_file,
                        naming: file_naming,
                        file_ext: file_extension,
                        array_style,
                        registry: &registry,
                    })?,
                }
            }
            TypesyncCommands::Flatbuffers(fbs_args) => {
                let output_path = fbs_args
                    .output
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_else(|| format!("{}schema.fbs", config.typesync.output_path));
                let namespace = fbs_args
                    .namespace
                    .or(config.typesync.flatbuffers_namespace.clone());
                generate_flatbuffers(
                    &structs,
                    &enums,
                    &output_path,
                    namespace.as_deref(),
                    &registry,
                )?;
            }
            TypesyncCommands::Protobuf(proto_args) => {
                let output_path = proto_args
                    .output
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_else(|| format!("{}schema.proto", config.typesync.output_path));
                let package = proto_args
                    .package
                    .or(config.typesync.protobuf_package.clone());
                let import_validate = if proto_args.no_import_validate {
                    false
                } else if proto_args.import_validate {
                    true
                } else {
                    config.typesync.protobuf_import_validate
                };
                generate_protobuf(
                    &structs,
                    &enums,
                    &output_path,
                    package.as_deref(),
                    import_validate,
                    &registry,
                )?;
            }
        }
        return Ok(());
    }

    // Determine which formats to generate
    let mut formats_to_generate: BTreeSet<TypeFormat> = BTreeSet::new();

    if let Some(ref formats) = args.formats {
        // Use explicit formats from CLI
        formats_to_generate.extend(formats.iter().cloned());
    } else {
        // Use config file settings
        if config.typesync.should_generate_arktype_types {
            formats_to_generate.insert(TypeFormat::Arktype);
        }
        if config.typesync.should_generate_effect_types {
            formats_to_generate.insert(TypeFormat::Effect);
        }
        if config.typesync.should_generate_macroforge_types {
            formats_to_generate.insert(TypeFormat::Macroforge);
        }
        if config.typesync.should_generate_flatbuffers_types {
            formats_to_generate.insert(TypeFormat::Flatbuffers);
        }
        if config.typesync.should_generate_protobuf_types {
            formats_to_generate.insert(TypeFormat::Protobuf);
        }
    }

    // Remove skipped formats
    if let Some(ref skip) = args.skip {
        for format in skip {
            formats_to_generate.remove(format);
        }
    }

    // Generate each format
    for format in &formats_to_generate {
        match format {
            TypeFormat::Arktype => {
                if output_mode == OutputMode::PerFile {
                    warn!(
                        "ArkType does not support per-file output (scope requires all types in one file). Falling back to single-file mode."
                    );
                }
                let path = format!("{}arktype.ts", config.typesync.output_path);
                generate_arktype(&structs, &enums, &path, &registry)?;
            }
            TypeFormat::Effect => match output_mode {
                OutputMode::Single => {
                    let path = format!("{}bindings.ts", config.typesync.output_path);
                    generate_effect(&structs, &enums, &path, &registry)?;
                }
                OutputMode::PerFile => {
                    generate_effect_per_file(EffectPerFileArgs {
                        structs: &structs,
                        enums: &enums,
                        base_output_path: &config.typesync.output_path,
                        subdir: "effect",
                        barrel_file,
                        naming: file_naming,
                        file_ext: file_extension,
                        registry: &registry,
                    })?;
                }
            },
            TypeFormat::Macroforge => match output_mode {
                OutputMode::Single => {
                    let path = format!("{}macroforge.ts", config.typesync.output_path);
                    generate_macroforge(&structs, &enums, &path, array_style, &registry)?;
                }
                OutputMode::PerFile => {
                    generate_macroforge_per_file(MacroforgePerFileArgs {
                        structs: &structs,
                        enums: &enums,
                        base_output_path: &config.typesync.output_path,
                        barrel_file,
                        naming: file_naming,
                        file_ext: file_extension,
                        array_style,
                        registry: &registry,
                    })?;
                }
            },
            TypeFormat::Flatbuffers => {
                let path = format!("{}schema.fbs", config.typesync.output_path);
                generate_flatbuffers(
                    &structs,
                    &enums,
                    &path,
                    config.typesync.flatbuffers_namespace.as_deref(),
                    &registry,
                )?;
            }
            TypeFormat::Protobuf => {
                let path = format!("{}schema.proto", config.typesync.output_path);
                generate_protobuf(
                    &structs,
                    &enums,
                    &path,
                    config.typesync.protobuf_package.as_deref(),
                    config.typesync.protobuf_import_validate,
                    &registry,
                )?;
            }
        }
    }

    info!(
        "Type generation complete. Generated {} format(s)",
        formats_to_generate.len()
    );
    Ok(())
}

fn generate_arktype(
    structs: &std::collections::BTreeMap<String, evenframe_core::types::StructConfig>,
    enums: &std::collections::BTreeMap<String, evenframe_core::types::TaggedUnion>,
    output_path: &str,
    registry: &ForeignTypeRegistry,
) -> Result<()> {
    info!("Generating ArkType types to {}", output_path);
    let content = generate_arktype_type_string(structs, enums, false, registry);
    let full_content = format!(
        "import {{ scope }} from 'arktype';\n\n{}\n\n export const validator = scope({{\n  ...bindings.export(),\n}}).export();",
        content
    );
    std::fs::write(output_path, full_content)?;
    debug!("ArkType types written successfully");
    Ok(())
}

fn generate_effect(
    structs: &std::collections::BTreeMap<String, evenframe_core::types::StructConfig>,
    enums: &std::collections::BTreeMap<String, evenframe_core::types::TaggedUnion>,
    output_path: &str,
    registry: &ForeignTypeRegistry,
) -> Result<()> {
    info!("Generating Effect schemas to {}", output_path);
    let content = generate_effect_schema_string(structs, enums, false, registry);
    let full_content = format!("import {{ Schema }} from \"effect\";\n\n{}", content);
    std::fs::write(output_path, full_content)?;
    debug!("Effect schemas written successfully");
    Ok(())
}

struct EffectPerFileArgs<'a> {
    structs: &'a std::collections::BTreeMap<String, evenframe_core::types::StructConfig>,
    enums: &'a std::collections::BTreeMap<String, evenframe_core::types::TaggedUnion>,
    base_output_path: &'a str,
    subdir: &'a str,
    barrel_file: bool,
    naming: FileNamingConvention,
    file_ext: &'a str,
    registry: &'a ForeignTypeRegistry,
}

fn generate_effect_per_file(args: EffectPerFileArgs<'_>) -> Result<()> {
    let EffectPerFileArgs {
        structs,
        enums,
        base_output_path,
        subdir,
        barrel_file,
        naming,
        file_ext,
        registry,
    } = args;

    let plan = compute_file_grouping(structs, enums);
    let dir = Path::new(base_output_path).join(subdir);
    std::fs::create_dir_all(&dir)?;
    cleanup_obsolete_files(&dir, &plan, naming, file_ext)?;

    info!(
        "Generating Effect schemas (per-file) to {} ({} files)",
        dir.display(),
        plan.groups.len()
    );

    for group in &plan.groups {
        let imports = resolve_imports(group, &plan, structs, enums, naming, file_ext);
        let type_names = group.all_types();
        let body = generate_effect_schema_for_types(&type_names, structs, enums, registry);

        let mut file_content = String::new();
        file_content.push_str("import { Schema } from \"effect\";\n");
        let import_lines = format_imports(&imports);
        if !import_lines.is_empty() {
            file_content.push_str(&import_lines);
            file_content.push('\n');
        }
        file_content.push('\n');
        file_content.push_str(&body);

        let filename = type_name_to_filename(&group.primary_type, naming);
        let file_path = dir.join(format!("{}{}", filename, file_ext));
        std::fs::write(&file_path, file_content)?;
        debug!("Written {}", file_path.display());
    }

    if barrel_file {
        let barrel_content = generate_barrel_file(&plan, naming, file_ext);
        let barrel_path = dir.join(barrel_filename(file_ext));
        std::fs::write(&barrel_path, barrel_content)?;
        debug!("Written barrel file {}", barrel_path.display());
    }

    info!("Effect per-file generation complete");
    Ok(())
}

fn generate_macroforge(
    structs: &std::collections::BTreeMap<String, evenframe_core::types::StructConfig>,
    enums: &std::collections::BTreeMap<String, evenframe_core::types::TaggedUnion>,
    output_path: &str,
    array_style: evenframe_core::typesync::config::ArrayStyle,
    registry: &ForeignTypeRegistry,
) -> Result<()> {
    info!("Generating Macroforge types to {}", output_path);
    let content = generate_macroforge_type_string(structs, enums, false, array_style, registry);
    std::fs::write(output_path, content)?;
    debug!("Macroforge types written successfully");
    Ok(())
}

struct MacroforgePerFileArgs<'a> {
    structs: &'a std::collections::BTreeMap<String, evenframe_core::types::StructConfig>,
    enums: &'a std::collections::BTreeMap<String, evenframe_core::types::TaggedUnion>,
    base_output_path: &'a str,
    barrel_file: bool,
    naming: FileNamingConvention,
    file_ext: &'a str,
    array_style: evenframe_core::typesync::config::ArrayStyle,
    registry: &'a ForeignTypeRegistry,
}

fn generate_macroforge_per_file(args: MacroforgePerFileArgs<'_>) -> Result<()> {
    let MacroforgePerFileArgs {
        structs,
        enums,
        base_output_path,
        barrel_file,
        naming,
        file_ext,
        array_style,
        registry,
    } = args;
    let plan = compute_file_grouping(structs, enums);
    let dir = Path::new(base_output_path);
    std::fs::create_dir_all(dir)?;
    cleanup_obsolete_files(dir, &plan, naming, file_ext)?;

    info!(
        "Generating Macroforge types (per-file) to {} ({} files)",
        dir.display(),
        plan.groups.len()
    );

    for group in &plan.groups {
        let imports = resolve_imports(group, &plan, structs, enums, naming, file_ext);
        let type_names = group.all_types();
        let body =
            generate_macroforge_for_types(&type_names, structs, enums, array_style, registry);

        let mut file_content = String::new();

        // Add macro import line if types have non-standard derives
        if let Some(macro_import) = compute_macro_import_line(&type_names, structs, enums) {
            file_content.push_str(&macro_import);
            file_content.push('\n');
        }

        // Add extra imports (effect types, RecordLink)
        let extra_imports = compute_extra_imports(&type_names, structs, enums, registry);
        for import_line in &extra_imports {
            file_content.push_str(import_line);
            file_content.push('\n');
        }

        let import_lines = format_imports(&imports);
        if !import_lines.is_empty() {
            file_content.push_str(&import_lines);
            file_content.push('\n');
        }
        if !file_content.is_empty() {
            file_content.push('\n');
        }
        file_content.push_str(&body);

        let filename = type_name_to_filename(&group.primary_type, naming);
        let file_path = dir.join(format!("{}{}", filename, file_ext));
        std::fs::write(&file_path, file_content)?;
        debug!("Written {}", file_path.display());
    }

    if barrel_file {
        let barrel_content = generate_barrel_file(&plan, naming, file_ext);
        let barrel_path = dir.join(barrel_filename(file_ext));
        std::fs::write(&barrel_path, barrel_content)?;
        debug!("Written barrel file {}", barrel_path.display());
    }

    info!("Macroforge per-file generation complete");
    Ok(())
}

fn generate_flatbuffers(
    structs: &std::collections::BTreeMap<String, evenframe_core::types::StructConfig>,
    enums: &std::collections::BTreeMap<String, evenframe_core::types::TaggedUnion>,
    output_path: &str,
    namespace: Option<&str>,
    registry: &ForeignTypeRegistry,
) -> Result<()> {
    info!("Generating FlatBuffers schema to {}", output_path);
    let content = generate_flatbuffers_schema_string(structs, enums, namespace, registry);
    std::fs::write(output_path, content)?;
    debug!("FlatBuffers schema written successfully");
    Ok(())
}

fn generate_protobuf(
    structs: &std::collections::BTreeMap<String, evenframe_core::types::StructConfig>,
    enums: &std::collections::BTreeMap<String, evenframe_core::types::TaggedUnion>,
    output_path: &str,
    package: Option<&str>,
    import_validate: bool,
    registry: &ForeignTypeRegistry,
) -> Result<()> {
    info!("Generating Protocol Buffers schema to {}", output_path);
    let content =
        generate_protobuf_schema_string(structs, enums, package, import_validate, registry);
    std::fs::write(output_path, content)?;
    debug!("Protocol Buffers schema written successfully");
    Ok(())
}

/// Removes files in `dir` matching `*{file_ext}` that are not part of the current output plan.
/// This cleans up obsolete files when types are regrouped into different files.
fn cleanup_obsolete_files(
    dir: &Path,
    plan: &FileOutputPlan,
    naming: FileNamingConvention,
    file_ext: &str,
) -> Result<()> {
    let mut expected: BTreeSet<String> = plan
        .groups
        .iter()
        .map(|g| {
            format!(
                "{}{}",
                type_name_to_filename(&g.primary_type, naming),
                file_ext
            )
        })
        .collect();
    expected.insert(barrel_filename(file_ext));

    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return Ok(()),
    };

    for entry in entries.flatten() {
        let file_name = entry.file_name().to_string_lossy().to_string();
        if file_name.ends_with(file_ext) && !expected.contains(&file_name) {
            info!("Removing obsolete file: {}", entry.path().display());
            std::fs::remove_file(entry.path())?;
        }
    }
    Ok(())
}