oas-forge 0.1.3

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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
# OpenAPI Specs Forge (oas-forge)

[![Crates.io](https://img.shields.io/crates/v/oas-forge.svg)](https://crates.io/crates/oas-forge)
[![Docs.rs](https://docs.rs/oas-forge/badge.svg)](https://docs.rs/oas-forge)
[![License](https://img.shields.io/crates/l/oas-forge.svg)](LICENSE)
[![Build Status](https://github.com/AceVik/oas-forge/actions/workflows/release.yml/badge.svg)](https://github.com/AceVik/oas-forge/actions)
[![Latest Release](https://img.shields.io/github/v/release/AceVik/oas-forge)](https://github.com/AceVik/oas-forge/releases/latest)

**The zero-runtime OpenAPI 3.1 compiler for Rust.**

`oas-forge` extracts, links, and merges code-first documentation into a standard `openapi.yaml` file at compile time. It eliminates the need for runtime macros that bloat your binary and crash on startup.

### 🏗️ Architecture

```ascii
[Source Code] --> [Scanner] --> [AST Parsing] --> [Registry]    
                                                     |
                                                     v
[Static YAML] --> [Merger] <--- [Monomorphizer] <--- [Fragments]
                       |
                       v
                 [openapi.yaml]
```
---

## 🛠️ Integration Guide

```toml
[build-dependencies]
oas-forge = "0.1"
```

### Method A: build.rs (Fluent API)
```rust,no_run
use oas_forge::Generator;

println!("cargo:rerun-if-changed=src");
println!("cargo:rerun-if-changed=Cargo.toml");

Generator::new()
    .input("src") // Recursive input directory (where to search for doc comments)
    .input("lib") // Multiple inputs supported
    .include("static/security.yaml") // Merge static oas content - optional
    .include("static/skeleton.json") // Multiple includes supported (yaml and json supported)
    .output("openapi.yaml") // Full Spec (Strict: requires openapi/info root)
    // This is for lib exports to be used in other projects (in .include(...))
    .output_fragments("fragment.json") // Headless Spec (Paths + Components, no Root)
    // More fine-grained outputs (Relaxed: no validation)
    .output_schemas("schemas.json") // Components/Schemas only
    .output_paths("routes.yaml") // Paths only
    .generate()
    .expect("Failed to generate OpenAPI spec");

    // Note: Output file extension determines format (yaml/json)
```

### Method B: Cargo.toml Metadata
Configure in your manifest to keep `build.rs` minimal.

**Cargo.toml**:
```toml,ignore
# Same possibilities as Method A, but configured via Cargo.toml
[package.metadata.oas-forge]
input = ["src", "lib"]
include = ["static/skeleton.yaml"]

# Full Specs
output = ["openapi.yaml"]

# Granular Exports
output_fragments = ["dist/lib-spec.yaml"]
output_schemas = ["frontend/api-types.json"]
output_paths = ["gateway/routes.yaml"]
```

**build.rs**:
```rust,ignore
use oas_forge::{config::Config, Generator};

fn main() {
  println!("cargo:rerun-if-changed=src");
  println!("cargo:rerun-if-changed=Cargo.toml");
  
  let config = Config::load();

  if let Err(e) = Generator::new()
    // Use Cargo.toml metadata
    .with_config(config)
    .generate()
  {
    eprintln!("Warning: Failed to generate OpenAPI docs: {}", e);
  }
}
```

### Method C: CLI
Ideal for CI/CD pipelines.

```bash,ignore
cargo install oas-forge
# Run generation
oas_forge -i src -o openapi.yaml 
oas_forge -i src -I static/openapi.yaml -o openapi.yaml
oas_forge -i src -i lib -I static/skeleton.yaml -I static/security.json -o openapi.yaml

# You get the idea. More complex example:
oas-forge \
  -i src \
  --output openapi.yaml \
  --output-fragments dist/lib.yaml \
  --output-schemas types.json \
  --output-paths routes.yaml
```

---

## ✨ Feature Reference

### ⚡ Route DSL

The Route DSL allows you to define API operations directly above your handler functions. This avoids verbose YAML and keeps your code clean.

#### Basic Example

```rust,ignore
/// List Users
/// 
/// Returns a paginated list of users.
///
/// @route GET /users
/// @tag Users
/// @query-param page: Option<u32> "Page number"
/// @return 200: $Vec<User> "List of users"
async fn list_users() { ... }
```

#### Advanced Features

**1. Inline Path Parameters**
Define path parameters, their types, and descriptions directly in the route string.

```rust,ignore
/// @route GET /users/{id: u32 "The unique ID"}
fn get_user(id: u32) { ... }
```
* **Result**: Automatically registers `id` as `in: path`, `required: true`, with `schema: {type: integer, format: int32}`.

**2. Flexible Parameter Syntax**
Define path, query, header, or cookie parameters (`@path-param`, `@query-param`, `@header-param`, `@cookie-param`). Attributes like `deprecated`, `required`, or `example` can be placed in any order after the type.
Path parameters are name validated against the route path.

```rust,ignore
/// @route GET /search
/// @query-param filter: Option<String> deprecated example="Alice" "Filter by name"
/// @header-param X-Trace-ID: Uuid required "Tracing ID"
fn search() { ... }
```
* `deprecated`: Sets `deprecated: true`.
* `example="Alice"`: Sets `example: "Alice"`.
* `Option<T>`: Infers `required: false` (unless `required` flag is explicitly present).

**3. Smart Responses (`@return`)**
The DSL infers schemas and handles generics automatically.

```rust,ignore
/// @route POST /users
/// @return 201: $User "Created"          <- JSON Ref to User schema
/// @return 200: $Page<User> "List"       <- Monomorphized Generic ($Page<User> -> Page_User)
/// @return 204: "Deleted"                <- Unit Type (No Content body)
/// @return 400: "Invalid Input"          <- String Literal (Description only)
fn create_user() { ... }
```

**4. Request Body (`@body`)**
Link a Struct as the request body. Defaults to `application/json` if no MIME type is specified.

```rust,ignore
/// @route POST /users
/// @body $CreateRequest application/json
fn create() { ... }
```

**5. Security (`@security`)**
Apply security schemes defined in your root spec or fragments.

```rust,ignore
/// @route GET /protected
/// @security oidc("read", "write")
/// @security basic()
fn protected() { ... }
```

**6. Mixing Raw YAML (Overrides)**
You can mix standard OpenAPI YAML attributes directly within the DSL block. This is useful for complex scenarios or when using `@insert` with fragments containing bare YAML keys.
Supported top-level keys: `parameters`, `requestBody`, `responses`, `security`, `callbacks`, `externalDocs`, `servers`.

```rust,ignore
/// @route GET /complex
/// @tag Items
///
/// # You can inject raw parameters alongside DSL
/// parameters:
///   - name: raw_param
///     in: query
///     schema: { type: string }
///
/// # Or override the description
/// externalDocs:
///   url: https://example.com/docs
///   description: More info
///   description: More info
fn complex_handler() {}
```

**7. Virtual Routes**
Define routes in module-level documentation (e.g., `src/main.rs`) without an attached function. Useful for legacy endpoints or proxies.

```rust,ignore
//! @route GET /legacy/proxy
//! @tag Legacy
//! @return 200: "Proxy Response"
```

### 🏛️ Legacy / Manual Mode
You don't have to use the DSL. `oas-forge` fully supports "Old School" OpenAPI definitions where you simply write raw YAML in your doc comments. This gives you full control.

```rust,ignore
/// @openapi
/// paths:
///   /manual/endpoint:
///     get:
///       tags: [Manual]
///       summary: Fully manual definition
///       description: This is standard OpenAPI YAML.
///       responses:
///         '200':
///           description: OK
///           content:
///             text/plain:
///               schema: { type: string }
async fn manual_handler() {}
```

#### Integration Example: Serving with Axum
Here is a complete pattern for serving your dynamic OpenAPI spec and Swagger UI using `axum`.

```rust,ignore
use axum::{
    Router,
    http::header,
    response::{Html, IntoResponse},
    routing::get,
};
use std::env;

// Embed the generated file
const OPENAPI_SPEC: &str = include_str!("../../openapi.yaml");

pub fn router() -> Router {
    Router::new()
        .route("/openapi.yaml", get(serve_spec))
        .route("/swagger", get(serve_ui))
}

/// @openapi
/// paths:
///   /docs/openapi.yaml:
///     get:
///       tags: [System]
///       summary: Get OpenAPI Specification
///       description: Returns the dynamic OpenAPI specification.
///       responses:
///         '200':
///           description: The OpenAPI YAML file.
///           content:
///             application/yaml:
///               schema: { type: string }
async fn serve_spec() -> impl IntoResponse {
    let spec = OPENAPI_SPEC.replace("$$OIDC_URL", &env::var("OIDC_URL").unwrap_or_default());
    ([(header::CONTENT_TYPE, "application/yaml")], spec)
}

async fn serve_ui() -> impl IntoResponse {
    let html = r#"<!DOCTYPE html>
<html lang="en">
<head>
  <title>Swagger UI</title>
  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css" />
</head>
<body>
  <div id="swagger-ui"></div>
  <script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
  <script>
    window.onload = () => {
      SwaggerUIBundle({
        url: '/docs/openapi.yaml',
        dom_id: '#swagger-ui',
        presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
        layout: "BaseLayout",
      });
    };
  </script>
</body>
</html>"#;
    Html(html)
}
```

### 📦 Schema Extraction
Annotate your data structures, enums and types with doc comments to generate OpenAPI schemas.

```rust,ignore
// Defines a custom PhoneNumber type. (As example for types from other crates.)
//! @openapi-type PhoneNumber
//! type: string
//! format: tel
//! pattern: "^\\+?[1-9]\\d{1,14}$"
//! description: E.164 formatted phone number.
//! example: "+491701234567"

/// E-Mail address.
/// @openapi
/// example: "johnd@mail.com"
/// format: email
pub type Email = String;

/// Description of user roles within the system.
/// @openapi
pub enum Role {
  Admin,
  Moderator,
  User,
}

/// Description of a User entity.
/// @openapi
pub struct User {
  pub id: u32,

  /// The username of the user.
  /// @openapi example: "johndoe"
  pub username: Option<String>,

  /// The email address of the user.
  /// @openapi example: "johndoe@mail.com"
  pub email: Email,

  pub phone: PhoneNumber,

  /// The role assigned to the user.
  /// @openapi default: "User"
  pub role: Role,

  pub is_active: bool,

  /// The timestamp when the user was created.
  /// @openapi example: "2024-01-01T12:00:00"
  pub created_at: chrono::NaiveDateTime,
}
```
**generates**:
```yaml,ignore
components:
  schemas:
    PhoneNumber:
      type: string
      format: tel
      pattern: ^\+?[1-9]\d{1,14}$
      description: E.164 formatted phone number.
      example: '+491701234567'
    Role:
      description: Description of user roles within the system.
      enum:
        - Admin
        - Moderator
        - User
      type: string
    Email:
      description: E-Mail address.
      example: johnd@mail.com
      format: email
      type: string
    User:
      description: Description of a User entity.
      properties:
        created_at:
          description: The timestamp when the user was created.
          example: 2024-01-01T12:00:00
          format: date-time
          type: string
        email:
          $ref: '#/components/schemas/Email'
          description: The email address of the user.
          example: johndoe@mail.com
        id:
          format: int32
          type: integer
        is_active:
          type: boolean
        phone:
          $ref: '#/components/schemas/PhoneNumber'
        role:
          $ref: '#/components/schemas/Role'
          default: User
          description: The role assigned to the user.
        username:
          description: The username of the user.
          example: johndoe
          type: string
      required:
        - id
        - email
        - phone
        - role
        - is_active
        - created_at
      type: object
``` 
**Note:**
- If a property type is `Option<T>`, it is considered optional in the schema and it is not listed under `required`.
- Primitive types are automatically mapped to their OpenAPI equivalents (e.g., `u32` to `integer` with `format: int32`).
- Custom types annotated with `@openapi-type` can be defined for more complex schema definitions.
- Enums are represented as string enums in the schema.
- Doc comments can include additional OpenAPI attributes like `example`, `format`, `pattern`, and `description`.
- The generator supports common Rust types and can be extended for more complex scenarios.

### 🏷️ Renaming & Implicit Export Safety (v0.1.2+)

**Implicit Safety:** Enums now require the `@openapi` tag to be exported to the schema. Enums without this tag are ignored, even if public.

**Renaming:** You can rename fields, variants, and structs using **Serde** attributes or **@openapi** directives.
**Precedence Order:**
1. Manual `@openapi rename` / `@openapi rename-all`
2. `#[serde(rename = "...")]` / `#[serde(rename_all = "...")]`
3. Default Rust Name

#### Example: Renaming & Serde Support

```rust,ignore
/// @openapi
/// @openapi rename-all camelCase
#[derive(serde::Serialize)] // Optional, used for reference
pub enum UserRole {
    /// @openapi rename "admin_user"
    Admin,
    Moderator, // -> "moderator" (camelCase)
    User       // -> "user"
}

/// @openapi rename "UserProfile"
#[serde(rename_all = "snake_case")]
pub struct Profile {
    pub first_name: String, // -> "first_name"
    
    /// @openapi rename "lastName"
    pub last_name: String,  // -> "lastName" (override)
}
```

### 🏷️ Adjacently Tagged Enums
Supports `#[serde(tag = "...")]` (Internally Tagged) and `#[serde(tag = "...", content = "...")]` (Adjacently Tagged) to generate `oneOf` schemas with a `discriminator`.

```rust,ignore
/// @openapi
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StorageConfig {
    /// Generates schema "StorageConfigLocal"
    Local { root_path: String },
    
    /// Generates schema "StorageConfigS3"
    S3 { bucket: String, region: String },
}

/// @openapi
#[derive(Serialize)]
#[serde(tag = "t", content = "c")]
pub enum MyResult {
    Ok(String),
    Err { code: i32 }
}
```
**Generates**:
- `StorageConfig` container with `oneOf`.
- `StorageConfigLocal`: `{ type: "local", root_path: "..." }`
- `MyResult`: container.
- `MyResultOk`: `{ t: "Ok", c: { type: "string" } }`
- `MyResultErr`: `{ t: "Err", c: { type: "object", properties: { code: ... } } }`

### ✅ Validation Attributes
Supports the `validator` crate's `#[validate(...)]` attributes to automatically populate OpenAPI keywords.

```rust,ignore
#[derive(Validate)]
pub struct UserDto {
    #[validate(email)]
    pub email: String,              // -> format: email

    #[validate(url)]
    pub website: String,            // -> format: uri

    #[validate(length(min = 3, max = 20))]
    pub username: String,           // -> minLength: 3, maxLength: 20

    #[validate(range(min = 18, max = 100))]
    pub age: u8,                    // -> minimum: 18, maximum: 100
    
    #[validate(regex = "path")]     // -> pattern: "..." (if literal provided)
    pub code: String,
}
```

### 🧬 Template schemas with generics
Define reusable schema templates with generics using the `$` prefix.

```rust,ignore
/// Paginated response wrapper.
/// @openapi<T>
pub struct PaginatedResponse<T> {
  /// @openapi example: 100
  pub total_count: u32,

  /// @openapi
  /// example: 1
  /// minimum: 1
  pub page: u32,

  /// @openapi
  /// example: 10
  /// minimum: 1
  /// maximum: 1000
  pub limit: u32,

  pub data: Vec<T>,
} 
```

**Usage:**
```rust,ignore
// More about this in the Route DSL section below.
/// @return 200: $PaginatedResponse<User> "Success"
```
**generates**:
```yaml,ignore
components:
  schemas:
    PaginatedResponse_User:
      description: Paginated response wrapper.
      properties:
        data:
          items:
            $ref: '#/components/schemas/User'
          type: array
        limit:
          example: 10
          format: int32
          maximum: 1000
          minimum: 1
          type: integer
        page:
          example: 1
          format: int32
          minimum: 1
          type: integer
        total_count:
          example: 100
          format: int32
          type: integer
      required:
      - total_count
      - page
      - limit
      - data
      type: object 
```
**Note:**
- The Monomorphizer pass generates concrete schemas for each unique instantiation of the generic template (e.g., `$PaginatedResponse<User>` becomes `PaginatedResponse_User`).
- Multiple generic parameters are supported (e.g., `$Result<T, E>` => `Result_T_E`).

### 🌳 Root Documentation
Every OpenAPI specification needs a root definition containing metadata like the API version, title, and global security schemes. `oas-forge` requires exactly one such root definition in your project.
You can define this using a standard `@openapi` block, typically on a unit struct or at the top of your `main.rs` / `lib.rs`.

#### 1. Basic Root Definition
The root definition must contain the `openapi` version and the `info` object.

```rust,ignore
/// @openapi
/// openapi: 3.1.0
/// info:
///   title: My Awesome API
///   version: 1.0.0
///   description: >
///     This is the main entry point for the API documentation.
///     You can use Markdown here.
``` 

#### 2. Variable Substitution

`oas-forge` automatically injects environment variables into your documentation. The most common use case is syncing the API version with your crate version.

* `{{CARGO_PKG_VERSION}}`: Replaced by the version from `Cargo.toml`.

```rust,ignore
/// @openapi
/// openapi: 3.1.0
/// info:
///   title: Starr API
///   # Automatically uses the version from Cargo.toml
///   version: {{CARGO_PKG_VERSION}}
```

#### 3. Defining Global Security Schemes

The root definition is the perfect place to define `securitySchemes` (Components) and global `security` requirements.

```rust,ignore
/// @openapi
/// openapi: 3.1.0
/// info:
///   title: Secure API
///   version: 1.0.0
/// components:
///   securitySchemes:
///     # Define a JWT Bearer scheme
///     BearerAuth:
///       type: http
///       scheme: bearer
///       bearerFormat: JWT
///     # Define an OAuth2/OIDC scheme
///     OidcAuth:
///       type: openIdConnect
///       openIdConnectUrl: [https://auth.example.com/.well-known/openid-configuration](https://auth.example.com/.well-known/openid-configuration)
/// # Apply BearerAuth globally to all routes (optional)
/// security:
///   - BearerAuth: []
```

#### 4. Attaching to Application Logic (Recommended)

You don't need to create a "lifeless" dummy struct just for documentation. You can attach the root definition directly to your main application entry point or router function. This keeps the documentation close to the actual code logic.

```rust,ignore
/// @openapi
/// openapi: 3.1.1
/// info:
///   title: User Management API
///   version: {{CARGO_PKG_VERSION}}
///   description: API documentation for the user service.
/// components:
///   securitySchemes:
///     oidcAuth:
///       type: openIdConnect
///       openIdConnectUrl: $$OIDC_URL/.well-known/openid-configuration
///       description: OIDC Authentication via Rauthy.
pub fn create_app() -> Router<AppState> {
  Router::new()
    .nest("/docs", swagger::router())
    .nest("/users", users::router())
}
```

### 🧩 Fragments & Mixins
Fragments allow you to define reusable OpenAPI snippets (like common error responses, standard parameters, or security schemes) and inject them into your operation definitions.

#### 1. Defining Fragments
Fragments are usually defined in a shared file (e.g., `lib.rs` or `docs.rs`) using module-level comments (`//!`). They can accept parameters using the `{{variable}}` syntax.

```rust,ignore
//! ---------------------------------------------------------------------------
//! A. Fragment for a List (e.g., Parameters)
//! ---------------------------------------------------------------------------
//! @openapi-fragment PaginationParams
//! - name: page
//!   in: query
//!   description: Page number
//!   schema: { type: integer, default: 1 }
//! - name: limit
//!   in: query
//!   schema: { type: integer, default: 10 }

//! ---------------------------------------------------------------------------
//! B. Fragment for an Object (e.g., Responses or Security)
//! ---------------------------------------------------------------------------
//! @openapi-fragment Secured(role)
//! security:
//!   - oidcAuth: [ {{role}} ]
//! responses:
//!   '401':
//!     description: Unauthorized
//!   '403':
//!     description: Forbidden - Requires {{role}} role
``` 
#### 2. Usage: `@insert` vs. `@extend`
While both keywords inject content, they work at different levels. Choosing the right one is crucial for valid YAML generation.

| Keyword | Mechanism | Best Used For | Behavior |
| :--- | :--- | :--- | :--- |
| **`@insert`** | **Textual Substitution** | **Lists / Arrays** | Acts like "Copy & Paste". Replaces the line with the fragment text *before* parsing. Essential for inserting items into a YAML list (like `parameters`). |
| **`@extend`** | **Deep Merge** | **Objects / Maps** | Parses the fragment as YAML and deeply merges it into the current structure. Ideal for adding fields to a struct or responses to an operation. |

#### Example: Using `@insert` (For Lists)

Use `@insert` when you want to add elements to a list, such as query parameters.

```rust,ignore
/// @openapi
/// paths:
///   /users:
///     get:
///       parameters:
///         # Inserts the list items directly here
///         @insert PaginationParams
```

#### Example: Using `@extend` (For Objects)

Use `@extend` when you want to merge properties, such as adding security requirements or standard responses to an existing block.

```rust,ignore
/// @openapi
/// paths:
///   /admin/dashboard:
///     get:
///       summary: Admin Area
///       
///       # Merges security and 401/403 responses into this operation
///       @extend Secured("admin")
///
///       responses:
///         '200':
///           description: OK
```

### 📚 Reference: Default Type Mappings

`oas-forge` automatically recognizes common Rust types (including popular crates like `chrono`, `uuid`, and `url`) and maps them to their OpenAPI equivalents.

| Rust Type | OpenAPI Type | Format | Notes |
| :--- | :--- | :--- | :--- |
| `bool` | `boolean` | - | |
| `String`, `&str`, `char` | `string` | - | |
| `i8`, `i16`, `i32`, `u8`, `u16`, `u32` | `integer` | `int32` | |
| `i64`, `u64`, `isize`, `usize` | `integer` | `int64` | `usize` and `isize` are treated as 64-bit. |
| `f32` | `number` | `float` | |
| `f64` | `number` | `double` | |
| `Uuid` | `string` | `uuid` | e.g., from `uuid` crate |
| `NaiveDate` | `string` | `date` | e.g., from `chrono` crate |
| `DateTime`, `NaiveDateTime` | `string` | `date-time` | e.g., from `chrono` crate |
| `NaiveTime` | `string` | `time` | e.g., from `chrono` crate |
| `Url`, `Uri` | `string` | `uri` | |
| `Decimal`, `BigDecimal` | `string` | `decimal` | String representation to preserve precision. |
| `ObjectId` | `string` | `objectid` | MongoDB/BSON identifier |
| `serde_json::Value` | - | - | Maps to `{}` (Any Type). |

### Axum/Swagger basic example without route dsl
```rust,ignore
use crate::app::AppState;
use axum::{
    Router,
    http::header,
    response::{Html, IntoResponse},
    routing::get,
};
use std::env;

const OPENAPI_SPEC: &str = include_str!("../../openapi.yaml");

const OIDC_PLACEHOLDER: &str = "$$OIDC_URL";
const DEFAULT_OIDC_URL: &str = "https://oidc.example.com";

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/openapi.yaml", get(serve_spec))
        .route("/swagger", get(serve_ui))
}

/// @openapi
/// paths:
///   /docs/openapi.yaml:
///     get:
///       tags: [System]
///       summary: Get OpenAPI Specification
///       description: Returns the dynamic OpenAPI 3.1.1 specification with runtime configuration.
///       responses:
///         '200':
///           description: The OpenAPI YAML file.
///           content:
///             application/yaml:
///               schema:
///                 type: string
async fn serve_spec() -> impl IntoResponse {
    let oidc_url = env::var("OIDC_URL").unwrap_or_else(|_| DEFAULT_OIDC_URL.to_string());
    let dynamic_spec = OPENAPI_SPEC.replace(OIDC_PLACEHOLDER, &oidc_url);

    ([(header::CONTENT_TYPE, "application/yaml")], dynamic_spec)
}

/// @openapi
/// paths:
///   /docs/swagger:
///     get:
///       tags: [System]
///       summary: Swagger UI
///       description: Renders the Swagger UI.
///       responses:
///         '200':
///           description: HTML Page containing the Swagger UI.
///           content:
///             text/html:
///               schema:
///                 type: string
async fn serve_ui() -> impl IntoResponse {
    let html = r#"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Starr API - Swagger UI</title>
    <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css" />
    <style>
        body { margin: 0; padding: 0; }
        #swagger-ui { max-width: 1400px; margin: 0 auto; }
    </style>
</head>
<body>
    <div id="swagger-ui"></div>
    <script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
    <script>
        window.onload = () => {
            window.ui = SwaggerUIBundle({
                url: '/docs/openapi.yaml',
                dom_id: '#swagger-ui',
                deepLinking: true,
                presets: [
                    SwaggerUIBundle.presets.apis,
                    SwaggerUIBundle.SwaggerUIStandalonePreset
                ],
                layout: "BaseLayout",
            });
        };
    </script>
</body>
</html>
"#;
    Html(html)
}
```

## 📜 License

This project is licensed under the [MIT license](LICENSE).