ggen-core 26.6.25

Core graph-aware code generation engine
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
//! Domain functions for CLI commands to reduce complexity
//!
//! This module contains business logic extracted from CLI functions
//! to maintain separation of concerns and keep CLI complexity low.

use crate::utils::error::{Error, Result};
use std::path::PathBuf;

/// Result type for schema validation
pub struct SchemaValidationResult {
    pub is_valid: bool,
    pub classes_count: usize,
    pub properties_count: usize,
    pub warnings: Vec<String>,
    pub errors: Vec<String>,
}

/// Result type for ontology project creation
pub struct ProjectCreationResult {
    pub ontology_file: String,
    pub config_file: String,
    pub generated_files: Vec<String>,
}

/// Generate language output from schema
pub async fn generate_language_output(
    schema_path: &PathBuf, language: &str, output: Option<&str>, zod: bool, utilities: bool,
) -> Result<(usize, String, String)> {
    use crate::codegen::TypeScriptGenerator;

    // Read schema
    let schema_content = std::fs::read_to_string(schema_path)
        .map_err(|e| Error::new(&format!("Failed to read schema: {}", e)))?;

    let schema: crate::ontology::OntologySchema = serde_json::from_str(&schema_content)
        .map_err(|e| Error::new(&format!("Invalid schema JSON: {}", e)))?;

    // Create output directory
    let output_dir = output.unwrap_or("generated");
    std::fs::create_dir_all(output_dir)
        .map_err(|e| Error::new(&format!("Failed to create output directory: {}", e)))?;

    let mut files_generated = 0;
    let mut primary_file = String::new();

    // Generate TypeScript code if requested
    if language == "typescript" {
        // Generate interfaces
        let interfaces = TypeScriptGenerator::generate_interfaces(&schema)
            .map_err(|e| Error::new(&format!("Interface generation failed: {}", e)))?;

        let interfaces_path = format!("{}/types.ts", output_dir);
        std::fs::write(&interfaces_path, interfaces)
            .map_err(|e| Error::new(&format!("Failed to write types: {}", e)))?;
        files_generated += 1;
        if primary_file.is_empty() {
            primary_file = interfaces_path.clone();
        }

        // Generate Zod schemas if requested
        if zod {
            let zod_schemas = TypeScriptGenerator::generate_zod_schemas(&schema)
                .map_err(|e| Error::new(&format!("Zod generation failed: {}", e)))?;

            let zod_path = format!("{}/schemas.ts", output_dir);
            std::fs::write(&zod_path, zod_schemas)
                .map_err(|e| Error::new(&format!("Failed to write schemas: {}", e)))?;
            files_generated += 1;
        }

        // Generate utility types if requested
        if utilities {
            let utils = TypeScriptGenerator::generate_utility_types(&schema)
                .map_err(|e| Error::new(&format!("Utilities generation failed: {}", e)))?;

            let utils_path = format!("{}/utilities.ts", output_dir);
            std::fs::write(&utils_path, utils)
                .map_err(|e| Error::new(&format!("Failed to write utilities: {}", e)))?;
            files_generated += 1;
        }
    }

    Ok((files_generated, primary_file, output_dir.to_string()))
}

/// Validate schema quality
pub async fn validate_schema_quality(
    schema_path: &PathBuf, strict: bool,
) -> Result<SchemaValidationResult> {
    // Read schema
    let schema_content = std::fs::read_to_string(schema_path)
        .map_err(|e| Error::new(&format!("Failed to read schema: {}", e)))?;

    let schema: crate::ontology::OntologySchema = serde_json::from_str(&schema_content)
        .map_err(|e| Error::new(&format!("Invalid schema JSON: {}", e)))?;

    let mut warnings = Vec::new();
    let mut errors = Vec::new();

    // Check for classes without properties
    for class in &schema.classes {
        if class.properties.is_empty() {
            warnings.push(format!("Class '{}' has no properties", class.name));
        }
    }

    // Check for properties with undefined classes
    for prop in &schema.properties {
        if prop.domain.is_empty() {
            warnings.push(format!("Property '{}' has no domain class", prop.name));
        }
    }

    // Check for circular references in strict mode
    if strict {
        for prop in &schema.properties {
            if let crate::ontology::PropertyRange::Reference(ref_class) = &prop.range {
                // Check if reference exists
                if !schema.classes.iter().any(|c| &c.uri == ref_class) {
                    errors.push(format!(
                        "Property '{}' references undefined class '{}'",
                        prop.name, ref_class
                    ));
                }
            }
        }
    }

    Ok(SchemaValidationResult {
        is_valid: errors.is_empty(),
        classes_count: schema.classes.len(),
        properties_count: schema.properties.len(),
        warnings,
        errors,
    })
}

/// Create ontology project with example files
pub async fn create_ontology_project(
    project_name: &str, template: Option<&str>,
) -> Result<ProjectCreationResult> {
    let proj_name = project_name;
    let proj_dir = PathBuf::from(&proj_name);

    // Create project directory
    std::fs::create_dir_all(&proj_dir)
        .map_err(|e| Error::new(&format!("Failed to create project: {}", e)))?;

    // Create subdirectories
    std::fs::create_dir_all(proj_dir.join("ontologies"))
        .map_err(|e| Error::new(&format!("Failed to create ontologies dir: {}", e)))?;
    std::fs::create_dir_all(proj_dir.join("src"))
        .map_err(|e| Error::new(&format!("Failed to create src dir: {}", e)))?;
    std::fs::create_dir_all(proj_dir.join("generated"))
        .map_err(|e| Error::new(&format!("Failed to create generated dir: {}", e)))?;

    let mut generated_files = Vec::new();

    // Create package.json
    let package_json = format!(
        r#"{{\n  "name": "{}",\n  "version": "1.0.0",\n  "description": "Ontology-driven code generation project",\n  "type": "module",\n  "scripts": {{\n    "extract": "ggen ontology extract ontologies/schema.ttl --output schema.json",\n    "generate": "ggen ontology generate schema.json --language typescript --zod --utilities",\n    "validate": "ggen ontology validate schema.json --strict"\n  }},\n  "dependencies": {{\n    "zod": "^3.0.0"\n  }},\n  "devDependencies": {{\n    "typescript": "^5.0.0"\n  }}\n}}\n"#,
        proj_name
    );
    let pkg_path = proj_dir.join("package.json");
    std::fs::write(&pkg_path, package_json)
        .map_err(|e| Error::new(&format!("Failed to write package.json: {}", e)))?;
    generated_files.push("package.json".to_string());

    // Create ggen.config.json
    let config = r#"{
  "ontologies": [
    "ontologies/schema.ttl"
  ],
  "namespace": "http://example.org#",
  "output": {
    "typescript": {
      "path": "src/types",
      "useZod": true,
      "generateUtilities": true
    }
  }
}
"#;
    let config_path = proj_dir.join("ggen.config.json");
    std::fs::write(&config_path, config)
        .map_err(|e| Error::new(&format!("Failed to write config: {}", e)))?;
    generated_files.push("ggen.config.json".to_string());

    // Create example ontology based on template
    let ontology_file = match template {
        Some("schema.org") => "schema-org-example.ttl",
        Some("foaf") => "foaf-example.ttl",
        Some("dublincore") => "dublincore-example.ttl",
        _ => "example.ttl",
    };

    let example_ttl = get_example_ontology(template);
    let ontology_path = proj_dir.join("ontologies").join(ontology_file);
    std::fs::write(&ontology_path, example_ttl)
        .map_err(|e| Error::new(&format!("Failed to write example ontology: {}", e)))?;
    generated_files.push(format!("ontologies/{}", ontology_file));

    // Create README
    let readme = format!(
        r#"# {} - Ontology Project

Auto-generated ontology project using ggen.

## Quick Start

```bash
# Extract ontology schema
npm run extract

# Generate TypeScript code from ontology
npm run generate

# Validate ontology quality
npm run validate
```

## Project Structure

- `ontologies/` - RDF/OWL ontology files (Turtle, RDF/XML, etc.)
- `src/` - Source code and generated types
- `generated/` - Generated artifacts (TypeScript, GraphQL, SQL, etc.)
- `ggen.config.json` - Configuration for code generation

## Available Commands

### Extract Schema
```bash
ggen ontology extract ontologies/schema.ttl [--namespace <uri>] [--output <file>]
```

### Generate Code
```bash
ggen ontology generate schema.json [--language typescript] [--zod] [--utilities]
```

### Validate Quality
```bash
ggen ontology validate schema.json [--strict]
```

## Supported Ontology Formats

- **Turtle** (.ttl) - Recommended, most human-readable
- **RDF/XML** (.rdf, .xml)
- **N-Triples** (.nt)

## Supported Code Generation Targets

- TypeScript interfaces with Zod validation schemas
- (GraphQL, React components, SQL coming soon)

## Example Ontologies

This project includes example ontologies:
- `schema-org-example.ttl` - Schema.org subset
- `foaf-example.ttl` - Friend of a Friend vocabulary
- `dublincore-example.ttl` - Dublin Core metadata

## Resources

- [RDF Concepts](https://www.w3.org/TR/rdf-concepts/)
- [SPARQL Query Language](https://www.w3.org/TR/sparql11-query/)
- [OWL 2 Web Ontology Language](https://www.w3.org/TR/owl2-overview/)
"#,
        proj_name
    );
    let readme_path = proj_dir.join("README.md");
    std::fs::write(&readme_path, readme)
        .map_err(|e| Error::new(&format!("Failed to write README: {}", e)))?;
    generated_files.push("README.md".to_string());

    let ontology_file_path = proj_dir.join("ontologies").join(ontology_file);
    let config_file_path = proj_dir.join("ggen.config.json");

    Ok(ProjectCreationResult {
        ontology_file: ontology_file_path.to_string_lossy().to_string(),
        config_file: config_file_path.to_string_lossy().to_string(),
        generated_files,
    })
}

// Default example ontology (Product/Order ecommerce-like)
const DEFAULT_EXAMPLE: &str = r#"@prefix ex: <http://example.org#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

# Classes
ex:Product a owl:Class ;
  rdfs:label "Product" ;
  rdfs:comment "A product in the catalog" .

ex:Order a owl:Class ;
  rdfs:label "Order" ;
  rdfs:comment "A customer order" .

# Properties
ex:name a owl:DatatypeProperty ;
  rdfs:domain ex:Product ;
  rdfs:range xsd:string ;
  rdfs:label "Name" ;
  a owl:FunctionalProperty .

ex:price a owl:DatatypeProperty ;
  rdfs:domain ex:Product ;
  rdfs:range xsd:decimal ;
  rdfs:label "Price" .

ex:quantity a owl:DatatypeProperty ;
  rdfs:domain ex:Order ;
  rdfs:range xsd:integer ;
  rdfs:label "Quantity" .
"#;

// Schema.org subset example
const SCHEMA_ORG_EXAMPLE: &str = r#"@prefix schema: <https://schema.org/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

# Product (from schema.org)
schema:Product a rdfs:Class ;
  rdfs:label "Product" ;
  rdfs:comment "Any offered product or service" .

schema:name a rdf:Property ;
  rdfs:domain schema:Product ;
  rdfs:range xsd:string ;
  rdfs:label "Name" .

schema:description a rdf:Property ;
  rdfs:domain schema:Product ;
  rdfs:range xsd:string ;
  rdfs:label "Description" .

schema:price a rdf:Property ;
  rdfs:domain schema:Product ;
  rdfs:range xsd:text ;
  rdfs:label "Price" .

schema:url a rdf:Property ;
  rdfs:domain schema:Product ;
  rdfs:range xsd:url ;
  rdfs:label "URL" .

# Organization
schema:Organization a rdfs:Class ;
  rdfs:label "Organization" .

schema:legalName a rdf:Property ;
  rdfs:domain schema:Organization ;
  rdfs:range xsd:string .

schema:email a rdf:Property ;
  rdfs:domain schema:Organization ;
  rdfs:range xsd:string .
"#;

// FOAF (Friend of a Friend) example
const FOAF_EXAMPLE: &str = r#"@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

# Person
foaf:Person a rdfs:Class ;
  rdfs:label "Person" ;
  rdfs:comment "A person" .

foaf:name a rdf:Property ;
  rdfs:domain foaf:Person ;
  rdfs:range xsd:string ;
  rdfs:label "Name" .

foaf:mbox a rdf:Property ;
  rdfs:domain foaf:Person ;
  rdfs:range xsd:string ;
  rdfs:label "Email" .

foaf:homepage a rdf:Property ;
  rdfs:domain foaf:Person ;
  rdfs:range xsd:url ;
  rdfs:label "Homepage" .

foaf:knows a rdf:Property ;
  rdfs:domain foaf:Person ;
  rdfs:range foaf:Person ;
  rdfs:label "Knows" .

# Group
foaf:Group a rdfs:Class ;
  rdfs:label "Group" ;
  rdfs:comment "A group of people" .

foaf:member a rdf:Property ;
  rdfs:domain foaf:Group ;
  rdfs:range foaf:Person ;
  rdfs:label "Member" .
"#;

// Dublin Core example
const DUBLINCORE_EXAMPLE: &str = r#"@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

# Resource
dcterms:Resource a rdfs:Class ;
  rdfs:label "Resource" ;
  rdfs:comment "A resource described by Dublin Core metadata" .

dc:title a rdf:Property ;
  rdfs:domain dcterms:Resource ;
  rdfs:range xsd:string ;
  rdfs:label "Title" .

dc:description a rdf:Property ;
  rdfs:domain dcterms:Resource ;
  rdfs:range xsd:string ;
  rdfs:label "Description" .

dc:creator a rdf:Property ;
  rdfs:domain dcterms:Resource ;
  rdfs:range xsd:string ;
  rdfs:label "Creator" .

dcterms:created a rdf:Property ;
  rdfs:domain dcterms:Resource ;
  rdfs:range xsd:dateTime ;
  rdfs:label "Created" .

dc:type a rdf:Property ;
  rdfs:domain dcterms:Resource ;
  rdfs:range xsd:string ;
  rdfs:label "Type" .

dc:subject a rdf:Property ;
  rdfs:domain dcterms:Resource ;
  rdfs:range xsd:string ;
  rdfs:label "Subject" .
"#;

fn get_example_ontology(template: Option<&str>) -> &'static str {
    match template {
        Some("schema.org") => SCHEMA_ORG_EXAMPLE,
        Some("foaf") => FOAF_EXAMPLE,
        Some("dublincore") => DUBLINCORE_EXAMPLE,
        _ => DEFAULT_EXAMPLE,
    }
}