autumn-web 0.3.0

An opinionated, convention-over-configuration web framework for Rust
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
// OpenAPI/JSON/JSON-schema all appear frequently here and are legitimate
// acronyms, so silence clippy::doc_markdown rather than wrapping every
// mention in backticks.
#![allow(clippy::doc_markdown)]

//! OpenAPI (Swagger) specification auto-generation.
//!
//! Autumn automatically infers an OpenAPI 3.0 document from your
//! annotated routes ([`get`](crate::get), [`post`](crate::post), etc.),
//! their path parameters, and the extractor / response types in each
//! handler signature. The generated spec is served at `/v3/api-docs` and
//! a Swagger UI is served at `/swagger-ui` when the feature is enabled.
//!
//! # Quick start
//!
//! Enable the `openapi` feature in `Cargo.toml`, then:
//!
//! ```toml
//! [dependencies]
//! autumn-web = { version = "0.2", features = ["openapi"] }
//! ```
//!
//! ```rust,ignore
//! use autumn_web::prelude::*;
//!
//! #[get("/hello")]
//! async fn hello() -> &'static str { "hi" }
//!
//! #[autumn_web::main]
//! async fn main() {
//!     autumn_web::app()
//!         .routes(routes![hello])
//!         .openapi(autumn_web::openapi::OpenApiConfig::new("My API", "1.0.0"))
//!         .run()
//!         .await;
//! }
//! ```
//!
//! With `.openapi(...)` enabled, the following endpoints are mounted:
//! * `GET /v3/api-docs` — serves the generated `openapi.json`.
//! * `GET /swagger-ui` — serves a Swagger UI HTML page loading the JSON
//!   above.
//!
//! # Enriching the auto-generated docs
//!
//! Decorate handlers with [`#[api_doc(...)]`](crate::api_doc) to override
//! or add documentation fields that cannot be inferred from the signature
//! (summaries, descriptions, tags, custom status codes, etc.):
//!
//! ```rust,no_run
//! use autumn_web::prelude::*;
//!
//! #[get("/users/{id}")]
//! #[api_doc(summary = "Fetch a user by id", tag = "users")]
//! async fn get_user(_id: Path<i32>) -> &'static str { "user" }
//! ```
//!
//! # Custom schemas
//!
//! Types that need rich schemas (beyond the generic "object" fallback)
//! implement the `OpenApiSchema` trait and are registered with
//! `OpenApiConfig::register_schema`.

use std::collections::BTreeMap;

#[cfg(feature = "openapi")]
use serde::{Deserialize, Serialize};

// ──────────────────────────────────────────────────────────────────
// Public metadata attached to each Route
// ──────────────────────────────────────────────────────────────────

/// OpenAPI metadata emitted alongside every annotated route.
///
/// Populated by the route macros ([`get`](crate::get),
/// [`post`](crate::post), etc.) from the handler's path, signature, and
/// any [`#[api_doc(...)]`](crate::api_doc) overrides.
#[derive(Clone, Debug, Default)]
pub struct ApiDoc {
    /// HTTP method as an uppercase string (e.g. `"GET"`).
    pub method: &'static str,
    /// Raw route path with `{param}` placeholders (e.g. `"/users/{id}"`).
    pub path: &'static str,
    /// Handler function name — used as the default `operationId`.
    pub operation_id: &'static str,
    /// Short human-readable summary (from `#[api_doc(summary = ...)]`).
    pub summary: Option<&'static str>,
    /// Longer free-form description.
    pub description: Option<&'static str>,
    /// Grouping tags. Defaults to the first path segment when unset.
    pub tags: &'static [&'static str],
    /// Path parameter names extracted from the URL template.
    ///
    /// Built at compile time from `{...}` segments in the route path.
    pub path_params: &'static [&'static str],
    /// Optional schema for the request body (typically the inner type of
    /// a `Json<T>` extractor).
    pub request_body: Option<SchemaEntry>,
    /// Optional schema for the success response (typically the inner type
    /// of a `Json<T>` return value).
    pub response: Option<SchemaEntry>,
    /// Success HTTP status code, defaults to `200`.
    pub success_status: u16,
    /// When `true`, the route is excluded from the generated spec.
    pub hidden: bool,
    /// Optional runtime hook that lets a handler register any extra
    /// component schemas with the generator.
    pub register_schemas: Option<fn(&mut SchemaRegistry)>,
}

/// Reference to a schema definition, produced by the route macros.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SchemaEntry {
    /// Short human-readable type name (used as `#/components/schemas/Name`).
    pub name: &'static str,
    /// Whether this is a primitive JSON type (string/number/bool/array) as
    /// opposed to a named object ref.
    pub kind: SchemaKind,
}

/// Classifier for how a type should appear in the spec.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum SchemaKind {
    /// Refers to a named component schema.
    Ref,
    /// A primitive JSON type inlined at the reference site.
    Primitive(&'static str),
    /// A JSON array whose items follow the referenced sub-schema. Used
    /// for handlers that return `Json<Vec<T>>` (or accept one as a
    /// request body) — emitting `Ref` for those would produce an
    /// object schema instead of the array the endpoint actually
    /// serializes.
    Array(&'static SchemaEntry),
    /// A nullable schema — used when the handler wraps the payload in
    /// `Option<T>`. The referenced sub-entry describes `T`.
    Nullable(&'static SchemaEntry),
}

// ──────────────────────────────────────────────────────────────────
// Configuration — users opt into OpenAPI generation explicitly.
// ──────────────────────────────────────────────────────────────────

/// User-facing configuration for OpenAPI generation.
///
/// Passed to [`AppBuilder::openapi`](crate::app::AppBuilder::openapi)
/// to enable spec generation and mount the documentation endpoints.
#[cfg(feature = "openapi")]
#[derive(Clone)]
pub struct OpenApiConfig {
    /// API title that appears in the Swagger UI header.
    pub title: String,
    /// API version (e.g. `"1.0.0"`).
    pub version: String,
    /// Optional free-form API description (Markdown permitted in UI).
    pub description: Option<String>,
    /// Path serving the raw `openapi.json`. Defaults to `/v3/api-docs`.
    pub openapi_json_path: String,
    /// Path serving the Swagger UI HTML. Defaults to `/swagger-ui`. Set
    /// to `None` to disable the UI while still exposing the JSON.
    pub swagger_ui_path: Option<String>,
    /// User-registered component schemas keyed by schema name.
    pub additional_schemas: BTreeMap<String, serde_json::Value>,
}

#[cfg(feature = "openapi")]
impl OpenApiConfig {
    /// Create a new config with the required `title` and `version`.
    #[must_use]
    pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            version: version.into(),
            description: None,
            openapi_json_path: "/v3/api-docs".to_owned(),
            swagger_ui_path: Some("/swagger-ui".to_owned()),
            additional_schemas: BTreeMap::new(),
        }
    }

    /// Set a free-form API description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Override the path serving `openapi.json`.
    #[must_use]
    pub fn openapi_json_path(mut self, path: impl Into<String>) -> Self {
        self.openapi_json_path = path.into();
        self
    }

    /// Override the Swagger UI path (or `None` to disable it).
    #[must_use]
    pub fn swagger_ui_path(mut self, path: Option<String>) -> Self {
        self.swagger_ui_path = path;
        self
    }

    /// Register a custom component schema. Useful when a handler's
    /// payload type does not implement `OpenApiSchema`.
    #[must_use]
    pub fn register_schema(mut self, name: impl Into<String>, schema: serde_json::Value) -> Self {
        self.additional_schemas.insert(name.into(), schema);
        self
    }
}

// ──────────────────────────────────────────────────────────────────
// Schema trait + primitive impls (feature-gated)
// ──────────────────────────────────────────────────────────────────

/// Describes a type's JSON schema for OpenAPI generation.
///
/// Provide a manual implementation for complex types to expose rich
/// schemas in the generated spec. A blanket default is not provided —
/// routes whose types do not implement this trait simply emit a generic
/// `object` placeholder referring to the type name.
#[cfg(feature = "openapi")]
pub trait OpenApiSchema {
    /// Component schema name (appears under `#/components/schemas/`).
    fn schema_name() -> &'static str;

    /// Produce the JSON schema for this type.
    fn schema() -> serde_json::Value;
}

#[cfg(feature = "openapi")]
macro_rules! impl_primitive_schema {
    ($ty:ty, $name:literal, $json:literal) => {
        impl OpenApiSchema for $ty {
            fn schema_name() -> &'static str {
                $name
            }
            fn schema() -> serde_json::Value {
                serde_json::json!({ "type": $json })
            }
        }
    };
}

#[cfg(feature = "openapi")]
impl_primitive_schema!(bool, "boolean", "boolean");
#[cfg(feature = "openapi")]
impl_primitive_schema!(String, "string", "string");
#[cfg(feature = "openapi")]
impl_primitive_schema!(&'static str, "string", "string");
#[cfg(feature = "openapi")]
impl_primitive_schema!(i8, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(i16, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(i32, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(i64, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(u8, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(u16, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(u32, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(u64, "integer", "integer");
#[cfg(feature = "openapi")]
impl_primitive_schema!(f32, "number", "number");
#[cfg(feature = "openapi")]
impl_primitive_schema!(f64, "number", "number");
#[cfg(feature = "openapi")]
impl_primitive_schema!(serde_json::Value, "object", "object");

// ──────────────────────────────────────────────────────────────────
// Runtime registry of component schemas populated while building the spec.
// ──────────────────────────────────────────────────────────────────

/// Accumulates component schemas while a spec is being built.
#[derive(Default)]
pub struct SchemaRegistry {
    schemas: BTreeMap<String, serde_json::Value>,
}

impl SchemaRegistry {
    /// Register a type via its `OpenApiSchema` implementation. A
    /// duplicate insertion is a no-op (the existing entry wins).
    #[cfg(feature = "openapi")]
    pub fn register<T: OpenApiSchema>(&mut self) {
        let name = T::schema_name().to_owned();
        self.schemas.entry(name).or_insert_with(T::schema);
    }

    /// Insert a raw pre-built schema by name.
    pub fn insert(&mut self, name: impl Into<String>, schema: serde_json::Value) {
        self.schemas.insert(name.into(), schema);
    }

    /// Drain the collected schemas, consuming the registry.
    #[must_use]
    pub fn into_map(self) -> BTreeMap<String, serde_json::Value> {
        self.schemas
    }

    /// Peek at the collected schemas without consuming the registry.
    #[must_use]
    pub const fn schemas(&self) -> &BTreeMap<String, serde_json::Value> {
        &self.schemas
    }
}

// ──────────────────────────────────────────────────────────────────
// Serializable OpenAPI 3.0 document types.
//
// Only the fields Autumn actually populates are modelled — unused
// OpenAPI keys (callbacks, links, discriminators…) are intentionally
// omitted so the generated JSON stays clean. Gated behind the
// `openapi` feature so the runtime spec builder doesn't add code
// size / dependency pressure to apps that never serve a JSON spec.
// ──────────────────────────────────────────────────────────────────

#[cfg(feature = "openapi")]
/// Represents a root OpenAPI 3.0 specification document.
#[derive(Debug, Serialize, Deserialize)]
pub struct OpenApiSpec {
    /// The OpenAPI version string (e.g., `3.0.3`).
    pub openapi: String,
    /// General information about the API.
    pub info: Info,
    /// The available paths and operations for the API.
    pub paths: BTreeMap<String, PathItem>,
    /// Reusable schemas, parameters, and other components.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub components: Option<Components>,
}

#[cfg(feature = "openapi")]
/// Provides metadata about the API.
#[derive(Debug, Serialize, Deserialize)]
pub struct Info {
    /// The title of the API.
    pub title: String,
    /// The version of the OpenAPI document.
    pub version: String,
    /// A description of the API.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

#[cfg(feature = "openapi")]
/// Describes the operations available on a single path.
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PathItem {
    /// A definition of a GET operation on this path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub get: Option<Operation>,
    /// A definition of a POST operation on this path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post: Option<Operation>,
    /// A definition of a PUT operation on this path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub put: Option<Operation>,
    /// A definition of a DELETE operation on this path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delete: Option<Operation>,
    /// A definition of a PATCH operation on this path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub patch: Option<Operation>,
}

#[cfg(feature = "openapi")]
/// Describes a single API operation on a path.
#[derive(Debug, Serialize, Deserialize)]
pub struct Operation {
    /// Unique string used to identify the operation.
    #[serde(rename = "operationId")]
    pub operation_id: String,
    /// A short summary of what the operation does.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// A verbose explanation of the operation behavior.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// A list of tags for API documentation control.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// A list of parameters that are applicable for this operation.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<Parameter>,
    /// The request body applicable for this operation.
    #[serde(rename = "requestBody", skip_serializing_if = "Option::is_none")]
    pub request_body: Option<RequestBody>,
    /// The list of possible responses as they are returned from executing this operation.
    pub responses: BTreeMap<String, Response>,
}

#[cfg(feature = "openapi")]
/// Describes a single operation parameter.
#[derive(Debug, Serialize, Deserialize)]
pub struct Parameter {
    /// The name of the parameter.
    pub name: String,
    /// The location of the parameter. Possible values are "query", "header", "path" or "cookie".
    #[serde(rename = "in")]
    pub location: String,
    /// Determines whether this parameter is mandatory.
    pub required: bool,
    /// The schema defining the type used for the parameter.
    pub schema: serde_json::Value,
}

#[cfg(feature = "openapi")]
/// Describes a single request body.
#[derive(Debug, Serialize, Deserialize)]
pub struct RequestBody {
    /// Determines if the request body is required in the request.
    pub required: bool,
    /// The content of the request body, keyed by media type.
    pub content: BTreeMap<String, MediaType>,
}

#[cfg(feature = "openapi")]
/// Describes a single response from an API Operation.
#[derive(Debug, Serialize, Deserialize)]
pub struct Response {
    /// A short description of the response.
    pub description: String,
    /// A map containing descriptions of potential response payloads, keyed by media type.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub content: BTreeMap<String, MediaType>,
}

#[cfg(feature = "openapi")]
/// Provides schema and examples for the media type identified by its key.
#[derive(Debug, Serialize, Deserialize)]
pub struct MediaType {
    /// The schema defining the content of the request, response, or parameter.
    pub schema: serde_json::Value,
}

#[cfg(feature = "openapi")]
/// Holds a set of reusable objects for different aspects of the OAS.
#[derive(Debug, Serialize, Deserialize)]
pub struct Components {
    /// Reusable Schema Objects.
    pub schemas: BTreeMap<String, serde_json::Value>,
}

// ──────────────────────────────────────────────────────────────────
// Spec generator
// ──────────────────────────────────────────────────────────────────

/// Build an [`OpenApiSpec`] from a collection of routes and user config.
///
/// This is the core of the auto-generation: every route's [`ApiDoc`] is
/// translated into an [`Operation`] under the matching [`PathItem`].
#[cfg(feature = "openapi")]
#[must_use]
pub fn generate_spec(config: &OpenApiConfig, routes: &[&ApiDoc]) -> OpenApiSpec {
    let mut paths: BTreeMap<String, PathItem> = BTreeMap::new();
    let mut registry = SchemaRegistry::default();

    for (name, schema) in &config.additional_schemas {
        registry.insert(name.clone(), schema.clone());
    }

    // Collect every named schema reference produced by any operation so
    // we can back-fill component entries for types the user didn't
    // explicitly register. Without this, auto-inferred `Json<MyDto>`
    // payloads would emit `$ref`s pointing at nonexistent component
    // schemas — an invalid OpenAPI document.
    let mut referenced_names: std::collections::BTreeSet<&'static str> =
        std::collections::BTreeSet::new();

    for api_doc in routes {
        if api_doc.hidden {
            continue;
        }
        if let Some(register) = api_doc.register_schemas {
            (register)(&mut registry);
        }

        if let Some(entry) = &api_doc.request_body {
            collect_ref_names(entry, &mut referenced_names);
        }
        if let Some(entry) = &api_doc.response {
            collect_ref_names(entry, &mut referenced_names);
        }

        let operation = operation_for(api_doc);
        let entry = paths.entry(api_doc.path.to_owned()).or_default();
        match api_doc.method {
            "GET" => entry.get = Some(operation),
            "POST" => entry.post = Some(operation),
            "PUT" => entry.put = Some(operation),
            "DELETE" => entry.delete = Some(operation),
            "PATCH" => entry.patch = Some(operation),
            // Unknown methods are silently skipped; Autumn's route macros
            // only emit the five verbs above today.
            _ => {}
        }
    }

    // Back-fill a minimal `{"type": "object", "title": "X"}` schema for
    // every referenced name the user didn't already register. Types that
    // implement OpenApiSchema can be registered explicitly via
    // OpenApiConfig::register_schema to replace the placeholder.
    for name in referenced_names {
        if !registry.schemas().contains_key(name) {
            registry.insert(
                name,
                serde_json::json!({
                    "type": "object",
                    "title": name,
                }),
            );
        }
    }

    let components_map = registry.into_map();
    let components = if components_map.is_empty() {
        None
    } else {
        Some(Components {
            schemas: components_map,
        })
    };

    OpenApiSpec {
        openapi: "3.0.3".to_owned(),
        info: Info {
            title: config.title.clone(),
            version: config.version.clone(),
            description: config.description.clone(),
        },
        paths,
        components,
    }
}

#[cfg(feature = "openapi")]
fn operation_for(api_doc: &ApiDoc) -> Operation {
    let tags = if api_doc.tags.is_empty() {
        default_tag(api_doc.path)
            .map(|t| vec![t.to_owned()])
            .unwrap_or_default()
    } else {
        api_doc.tags.iter().map(|s| (*s).to_owned()).collect()
    };

    let parameters = api_doc
        .path_params
        .iter()
        .map(|name| Parameter {
            name: (*name).to_owned(),
            location: "path".to_owned(),
            required: true,
            schema: serde_json::json!({ "type": "string" }),
        })
        .collect();

    let request_body = api_doc.request_body.as_ref().map(|entry| RequestBody {
        required: true,
        content: std::iter::once((
            "application/json".to_owned(),
            MediaType {
                schema: schema_value_for(entry),
            },
        ))
        .collect(),
    });

    let mut responses: BTreeMap<String, Response> = BTreeMap::new();
    let status = if api_doc.success_status == 0 {
        200
    } else {
        api_doc.success_status
    };
    let response_content = api_doc
        .response
        .as_ref()
        .map(|entry| {
            let mut content = BTreeMap::new();
            content.insert(
                "application/json".to_owned(),
                MediaType {
                    schema: schema_value_for(entry),
                },
            );
            content
        })
        .unwrap_or_default();
    responses.insert(
        status.to_string(),
        Response {
            description: status_description(status).to_owned(),
            content: response_content,
        },
    );

    Operation {
        operation_id: api_doc.operation_id.to_owned(),
        summary: api_doc.summary.map(str::to_owned),
        description: api_doc.description.map(str::to_owned),
        tags,
        parameters,
        request_body,
        responses,
    }
}

#[cfg(feature = "openapi")]
fn schema_value_for(entry: &SchemaEntry) -> serde_json::Value {
    match entry.kind {
        SchemaKind::Primitive(json_type) => serde_json::json!({ "type": json_type }),
        SchemaKind::Ref => {
            serde_json::json!({ "$ref": format!("#/components/schemas/{}", entry.name) })
        }
        SchemaKind::Array(items) => serde_json::json!({
            "type": "array",
            "items": schema_value_for(items),
        }),
        SchemaKind::Nullable(inner) => {
            // OpenAPI 3.0 has no `type: "null"` (that's a 3.1 feature),
            // so we use the 3.0-compatible patterns:
            //   * For a `$ref`, wrap in `allOf` alongside
            //     `nullable: true` — bare `$ref`s can't carry siblings,
            //     and `allOf` is the standard workaround.
            //   * For every other schema body, inject `nullable: true`
            //     directly onto the existing object.
            if inner.kind == SchemaKind::Ref {
                serde_json::json!({
                    "nullable": true,
                    "allOf": [schema_value_for(inner)],
                })
            } else {
                let mut v = schema_value_for(inner);
                if let Some(obj) = v.as_object_mut() {
                    obj.insert("nullable".to_owned(), serde_json::Value::Bool(true));
                }
                v
            }
        }
    }
}

/// Walk into a `SchemaEntry` and yield every named ref reached through
/// `Array` / `Nullable` wrappers. Back-fill logic uses this so a
/// `Json<Vec<User>>` response registers a `User` component schema.
#[cfg(feature = "openapi")]
fn collect_ref_names(entry: &SchemaEntry, out: &mut std::collections::BTreeSet<&'static str>) {
    match entry.kind {
        SchemaKind::Ref => {
            out.insert(entry.name);
        }
        SchemaKind::Array(inner) | SchemaKind::Nullable(inner) => collect_ref_names(inner, out),
        SchemaKind::Primitive(_) => {}
    }
}

#[cfg(feature = "openapi")]
fn default_tag(path: &str) -> Option<&str> {
    path.trim_start_matches('/')
        .split('/')
        .find(|seg| !seg.is_empty() && !seg.starts_with('{'))
}

#[cfg(feature = "openapi")]
const fn status_description(status: u16) -> &'static str {
    match status {
        200 => "OK",
        201 => "Created",
        202 => "Accepted",
        204 => "No Content",
        301 => "Moved Permanently",
        302 => "Found",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        409 => "Conflict",
        422 => "Unprocessable Entity",
        500 => "Internal Server Error",
        _ => "Response",
    }
}

// ──────────────────────────────────────────────────────────────────
// Swagger UI HTML
// ──────────────────────────────────────────────────────────────────

#[cfg(feature = "openapi")]
pub(crate) const SWAGGER_UI_VERSION: &str = "5.32.4";
#[cfg(feature = "openapi")]
pub(crate) const SWAGGER_UI_CSS: &str = include_str!("../vendor/swagger-ui/swagger-ui.css");
#[cfg(feature = "openapi")]
pub(crate) const SWAGGER_UI_BUNDLE: &[u8] =
    include_bytes!("../vendor/swagger-ui/swagger-ui-bundle.js");
#[cfg(feature = "openapi")]
const SWAGGER_UI_CSS_FILE: &str = "swagger-ui.css";
#[cfg(feature = "openapi")]
const SWAGGER_UI_BUNDLE_FILE: &str = "swagger-ui-bundle.js";
#[cfg(feature = "openapi")]
const SWAGGER_UI_INITIALIZER_FILE: &str = "swagger-initializer.js";

/// Compute the same-origin asset URLs mounted beneath the Swagger UI HTML path.
#[cfg(feature = "openapi")]
#[must_use]
pub(crate) fn swagger_ui_asset_paths(swagger_path: &str) -> [String; 3] {
    [
        swagger_ui_asset_path(swagger_path, SWAGGER_UI_CSS_FILE),
        swagger_ui_asset_path(swagger_path, SWAGGER_UI_BUNDLE_FILE),
        swagger_ui_asset_path(swagger_path, SWAGGER_UI_INITIALIZER_FILE),
    ]
}

#[cfg(feature = "openapi")]
#[must_use]
fn swagger_ui_asset_path(swagger_path: &str, asset_file: &str) -> String {
    let base = swagger_path.trim_end_matches('/');
    if base.is_empty() || base == "/" {
        format!("/{asset_file}")
    } else {
        format!("{base}/{asset_file}")
    }
}

/// Minimal Swagger UI bootstrap HTML that loads same-origin vendored assets.
#[cfg(feature = "openapi")]
#[must_use]
pub fn swagger_ui_html(
    title: &str,
    css_url: &str,
    bundle_url: &str,
    initializer_url: &str,
) -> String {
    let title = html_escape(title);
    let css_url = html_escape(css_url);
    let bundle_url = html_escape(bundle_url);
    let initializer_url = html_escape(initializer_url);
    let mut out = String::with_capacity(1024);
    out.push_str("<!DOCTYPE html>\n");
    out.push_str("<html lang=\"en\">\n");
    out.push_str("  <head>\n");
    out.push_str("    <meta charset=\"utf-8\" />\n");
    out.push_str("    <title>");
    out.push_str(&title);
    out.push_str("</title>\n");
    out.push_str("    <link rel=\"stylesheet\" href=\"");
    out.push_str(&css_url);
    out.push_str("\" />\n");
    out.push_str("  </head>\n");
    out.push_str("  <body>\n");
    out.push_str("    <div id=\"swagger-ui\"></div>\n");
    out.push_str("    <script src=\"");
    out.push_str(&bundle_url);
    out.push_str("\" charset=\"UTF-8\"></script>\n");
    out.push_str("    <script src=\"");
    out.push_str(&initializer_url);
    out.push_str("\" charset=\"UTF-8\"></script>\n");
    out.push_str("  </body>\n");
    out.push_str("</html>\n");
    out
}

/// External Swagger UI initializer script so the default `script-src 'self'`
/// CSP can boot the docs UI without permitting inline JavaScript.
#[cfg(feature = "openapi")]
#[must_use]
pub fn swagger_ui_initializer_js(spec_url: &str) -> String {
    let spec_url = serde_json::to_string(spec_url)
        .unwrap_or_else(|e| format!("\"/v3/api-docs?serialization_error={e}\""));
    let mut out = String::with_capacity(256);
    out.push_str("window.onload = function() {\n");
    out.push_str("  window.ui = SwaggerUIBundle({\n");
    out.push_str("    url: ");
    out.push_str(&spec_url);
    out.push_str(",\n");
    out.push_str("    dom_id: \"#swagger-ui\",\n");
    out.push_str("    deepLinking: true\n");
    out.push_str("  });\n");
    out.push_str("};\n");
    out
}

#[cfg(feature = "openapi")]
fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

// ──────────────────────────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────────────────────────

#[cfg(all(test, feature = "openapi"))]
mod tests {
    use super::*;

    fn make_doc() -> ApiDoc {
        ApiDoc {
            method: "GET",
            path: "/users/{id}",
            operation_id: "get_user",
            summary: Some("Fetch a user"),
            description: None,
            tags: &[],
            path_params: &["id"],
            request_body: None,
            response: None,
            success_status: 200,
            hidden: false,
            register_schemas: None,
        }
    }

    #[test]
    fn generate_spec_builds_path_with_parameters() {
        let doc = make_doc();
        let config = OpenApiConfig::new("Demo", "1.0.0");
        let spec = generate_spec(&config, &[&doc]);

        assert_eq!(spec.openapi, "3.0.3");
        assert_eq!(spec.info.title, "Demo");
        assert!(spec.paths.contains_key("/users/{id}"));

        let op = spec.paths["/users/{id}"].get.as_ref().unwrap();
        assert_eq!(op.operation_id, "get_user");
        assert_eq!(op.parameters.len(), 1);
        assert_eq!(op.parameters[0].name, "id");
        assert_eq!(op.parameters[0].location, "path");
        assert_eq!(op.tags, vec!["users".to_owned()]);
    }

    #[test]
    fn generate_spec_skips_hidden_routes() {
        let mut doc = make_doc();
        doc.hidden = true;
        let config = OpenApiConfig::new("Demo", "1.0.0");
        let spec = generate_spec(&config, &[&doc]);
        assert!(spec.paths.is_empty());
    }

    #[test]
    fn generate_spec_writes_request_body_ref() {
        let mut doc = make_doc();
        doc.method = "POST";
        doc.path = "/users";
        doc.operation_id = "create_user";
        doc.path_params = &[];
        doc.request_body = Some(SchemaEntry {
            name: "CreateUser",
            kind: SchemaKind::Ref,
        });
        doc.success_status = 201;

        let config = OpenApiConfig::new("Demo", "1.0.0");
        let spec = generate_spec(&config, &[&doc]);
        let op = spec.paths["/users"].post.as_ref().unwrap();
        let body = op.request_body.as_ref().unwrap();
        assert!(body.required);
        let media = body.content.get("application/json").unwrap();
        assert_eq!(
            media.schema,
            serde_json::json!({ "$ref": "#/components/schemas/CreateUser" }),
        );
        assert!(op.responses.contains_key("201"));
    }

    #[test]
    fn generate_spec_inlines_primitive_response() {
        let mut doc = make_doc();
        doc.response = Some(SchemaEntry {
            name: "string",
            kind: SchemaKind::Primitive("string"),
        });
        let config = OpenApiConfig::new("Demo", "1.0.0");
        let spec = generate_spec(&config, &[&doc]);
        let op = spec.paths["/users/{id}"].get.as_ref().unwrap();
        let media = op.responses["200"].content.get("application/json").unwrap();
        assert_eq!(media.schema, serde_json::json!({ "type": "string" }));
    }

    #[test]
    fn swagger_ui_html_uses_same_origin_assets() {
        let html = swagger_ui_html(
            "Demo",
            "/swagger-ui/swagger-ui.css",
            "/swagger-ui/swagger-ui-bundle.js",
            "/swagger-ui/swagger-initializer.js",
        );
        assert!(html.contains("/swagger-ui/swagger-ui.css"));
        assert!(html.contains("/swagger-ui/swagger-ui-bundle.js"));
        assert!(html.contains("/swagger-ui/swagger-initializer.js"));
        assert!(!html.contains("unpkg.com"));
        assert!(!html.contains("window.onload = function()"));
    }

    #[test]
    fn swagger_ui_initializer_js_references_spec_url() {
        let js = swagger_ui_initializer_js("/v3/api-docs");
        assert!(js.contains("SwaggerUIBundle"));
        assert!(js.contains(r#""/v3/api-docs""#));
    }

    #[test]
    fn nullable_ref_uses_openapi_3_0_shape() {
        // OpenAPI 3.0 has no `type: "null"`, so nullable refs must use
        // `nullable: true` + `allOf` instead. Wrapping in `anyOf` with
        // a `type: "null"` member produces a spec that Swagger and
        // OpenAPI validators reject.
        static INNER: SchemaEntry = SchemaEntry {
            name: "User",
            kind: SchemaKind::Ref,
        };
        let entry = SchemaEntry {
            name: "nullable",
            kind: SchemaKind::Nullable(&INNER),
        };
        let value = schema_value_for(&entry);
        assert_eq!(value["nullable"], true);
        assert_eq!(
            value["allOf"][0]["$ref"], "#/components/schemas/User",
            "nullable refs must wrap in allOf so `$ref` can carry siblings"
        );
        assert!(value.get("anyOf").is_none(), "must not emit anyOf/null");
        assert!(
            value.get("type").is_none()
                || value.get("type").unwrap() != &serde_json::Value::String("null".into()),
            "must not emit type: null"
        );
    }

    #[test]
    fn nullable_primitive_inlines_nullable_flag() {
        static INNER: SchemaEntry = SchemaEntry {
            name: "integer",
            kind: SchemaKind::Primitive("integer"),
        };
        let entry = SchemaEntry {
            name: "nullable",
            kind: SchemaKind::Nullable(&INNER),
        };
        let value = schema_value_for(&entry);
        assert_eq!(value["type"], "integer");
        assert_eq!(value["nullable"], true);
    }

    #[test]
    fn generate_spec_includes_additional_schemas() {
        let doc = make_doc();
        let config = OpenApiConfig::new("Demo", "1.0.0")
            .register_schema("Foo", serde_json::json!({ "type": "object" }));
        let spec = generate_spec(&config, &[&doc]);
        let components = spec.components.unwrap();
        assert!(components.schemas.contains_key("Foo"));
    }

    #[test]
    fn generate_spec_back_fills_unregistered_ref_schemas() {
        // A Json<CreateUser> handler emits a `$ref` with no component
        // schema registered. The generator must back-fill a placeholder
        // schema so the resulting OpenAPI document is valid.
        let mut doc = make_doc();
        doc.method = "POST";
        doc.path = "/users";
        doc.path_params = &[];
        doc.request_body = Some(SchemaEntry {
            name: "CreateUser",
            kind: SchemaKind::Ref,
        });
        doc.response = Some(SchemaEntry {
            name: "User",
            kind: SchemaKind::Ref,
        });

        let config = OpenApiConfig::new("Demo", "1.0.0");
        let spec = generate_spec(&config, &[&doc]);
        let components = spec.components.expect("components must be emitted");
        let create = components
            .schemas
            .get("CreateUser")
            .expect("CreateUser should be back-filled");
        let user = components
            .schemas
            .get("User")
            .expect("User should be back-filled");
        assert_eq!(create["type"], "object");
        assert_eq!(create["title"], "CreateUser");
        assert_eq!(user["type"], "object");
        assert_eq!(user["title"], "User");
    }

    #[test]
    fn generate_spec_preserves_user_registered_schemas_over_backfill() {
        let mut doc = make_doc();
        doc.response = Some(SchemaEntry {
            name: "User",
            kind: SchemaKind::Ref,
        });

        let user_schema = serde_json::json!({
            "type": "object",
            "properties": {"id": {"type": "integer"}},
        });
        let config =
            OpenApiConfig::new("Demo", "1.0.0").register_schema("User", user_schema.clone());
        let spec = generate_spec(&config, &[&doc]);
        let components = spec.components.unwrap();
        let stored = components.schemas.get("User").unwrap();
        assert_eq!(stored, &user_schema, "user schema must not be overwritten");
    }

    #[test]
    fn default_tag_picks_first_static_segment() {
        assert_eq!(default_tag("/users/{id}"), Some("users"));
        assert_eq!(default_tag("/api/v1/users"), Some("api"));
        assert_eq!(default_tag("/"), None);
        assert_eq!(default_tag("/{id}"), None);
    }

    #[test]
    fn schema_registry_deduplicates() {
        struct Foo;
        impl OpenApiSchema for Foo {
            fn schema_name() -> &'static str {
                "Foo"
            }
            fn schema() -> serde_json::Value {
                serde_json::json!({ "type": "object", "title": "Foo" })
            }
        }

        let mut registry = SchemaRegistry::default();
        registry.register::<Foo>();
        registry.register::<Foo>();
        assert_eq!(registry.schemas().len(), 1);
    }

    #[test]
    fn primitive_impls_cover_common_types() {
        assert_eq!(<String as OpenApiSchema>::schema_name(), "string");
        assert_eq!(<i32 as OpenApiSchema>::schema_name(), "integer");
        assert_eq!(<bool as OpenApiSchema>::schema_name(), "boolean");
        assert_eq!(<f64 as OpenApiSchema>::schema_name(), "number");
    }

    #[test]
    fn swagger_ui_html_embeds_spec_url() {
        let html = swagger_ui_html(
            "My API",
            "/swagger-ui/swagger-ui.css",
            "/swagger-ui/swagger-ui-bundle.js",
            "/swagger-ui/swagger-initializer.js",
        );
        assert!(html.contains("/swagger-ui/swagger-ui.css"));
        assert!(html.contains("My API"));
    }

    #[test]
    fn swagger_ui_html_escapes_attributes() {
        let html = swagger_ui_html(
            "A \"cool\" & fun API",
            "/swagger-ui/swagger-ui.css?x=<y>",
            "/swagger-ui/swagger-ui-bundle.js",
            "/swagger-ui/swagger-initializer.js",
        );
        assert!(html.contains("/swagger-ui/swagger-ui.css?x=&lt;y&gt;"));
        assert!(html.contains("A &quot;cool&quot; &amp; fun API"));
    }
}