spikard-codegen 0.15.5

Code generation utilities for Spikard
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
//! Convert test fixtures to `OpenAPI` 3.1 specifications

use super::spec::{
    MediaType, OpenApiSpec, Operation, Parameter, PathItem, RequestBody, Response, Schema, SchemaObject,
};
use crate::error::{CodegenError, Result};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// Test fixture structure (matching `testing_data`/*.json)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Fixture {
    pub name: String,
    pub description: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub handler: Option<FixtureHandler>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub streaming: Option<FixtureStreaming>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub background: Option<FixtureBackground>,

    pub request: FixtureRequest,
    pub expected_response: FixtureExpectedResponse,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureStreaming {
    /// Optional explicit content type for the stream (overrides headers)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,

    /// Stream chunks that will be yielded sequentially
    pub chunks: Vec<FixtureStreamChunk>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureBackground {
    pub state_path: String,
    pub state_key: String,
    pub value_field: String,
    pub expected_state: Vec<Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FixtureStreamChunk {
    /// UTF-8 text chunk
    Text { value: String },
    /// Arbitrary bytes encoded as base64 for portability
    Bytes { base64: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureHandler {
    pub route: String,
    pub method: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_schema: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_schema: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub cors: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub middleware: Option<Value>,

    /// Dependency injection: app-level dependencies
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dependencies: Option<Value>,

    /// Dependency injection: dependencies required by this handler
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handler_dependencies: Option<Value>,

    /// Dependency injection: route-level dependency overrides
    #[serde(skip_serializing_if = "Option::is_none")]
    pub route_overrides: Option<Value>,

    /// Dependency injection: injection strategy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub injection_strategy: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureRequest {
    pub method: String,
    pub path: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_params: Option<HashMap<String, Value>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub cookies: Option<HashMap<String, String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<HashMap<String, Value>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub form_data: Option<HashMap<String, Value>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub files: Option<Vec<FixtureFile>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureFile {
    pub field_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_encoding: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub magic_bytes: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureExpectedResponse {
    pub status_code: u16,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_partial: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub validation_errors: Option<Vec<ValidationError>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    #[serde(rename = "type")]
    pub error_type: String,
    pub loc: Vec<String>,
    pub msg: String,
}

/// Options for `OpenAPI` generation
#[derive(Debug, Clone)]
pub struct OpenApiOptions {
    pub title: String,
    pub version: String,
    pub description: Option<String>,
}

impl Default for OpenApiOptions {
    fn default() -> Self {
        Self {
            title: "Generated API".to_string(),
            version: "1.0.0".to_string(),
            description: Some("API generated from test fixtures".to_string()),
        }
    }
}

/// Convert test fixtures to `OpenAPI` 3.1 specification
///
/// # Errors
///
/// Returns an error if the fixtures are invalid or cannot be converted to an `OpenAPI` specification.
pub fn fixtures_to_openapi(fixtures: &[Fixture], options: OpenApiOptions) -> Result<OpenApiSpec> {
    let mut spec = OpenApiSpec::new(options.title, options.version);
    spec.info.description = options.description;

    let grouped = group_fixtures_by_route(fixtures);

    for ((path, method), route_fixtures) in grouped {
        let operation = build_operation(&route_fixtures, &method);

        let path_item = spec.paths.entry(path.clone()).or_insert_with(|| PathItem {
            get: None,
            post: None,
            put: None,
            patch: None,
            delete: None,
            parameters: None,
        });

        match method.to_uppercase().as_str() {
            "GET" => path_item.get = Some(operation),
            "POST" => path_item.post = Some(operation),
            "PUT" => path_item.put = Some(operation),
            "PATCH" => path_item.patch = Some(operation),
            "DELETE" => path_item.delete = Some(operation),
            _ => {}
        }
    }

    Ok(spec)
}

/// Load fixtures from a directory
///
/// # Errors
///
/// Returns an error if the directory cannot be read or if a fixture file is invalid.
///
/// # Panics
///
/// Panics if a filename in the directory cannot be converted to a string.
pub fn load_fixtures_from_dir(dir: &Path) -> Result<Vec<Fixture>> {
    let mut fixtures = Vec::new();

    if !dir.exists() {
        return Ok(fixtures);
    }

    for entry in fs::read_dir(dir).map_err(CodegenError::IoError)? {
        let entry = entry.map_err(CodegenError::IoError)?;
        let path = entry.path();

        if path.extension().is_none_or(|e| e != "json") {
            continue;
        }

        let filename = path.file_name().unwrap().to_str().unwrap();
        if filename.starts_with("00-") || filename == "schema.json" {
            continue;
        }

        let content = fs::read_to_string(&path)?;
        match serde_json::from_str::<Fixture>(&content) {
            Ok(fixture) => fixtures.push(fixture),
            Err(e) => {
                eprintln!("Warning: Skipping {}: {}", path.display(), e);
            }
        }
    }

    Ok(fixtures)
}

/// Group fixtures by (path, method)
fn group_fixtures_by_route(fixtures: &[Fixture]) -> HashMap<(String, String), Vec<Fixture>> {
    let mut grouped: HashMap<(String, String), Vec<Fixture>> = HashMap::new();

    for fixture in fixtures {
        let path = fixture.request.path.clone();
        let method = fixture.request.method.to_uppercase();

        grouped.entry((path, method)).or_default().push(fixture.clone());
    }

    grouped
}

/// Build `OpenAPI` operation from fixtures
fn build_operation(fixtures: &[Fixture], method: &str) -> Operation {
    let first = &fixtures[0];

    let mut operation = Operation {
        summary: Some(first.description.clone()),
        description: None,
        operation_id: Some(format!(
            "{}_{}",
            method.to_lowercase(),
            sanitize_path(&first.request.path)
        )),
        parameters: None,
        request_body: None,
        responses: IndexMap::new(),
        tags: first.tags.clone(),
    };

    if let Some(ref handler) = first.handler {
        if let Some(ref params) = handler.parameters {
            operation.parameters = Some(extract_parameters(params));
        }

        if let Some(ref body_schema) = handler.body_schema {
            operation.request_body = Some(build_request_body(body_schema));
        }
    }

    let mut responses = IndexMap::new();
    for fixture in fixtures {
        let status = fixture.expected_response.status_code.to_string();

        if !responses.contains_key(&status) {
            responses.insert(status.clone(), build_response(&fixture.expected_response));
        }
    }

    operation.responses = responses;

    operation
}

/// Extract parameters from handler schema
fn extract_parameters(params_schema: &Value) -> Vec<Parameter> {
    let mut parameters = Vec::new();

    if let Some(obj) = params_schema.as_object() {
        if let Some(path_params) = obj.get("path").and_then(|v| v.as_object()) {
            for (name, schema) in path_params {
                parameters.push(Parameter {
                    name: name.clone(),
                    location: "path".to_string(),
                    description: schema.get("description").and_then(|v| v.as_str()).map(String::from),
                    required: Some(true),
                    schema: Some(json_to_schema(schema)),
                });
            }
        }

        if let Some(query_params) = obj.get("query").and_then(|v| v.as_object()) {
            for (name, schema) in query_params {
                parameters.push(Parameter {
                    name: name.clone(),
                    location: "query".to_string(),
                    description: schema.get("description").and_then(|v| v.as_str()).map(String::from),
                    required: schema.get("required").and_then(Value::as_bool),
                    schema: Some(json_to_schema(schema)),
                });
            }
        }

        if let Some(headers) = obj.get("headers").and_then(|v| v.as_object()) {
            for (name, schema) in headers {
                parameters.push(Parameter {
                    name: name.clone(),
                    location: "header".to_string(),
                    description: schema.get("description").and_then(|v| v.as_str()).map(String::from),
                    required: schema.get("required").and_then(Value::as_bool),
                    schema: Some(json_to_schema(schema)),
                });
            }
        }

        if let Some(cookies) = obj.get("cookies").and_then(|v| v.as_object()) {
            for (name, schema) in cookies {
                parameters.push(Parameter {
                    name: name.clone(),
                    location: "cookie".to_string(),
                    description: schema.get("description").and_then(|v| v.as_str()).map(String::from),
                    required: schema.get("required").and_then(Value::as_bool),
                    schema: Some(json_to_schema(schema)),
                });
            }
        }
    }

    parameters
}

/// Build request body from schema
fn build_request_body(schema: &Value) -> RequestBody {
    let mut content = IndexMap::new();

    content.insert(
        "application/json".to_string(),
        MediaType {
            schema: Some(json_to_schema(schema)),
            example: None,
            examples: None,
        },
    );

    RequestBody {
        description: None,
        content,
        required: Some(true),
    }
}

/// Build response from expected response
fn build_response(expected: &FixtureExpectedResponse) -> Response {
    let description = match expected.status_code {
        200 => "Successful response",
        201 => "Created successfully",
        204 => "No content",
        400 => "Bad request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not found",
        422 => "Validation error",
        _ => "Response",
    };

    let mut response = Response {
        description: description.to_string(),
        content: None,
        headers: None,
    };

    if expected.body.is_some() || expected.validation_errors.is_some() {
        let mut content = IndexMap::new();

        content.insert(
            "application/json".to_string(),
            MediaType {
                schema: Some(Schema::Object(Box::new(SchemaObject {
                    schema_type: "object".to_string(),
                    properties: None,
                    required: None,
                    format: None,
                    items: None,
                    minimum: None,
                    maximum: None,
                    min_length: None,
                    max_length: None,
                    pattern: None,
                    description: None,
                }))),
                example: expected.body.clone(),
                examples: None,
            },
        );

        response.content = Some(content);
    }

    response
}

/// Convert JSON Schema to `OpenAPI` Schema
fn json_to_schema(json: &Value) -> Schema {
    json.as_object().map_or_else(
        || {
            Schema::Object(Box::new(SchemaObject {
                schema_type: "string".to_string(),
                properties: None,
                required: None,
                format: None,
                items: None,
                minimum: None,
                maximum: None,
                min_length: None,
                max_length: None,
                pattern: None,
                description: None,
            }))
        },
        |obj| {
            let schema_type = obj.get("type").and_then(|v| v.as_str()).unwrap_or("string").to_string();

            Schema::Object(Box::new(SchemaObject {
                schema_type,
                properties: obj.get("properties").and_then(|v| {
                    v.as_object().map(|props| {
                        props
                            .iter()
                            .map(|(k, v)| (k.clone(), Box::new(json_to_schema(v))))
                            .collect()
                    })
                }),
                required: obj.get("required").and_then(|v| {
                    v.as_array()
                        .map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect())
                }),
                format: obj.get("format").and_then(|v| v.as_str()).map(String::from),
                items: obj.get("items").map(|v| Box::new(json_to_schema(v))),
                minimum: obj.get("minimum").and_then(Value::as_f64),
                maximum: obj.get("maximum").and_then(Value::as_f64),
                min_length: obj
                    .get("minLength")
                    .and_then(Value::as_u64)
                    .map(|v| usize::try_from(v).unwrap_or(0)),
                max_length: obj
                    .get("maxLength")
                    .and_then(Value::as_u64)
                    .map(|v| usize::try_from(v).unwrap_or(0)),
                pattern: obj.get("pattern").and_then(|v| v.as_str()).map(String::from),
                description: obj.get("description").and_then(|v| v.as_str()).map(String::from),
            }))
        },
    )
}

/// Sanitize path for operation ID
fn sanitize_path(path: &str) -> String {
    path.replace('/', "_")
        .replace(['{', '}'], "")
        .trim_matches('_')
        .to_string()
}

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

    #[test]
    fn test_sanitize_path() {
        assert_eq!(sanitize_path("/users/{id}"), "users_id");
        assert_eq!(sanitize_path("/api/v1/posts"), "api_v1_posts");
    }
}