oas-forge 0.1.4

The zero-runtime OpenAPI 3.1 compiler for Rust. Extracts, links, and merges code-first documentation.
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
use crate::dsl;
use crate::error::{Error, Result};
use crate::generics::Monomorphizer;
use crate::index::Registry;
use crate::preprocessor;
use crate::visitor::{self, ExtractedItem};
use regex::Regex;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::OnceLock;
use walkdir::WalkDir;

/// Represents a source-mapped snippet of OpenAPI definition.
#[derive(Debug, Clone)]
pub struct Snippet {
    pub content: String,
    pub file_path: PathBuf,
    pub line_number: usize,
    pub operation_id: Option<String>,
}

// DX Macros Preprocessor
// Implementation of auto-quoting and short-hands.
pub fn preprocess_macros(snippet: &Snippet, registry: &mut Registry) -> Snippet {
    let content = &snippet.content;
    let mut new_lines = Vec::new();

    // Regex definition
    static GENERIC_RE: OnceLock<Regex> = OnceLock::new();
    let generic_re =
        GENERIC_RE.get_or_init(|| Regex::new(r"\$([a-zA-Z0-9_]+)<([a-zA-Z0-9_, ]+)>").unwrap());

    static MACRO_INSERT_RE: OnceLock<Regex> = OnceLock::new();
    let macro_insert_re = MACRO_INSERT_RE
        .get_or_init(|| Regex::new(r"^(\s*)(-)?\s*@insert\s+([a-zA-Z0-9_]+)$").unwrap());

    static MACRO_EXTEND_RE: OnceLock<Regex> = OnceLock::new();
    let macro_extend_re =
        MACRO_EXTEND_RE.get_or_init(|| Regex::new(r"^(\s*)@extend\s+(.+)$").unwrap());

    // static MACRO_RETURN_RE: OnceLock<Regex> = OnceLock::new();
    // let macro_return_re = MACRO_RETURN_RE.get_or_init(|| {
    //    Regex::new(r#"^(\s*)@return\s+(\d{3})\s*:\s*([^\s"]+)(?:\s+"(.*)")?$"#).unwrap()
    // });

    static ARRAY_SHORT_RE: OnceLock<Regex> = OnceLock::new();
    let array_short_re =
        ARRAY_SHORT_RE.get_or_init(|| Regex::new(r"\$Vec<([a-zA-Z0-9_]+)>").unwrap());

    for line in content.lines() {
        let current_lines = vec![line.to_string()];

        // 0. Remove conflicting @return expansion
        // dsl.rs handles @return differently and robustly.
        // Expanding it here creates a conflict because dsl.rs does not recognize the expanded YAML.

        /*
        // Was:
        if let Some(caps) = macro_return_re.captures(line) {
             // ...
        }
        */

        for sub_line in current_lines {
            let mut processed_line = sub_line.clone();

            // 1. Array Shorthand ($Vec<T>)
            // Replace ALL occurrences in the line
            while let Some(caps) = array_short_re.captures(&processed_line.clone()) {
                let full_match = caps.get(0).unwrap().as_str();
                let type_name = caps.get(1).unwrap().as_str();
                // Inline JSON syntax for array
                let replacement = format!(
                    "{{ type: array, items: {{ $ref: \"#/components/schemas/{}\" }} }}",
                    type_name
                );
                processed_line = processed_line.replace(full_match, &replacement);
            }

            // 2. Generics Flattening (Inline) + Instantiation
            // (Existing logic)
            while let Some(caps) = generic_re.captures(&processed_line.clone()) {
                let full_match = caps.get(0).unwrap().as_str();
                let name = caps.get(1).unwrap().as_str();
                let args_raw = caps.get(2).unwrap().as_str();

                // Instantiate via Monomorphizer
                let mut mono = Monomorphizer::new(registry);
                let concrete_name = mono.monomorphize(name, args_raw);

                // Replace with Smart Ref format ($Name)
                let replacement = format!("${}", concrete_name);
                processed_line = processed_line.replace(full_match, &replacement);
            }

            // 3. Short-hand @insert
            if let Some(caps) = macro_insert_re.captures(&processed_line) {
                let indent = &caps[1];
                let name = &caps[3];

                if !registry.fragments.contains_key(name) {
                    let final_indent = format!("{}- ", indent);
                    new_lines.push(format!(
                        "{}$ref: \"#/components/parameters/{}\"",
                        final_indent, name
                    ));
                    continue;
                }
            }

            // 4. Auto-Quoting @extend
            if let Some(caps) = macro_extend_re.captures(&processed_line) {
                let indent = &caps[1];
                let content = &caps[2];
                let escaped_content = content.replace('\'', "''");
                new_lines.push(format!("{}x-openapi-extend: '{}'", indent, escaped_content));
                continue;
            }

            new_lines.push(processed_line);
        }
    }

    Snippet {
        content: new_lines.join("\n"),
        file_path: snippet.file_path.clone(),
        line_number: snippet.line_number,
        operation_id: snippet.operation_id.clone(),
    }
}

pub fn substitute_smart_references(content: &str, schemas: &HashSet<String>) -> String {
    let mut result = String::with_capacity(content.len());
    let chars: Vec<char> = content.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        if chars[i] == '$' {
            let mut j = i + 1;
            if j < chars.len() && (chars[j].is_alphabetic() || chars[j] == '_') {
                while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
                    j += 1;
                }

                let ident: String = chars[i + 1..j].iter().collect();

                if schemas.contains(&ident) {
                    let is_quoted = i > 0 && chars[i - 1] == '"';

                    if !is_quoted {
                        result.push('"');
                    }
                    result.push_str("#/components/schemas/");
                    result.push_str(&ident);
                    if !is_quoted {
                        result.push('"');
                    }

                    i = j;
                    continue;
                }
            }
        }
        result.push(chars[i]);
        i += 1;
    }
    result
}

fn finalize_substitution(content: &str) -> String {
    let version = std::env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "0.0.0".to_string());
    let step1 = content.replace(r"\$", "$");
    step1.replace("{{CARGO_PKG_VERSION}}", &version)
}

pub fn scan_directories(
    roots: &[PathBuf],
    includes: &[PathBuf],
) -> Result<(Vec<Snippet>, Registry)> {
    let mut registry = Registry::new();
    let mut operation_snippets: Vec<Snippet> = Vec::new();
    let mut files_found = false;

    let mut all_paths = Vec::new();

    for root in roots {
        for entry in WalkDir::new(root) {
            let entry = entry.map_err(|e| Error::Io(std::io::Error::other(e)))?;
            let path = entry.path().to_path_buf();
            if path.is_file() {
                all_paths.push(path);
            }
        }
    }
    for path in includes {
        if path.exists() {
            all_paths.push(path.to_path_buf());
        }
    }

    if !all_paths.is_empty() {
        files_found = true;
    }

    // PASS 1: Indexing
    for path in all_paths {
        if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
            match ext {
                "rs" => {
                    let extracted = visitor::extract_from_file(path.clone())?;
                    for item in extracted {
                        match item {
                            ExtractedItem::Schema {
                                name,
                                content,
                                line,
                            } => {
                                if let Some(n) = name {
                                    registry.insert_schema(n, content.clone());
                                }
                                operation_snippets.push(Snippet {
                                    content,
                                    file_path: path.clone(),
                                    line_number: line,
                                    operation_id: None,
                                });
                            }
                            ExtractedItem::RouteDSL {
                                content,
                                line,
                                operation_id,
                            } => {
                                operation_snippets.push(Snippet {
                                    content,
                                    file_path: path.clone(),
                                    line_number: line,
                                    operation_id: Some(operation_id),
                                });
                            }
                            ExtractedItem::Fragment {
                                name,
                                params,
                                content,
                                ..
                            } => {
                                registry.insert_fragment(name, params, content);
                            }
                            ExtractedItem::Blueprint {
                                name,
                                params,
                                content,
                                ..
                            } => {
                                registry.insert_blueprint(name, params, content);
                            }
                        }
                    }
                }
                "json" | "yaml" | "yml" => {
                    let content = std::fs::read_to_string(&path)?;

                    // Hydrate registry from vendor extensions
                    if let Ok(mut val) = serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&content) {
                        if let Some(components) = val.get_mut("components") {
                            // Import templates (blueprints)
                            if let Some(templates) = components.get("x-oas-forge-templates") {
                                if let Ok(blueprints) = serde_json::from_value::<
                                    std::collections::HashMap<String, crate::index::Blueprint>,
                                >(
                                    serde_json::to_value(templates).unwrap_or_default(),
                                ) {
                                    for (name, bp) in blueprints {
                                        log::info!("Imported template '{}' from {:?}", name, path);
                                        registry.insert_blueprint(name, bp.params, bp.body);
                                    }
                                }
                            }

                            // Import fragments
                            if let Some(frags) = components.get("x-oas-forge-fragments") {
                                if let Ok(fragments) = serde_json::from_value::<
                                    std::collections::HashMap<String, crate::index::Fragment>,
                                >(
                                    serde_json::to_value(frags).unwrap_or_default(),
                                ) {
                                    for (name, frag) in fragments {
                                        log::info!("Imported fragment '{}' from {:?}", name, path);
                                        registry.insert_fragment(name, frag.params, frag.body);
                                    }
                                }
                            }

                            // Import standard schemas (register names for smart reference resolution)
                            if let Some(serde_yaml_ng::Value::Mapping(schema_map)) =
                                components.get("schemas")
                            {
                                for (key, _) in schema_map {
                                    if let serde_yaml_ng::Value::String(name) = key {
                                        registry.insert_schema(name.clone(), String::new());
                                    }
                                }
                            }

                            // Strip vendor keys so they don't leak into the final output
                            if let serde_yaml_ng::Value::Mapping(comp_map) = components {
                                comp_map.remove(serde_yaml_ng::Value::String(
                                    "x-oas-forge-templates".to_string(),
                                ));
                                comp_map.remove(serde_yaml_ng::Value::String(
                                    "x-oas-forge-fragments".to_string(),
                                ));
                            }
                        }

                        // Re-serialize the cleaned content
                        let cleaned =
                            serde_yaml_ng::to_string(&val).unwrap_or_else(|_| content.clone());
                        let cleaned = cleaned.trim_start_matches("---\n").to_string();

                        operation_snippets.push(Snippet {
                            content: cleaned,
                            file_path: path.clone(),
                            line_number: 1,
                            operation_id: None,
                        });
                    } else {
                        // Fallback: push raw content
                        operation_snippets.push(Snippet {
                            content,
                            file_path: path.clone(),
                            line_number: 1,
                            operation_id: None,
                        });
                    }
                }
                _ => {}
            }
        }
    }

    // PASS 2: Pre-Processing & DSL Compilation
    let mut preprocessed_snippets = Vec::new();
    for snippet in operation_snippets {
        // 2a. Expand Macros
        let macrod_snippet = preprocess_macros(&snippet, &mut registry);

        // 2b. Expand Fragments
        let expanded_content = preprocessor::preprocess(&macrod_snippet.content, &registry);

        // 2c. Compile DSL -> YAML
        let final_content = if let Some(op_id) = &macrod_snippet.operation_id {
            let lines: Vec<String> = expanded_content.lines().map(|s| s.to_string()).collect();
            if let Some(yaml) = dsl::parse_route_dsl(&lines, op_id) {
                yaml
            } else {
                // If it was captured as DSL but failed parsing (e.g. no @route?), fallback.
                // But visitor logic ensures @route exists.
                // Parsing might fail if parse_route_dsl logic filters it out.
                expanded_content
            }
        } else {
            expanded_content
        };

        preprocessed_snippets.push(Snippet {
            content: final_content,
            file_path: macrod_snippet.file_path,
            line_number: macrod_snippet.line_number,
            operation_id: macrod_snippet.operation_id,
        });
    }

    // PASS 3: Monomorphization
    let mut monomorphizer = Monomorphizer::new(&mut registry);
    let mut mono_snippets: Vec<Snippet> = Vec::new();

    for snippet in preprocessed_snippets {
        let mono_content = monomorphizer.process(&snippet.content);
        mono_snippets.push(Snippet {
            content: mono_content,
            file_path: snippet.file_path,
            line_number: snippet.line_number,
            operation_id: snippet.operation_id,
        });
    }

    // Inject Concrete Schemas
    let mut generated_snippets = Vec::new();
    for (name, content) in &registry.concrete_schemas {
        let wrapped = format!(
            "components:\n  schemas:\n    {}:\n{}",
            name,
            indent(content)
        );
        generated_snippets.push(Snippet {
            content: wrapped,
            file_path: PathBuf::from("<generated>"),
            line_number: 1,
            operation_id: None,
        });
    }
    mono_snippets.extend(generated_snippets);

    // PASS 4: Substitution
    let mut all_schemas = registry.schemas.keys().cloned().collect::<HashSet<_>>();
    all_schemas.extend(registry.concrete_schemas.keys().cloned());

    let mut final_snippets = Vec::new();
    for snippet in mono_snippets {
        let subbed = substitute_smart_references(&snippet.content, &all_schemas);
        let finalized_content = finalize_substitution(&subbed);
        final_snippets.push(Snippet {
            content: finalized_content,
            file_path: snippet.file_path,
            line_number: snippet.line_number,
            operation_id: snippet.operation_id,
        });
    }

    if !files_found {
        return Err(Error::NoFilesFound);
    }

    Ok((final_snippets, registry))
}

fn indent(s: &str) -> String {
    s.lines()
        .map(|l| format!("      {}", l))
        .collect::<Vec<_>>()
        .join("\n")
}

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

    #[test]
    fn test_escaping() {
        let input = r"price: \$100";
        let output = finalize_substitution(input);
        assert_eq!(output, "price: $100");
    }

    #[test]
    fn test_vec_macro() {
        let mut registry = Registry::new();
        let snippet = Snippet {
            content: "tags: $Vec<Tag>".to_string(),
            file_path: PathBuf::from("test.rs"),
            line_number: 1,
            operation_id: None,
        };
        let processed = preprocess_macros(&snippet, &mut registry);
        assert!(processed.content.contains("type: array"));
        assert!(processed.content.contains("items:"));
        assert!(
            processed
                .content
                .contains("$ref: \"#/components/schemas/Tag\"")
        );
    }

    // tests for @return removed as logic moved to dsl.rs
}