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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
#![cfg_attr(doc_cfg, feature(doc_cfg))]
//! This crate implements necessary boiler plate code to serve Swagger UI via web server. It
//! works as a bridge for serving the OpenAPI documentation created with [`utoipa`][utoipa] library in the
//! Swagger UI.
//!
//! [utoipa]: <https://docs.rs/utoipa/>
//!
//! **Currently implemented boiler plate for:**
//!
//! * **actix-web** `version >= 4`
//! * **rocket** `version >=0.5.0-rc.2`
//! * **axum** `version >=0.6`
//!
//! Serving Swagger UI is framework independent thus this crate also supports serving the Swagger UI with
//! other frameworks as well. With other frameworks there is bit more manual implementation to be done. See
//! more details at [`serve`] or [`examples`][examples].
//!
//! [examples]: <https://github.com/juhaku/utoipa/tree/master/examples>
//!
//! # Crate Features
//!
//! * **actix-web** Enables `actix-web` integration with pre-configured SwaggerUI service factory allowing
//!   users to use the Swagger UI without a hassle.
//! * **rocket** Enables `rocket` integration with with pre-configured routes for serving the Swagger UI
//!   and api doc without a hassle.
//! * **axum** Enables `axum` integration with pre-configured Router serving Swagger UI and OpenAPI specs
//!   hassle free.
//! * **debug-embed** Enables `debug-embed` feature on `rust_embed` crate to allow embedding files in debug
//!   builds as well.
//!
//! # Install
//!
//! Use only the raw types without any boiler plate implementation.
//! ```toml
//! [dependencies]
//! utoipa-swagger-ui = "3"
//!
//! ```
//! Enable actix-web framework with Swagger UI you could define the dependency as follows.
//! ```toml
//! [dependencies]
//! utoipa-swagger-ui = { version = "3", features = ["actix-web"] }
//! ```
//!
//! **Note!** Also remember that you already have defined `utoipa` dependency in your `Cargo.toml`
//!
//! # Examples
//!
//! Serve Swagger UI with api doc via **`actix-web`**. See full example from
//! [examples](https://github.com/juhaku/utoipa/tree/master/examples/todo-actix).
//! ```no_run
//! # use actix_web::{App, HttpServer};
//! # use utoipa_swagger_ui::SwaggerUi;
//! # use utoipa::OpenApi;
//! # use std::net::Ipv4Addr;
//! # #[derive(OpenApi)]
//! # #[openapi()]
//! # struct ApiDoc;
//! HttpServer::new(move || {
//!         App::new()
//!             .service(
//!                 SwaggerUi::new("/swagger-ui/{_:.*}")
//!                     .url("/api-docs/openapi.json", ApiDoc::openapi()),
//!             )
//!     })
//!     .bind((Ipv4Addr::UNSPECIFIED, 8989)).unwrap()
//!     .run();
//! ```
//!
//! Serve Swagger UI with api doc via **`rocket`**. See full example from
//! [examples](https://github.com/juhaku/utoipa/tree/master/examples/rocket-todo).
//! ```no_run
//! # use rocket::{Build, Rocket};
//! # use utoipa_swagger_ui::SwaggerUi;
//! # use utoipa::OpenApi;
//! #[rocket::launch]
//! fn rocket() -> Rocket<Build> {
//! #
//! #     #[derive(OpenApi)]
//! #     #[openapi()]
//! #     struct ApiDoc;
//! #
//!     rocket::build()
//!         .mount(
//!             "/",
//!             SwaggerUi::new("/swagger-ui/<_..>")
//!                 .url("/api-docs/openapi.json", ApiDoc::openapi()),
//!         )
//! }
//! ```
//!
//! Setup Router to serve Swagger UI with **`axum`** framework. See full implementation of how to serve
//! Swagger UI with axum from [examples](https://github.com/juhaku/utoipa/tree/master/examples/todo-axum).
//!```no_run
//! # use axum::{routing, Router, body::HttpBody};
//! # use utoipa_swagger_ui::SwaggerUi;
//! # use utoipa::OpenApi;
//!# #[derive(OpenApi)]
//!# #[openapi()]
//!# struct ApiDoc;
//!#
//!# fn inner<S, B>()
//!# where
//!#     B: HttpBody + Send + 'static,
//!#     S: Clone + Send + Sync + 'static,
//!# {
//! let app = Router::<S, B>::new()
//!     .merge(SwaggerUi::new("/swagger-ui")
//!         .url("/api-docs/openapi.json", ApiDoc::openapi()));
//!# }
//! ```
use std::{borrow::Cow, error::Error, mem, sync::Arc};

mod actix;
mod axum;
pub mod oauth;
mod rocket;

use rust_embed::RustEmbed;
use serde::Serialize;
#[cfg(any(feature = "actix-web", feature = "rocket", feature = "axum"))]
use utoipa::openapi::OpenApi;

#[derive(RustEmbed)]
#[folder = "$UTOIPA_SWAGGER_DIR/$UTOIPA_SWAGGER_UI_VERSION/dist/"]
struct SwaggerUiDist;

/// Entry point for serving Swagger UI and api docs in application. It uses provides
/// builder style chainable configuration methods for configuring api doc urls.
///
/// # Examples
///
/// Create new [`SwaggerUi`] with defaults.
/// ```rust
/// # use utoipa_swagger_ui::SwaggerUi;
/// # use utoipa::OpenApi;
/// # #[derive(OpenApi)]
/// # #[openapi()]
/// # struct ApiDoc;
/// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
///     .url("/api-docs/openapi.json", ApiDoc::openapi());
/// ```
///
/// Create a new [`SwaggerUi`] with custom [`Config`] and [`oauth::Config`].
/// ```rust
/// # use utoipa_swagger_ui::{SwaggerUi, Config, oauth};
/// # use utoipa::OpenApi;
/// # #[derive(OpenApi)]
/// # #[openapi()]
/// # struct ApiDoc;
/// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
///     .url("/api-docs/openapi.json", ApiDoc::openapi())
///     .config(Config::default().try_it_out_enabled(true).filter(true))
///     .oauth(oauth::Config::new());
/// ```
///
#[non_exhaustive]
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg(any(feature = "actix-web", feature = "rocket", feature = "axum"))]
#[cfg_attr(
    doc_cfg,
    doc(cfg(any(feature = "actix-web", feature = "rocket", feature = "axum")))
)]
pub struct SwaggerUi {
    path: Cow<'static, str>,
    urls: Vec<(Url<'static>, OpenApi)>,
    config: Option<Config<'static>>,
    external_urls: Vec<(Url<'static>, serde_json::Value)>,
}

#[cfg(any(feature = "actix-web", feature = "rocket", feature = "axum"))]
#[cfg_attr(
    doc_cfg,
    doc(cfg(any(feature = "actix-web", feature = "rocket", feature = "axum")))
)]
impl SwaggerUi {
    /// Create a new [`SwaggerUi`] for given path.
    ///
    /// Path argument will expose the Swagger UI to the user and should be something that
    /// the underlying application framework / library supports.
    ///
    /// # Examples
    ///
    /// Exposes Swagger UI using path `/swagger-ui` using actix-web supported syntax.
    ///
    /// ```rust
    /// # use utoipa_swagger_ui::SwaggerUi;
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}");
    /// ```
    pub fn new<P: Into<Cow<'static, str>>>(path: P) -> Self {
        Self {
            path: path.into(),
            urls: Vec::new(),
            config: None,
            external_urls: Vec::new(),
        }
    }

    /// Add api doc [`Url`] into [`SwaggerUi`].
    ///
    /// Method takes two arguments where first one is path which exposes the [`OpenApi`] to the user.
    /// Second argument is the actual Rust implementation of the OpenAPI doc which is being exposed.
    ///
    /// Calling this again will add another url to the Swagger UI.
    ///
    /// # Examples
    ///
    /// Expose manually created OpenAPI doc.
    /// ```rust
    /// # use utoipa_swagger_ui::SwaggerUi;
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
    ///     .url("/api-docs/openapi.json", utoipa::openapi::OpenApi::new(
    ///        utoipa::openapi::Info::new("my application", "0.1.0"),
    ///        utoipa::openapi::Paths::new(),
    /// ));
    /// ```
    ///
    /// Expose derived OpenAPI doc.
    /// ```rust
    /// # use utoipa_swagger_ui::SwaggerUi;
    /// # use utoipa::OpenApi;
    /// # #[derive(OpenApi)]
    /// # #[openapi()]
    /// # struct ApiDoc;
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
    ///     .url("/api-docs/openapi.json", ApiDoc::openapi());
    /// ```
    pub fn url<U: Into<Url<'static>>>(mut self, url: U, openapi: OpenApi) -> Self {
        self.urls.push((url.into(), openapi));

        self
    }

    /// Add multiple [`Url`]s to Swagger UI.
    ///
    /// Takes one [`Vec`] argument containing tuples of [`Url`] and [`OpenApi`].
    ///
    /// Situations where this comes handy is when there is a need or wish to separate different parts
    /// of the api to separate api docs.
    ///
    /// # Examples
    ///
    /// Expose multiple api docs via Swagger UI.
    /// ```rust
    /// # use utoipa_swagger_ui::{SwaggerUi, Url};
    /// # use utoipa::OpenApi;
    /// # #[derive(OpenApi)]
    /// # #[openapi()]
    /// # struct ApiDoc;
    /// # #[derive(OpenApi)]
    /// # #[openapi()]
    /// # struct ApiDoc2;
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
    ///     .urls(
    ///       vec![
    ///          (Url::with_primary("api doc 1", "/api-docs/openapi.json", true), ApiDoc::openapi()),
    ///          (Url::new("api doc 2", "/api-docs/openapi2.json"), ApiDoc2::openapi())
    ///     ]
    /// );
    /// ```
    pub fn urls(mut self, urls: Vec<(Url<'static>, OpenApi)>) -> Self {
        self.urls = urls;

        self
    }

    /// Add external API doc to the [`SwaggerUi`].
    ///
    /// This operation is unchecked and so it does not check any validity of provided content.
    /// Users are required to do their own check if any regarding validity of the external
    /// OpenAPI document.
    ///
    /// Method accepts two arguments, one is [`Url`] the API doc is served at and the second one is
    /// the [`serde_json::Value`] of the OpenAPI doc to be served.
    ///
    /// # Examples
    ///
    /// Add external API doc to the [`SwaggerUi`].
    ///```rust
    /// # use utoipa_swagger_ui::{SwaggerUi, Url};
    /// # use utoipa::OpenApi;
    /// # use serde_json::json;
    /// let external_openapi = json!({"openapi": "3.0.0"});
    ///
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
    ///     .external_url_unchecked("/api-docs/openapi.json", external_openapi);
    ///```
    pub fn external_url_unchecked<U: Into<Url<'static>>>(
        mut self,
        url: U,
        openapi: serde_json::Value,
    ) -> Self {
        self.external_urls.push((url.into(), openapi));

        self
    }

    /// Add external API docs to the [`SwaggerUi`] from iterator.
    ///
    /// This operation is unchecked and so it does not check any validity of provided content.
    /// Users are required to do their own check if any regarding validity of the external
    /// OpenAPI documents.
    ///
    /// Method accepts one argument, an `iter` of [`Url`] and [`serde_json::Value`] tuples. The
    /// [`Url`] will point to location the OpenAPI document is served and the [`serde_json::Value`]
    /// is the OpenAPI document to be served.
    ///
    /// # Examples
    ///
    /// Add external API docs to the [`SwaggerUi`].
    ///```rust
    /// # use utoipa_swagger_ui::{SwaggerUi, Url};
    /// # use utoipa::OpenApi;
    /// # use serde_json::json;
    /// let external_openapi = json!({"openapi": "3.0.0"});
    /// let external_openapi2 = json!({"openapi": "3.0.0"});
    ///
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
    ///     .external_urls_from_iter_unchecked([
    ///         ("/api-docs/openapi.json", external_openapi),
    ///         ("/api-docs/openapi2.json", external_openapi2)
    ///     ]);
    ///```
    pub fn external_urls_from_iter_unchecked<
        I: IntoIterator<Item = (U, serde_json::Value)>,
        U: Into<Url<'static>>,
    >(
        mut self,
        external_urls: I,
    ) -> Self {
        self.external_urls.extend(
            external_urls
                .into_iter()
                .map(|(url, doc)| (url.into(), doc)),
        );

        self
    }

    /// Add oauth [`oauth::Config`] into [`SwaggerUi`].
    ///
    /// Method takes one argument which exposes the [`oauth::Config`] to the user.
    ///
    /// # Examples
    ///
    /// Enable pkce with default client_id.
    /// ```rust
    /// # use utoipa_swagger_ui::{SwaggerUi, oauth};
    /// # use utoipa::OpenApi;
    /// # #[derive(OpenApi)]
    /// # #[openapi()]
    /// # struct ApiDoc;
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
    ///     .url("/api-docs/openapi.json", ApiDoc::openapi())
    ///     .oauth(oauth::Config::new()
    ///         .client_id("client-id")
    ///         .scopes(vec![String::from("openid")])
    ///         .use_pkce_with_authorization_code_grant(true)
    ///     );
    /// ```
    pub fn oauth(mut self, oauth: oauth::Config) -> Self {
        let config = self.config.get_or_insert(Default::default());
        config.oauth = Some(oauth);

        self
    }

    /// Add custom [`Config`] into [`SwaggerUi`] which gives users more granular control over
    /// Swagger UI options.
    ///
    /// Methods takes one [`Config`] argument which exposes Swagger UI's configurable options
    /// to the users.
    ///
    /// # Examples
    ///
    /// Create a new [`SwaggerUi`] with custom configuration.
    /// ```rust
    /// # use utoipa_swagger_ui::{SwaggerUi, Config};
    /// # use utoipa::OpenApi;
    /// # #[derive(OpenApi)]
    /// # #[openapi()]
    /// # struct ApiDoc;
    /// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
    ///     .url("/api-docs/openapi.json", ApiDoc::openapi())
    ///     .config(Config::default().try_it_out_enabled(true).filter(true));
    /// ```
    pub fn config(mut self, config: Config<'static>) -> Self {
        self.config = Some(config);

        self
    }
}

/// Rust type for Swagger UI url configuration object.
#[non_exhaustive]
#[cfg_attr(feature = "debug", derive(Debug))]
#[derive(Default, Serialize, Clone)]
pub struct Url<'a> {
    name: Cow<'a, str>,
    url: Cow<'a, str>,
    #[serde(skip)]
    primary: bool,
}

impl<'a> Url<'a> {
    /// Create new [`Url`].
    ///
    /// Name is shown in the select dropdown when there are multiple docs in Swagger UI.
    ///
    /// Url is path which exposes the OpenAPI doc.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use utoipa_swagger_ui::Url;
    /// let url = Url::new("My Api", "/api-docs/openapi.json");
    /// ```
    pub fn new(name: &'a str, url: &'a str) -> Self {
        Self {
            name: Cow::Borrowed(name),
            url: Cow::Borrowed(url),
            ..Default::default()
        }
    }

    /// Create new [`Url`] with primary flag.
    ///
    /// Primary flag allows users to override the default behavior of the Swagger UI for selecting the primary
    /// doc to display. By default when there are multiple docs in Swagger UI the first one in the list
    /// will be the primary.
    ///
    /// Name is shown in the select dropdown when there are multiple docs in Swagger UI.
    ///
    /// Url is path which exposes the OpenAPI doc.
    ///
    /// # Examples
    ///
    /// Set "My Api" as primary.
    /// ```rust
    /// # use utoipa_swagger_ui::Url;
    /// let url = Url::with_primary("My Api", "/api-docs/openapi.json", true);
    /// ```
    pub fn with_primary(name: &'a str, url: &'a str, primary: bool) -> Self {
        Self {
            name: Cow::Borrowed(name),
            url: Cow::Borrowed(url),
            primary,
        }
    }
}

impl<'a> From<&'a str> for Url<'a> {
    fn from(url: &'a str) -> Self {
        Self {
            url: Cow::Borrowed(url),
            ..Default::default()
        }
    }
}

impl From<String> for Url<'_> {
    fn from(url: String) -> Self {
        Self {
            url: Cow::Owned(url),
            ..Default::default()
        }
    }
}

impl<'a> From<Cow<'static, str>> for Url<'a> {
    fn from(url: Cow<'static, str>) -> Self {
        Self {
            url,
            ..Default::default()
        }
    }
}

const SWAGGER_STANDALONE_LAYOUT: &str = "StandaloneLayout";
const SWAGGER_BASE_LAYOUT: &str = "BaseLayout";

/// Object used to alter Swagger UI settings.
///
/// Config struct provides [Swagger UI configuration](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md)
/// for settings which could be altered with **docker variables**.
///
/// # Examples
///
/// In simple case create config directly from url that points to the api doc json.
/// ```rust
/// # use utoipa_swagger_ui::Config;
/// let config = Config::from("/api-doc.json");
/// ```
///
/// If there is multiple api docs to serve config can be also directly created with [`Config::new`]
/// ```rust
/// # use utoipa_swagger_ui::Config;
/// let config = Config::new(["/api-docs/openapi1.json", "/api-docs/openapi2.json"]);
/// ```
///
/// Or same as above but more verbose syntax.
/// ```rust
/// # use utoipa_swagger_ui::{Config, Url};
/// let config = Config::new([
///     Url::new("api1", "/api-docs/openapi1.json"),
///     Url::new("api2", "/api-docs/openapi2.json")
/// ]);
/// ```
///
/// With oauth config.
/// ```rust
/// # use utoipa_swagger_ui::{Config, oauth};
/// let config = Config::with_oauth_config(
///     ["/api-docs/openapi1.json", "/api-docs/openapi2.json"],
///     oauth::Config::new(),
/// );
/// ```
#[non_exhaustive]
#[derive(Serialize, Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[serde(rename_all = "camelCase")]
pub struct Config<'a> {
    /// Url to fetch external configuration from.
    #[serde(skip_serializing_if = "Option::is_none")]
    config_url: Option<String>,

    /// Id of the DOM element where `Swagger UI` will put it's user interface.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "dom_id")]
    dom_id: Option<String>,

    /// [`Url`] the Swagger UI is serving.
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,

    /// Name of the primary url if any.
    #[serde(skip_serializing_if = "Option::is_none", rename = "urls.primaryName")]
    urls_primary_name: Option<String>,

    /// [`Url`]s the Swagger UI is serving.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    urls: Vec<Url<'a>>,

    /// Enables overriding configuration parameters with url query parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    query_config_enabled: Option<bool>,

    /// Controls whether [deep linking](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/deep-linking.md)
    /// is enabled in OpenAPI spec.
    ///
    /// Deep linking automatically scrolls and expands UI to given url fragment.
    #[serde(skip_serializing_if = "Option::is_none")]
    deep_linking: Option<bool>,

    /// Controls whether operation id is shown in the operation list.
    #[serde(skip_serializing_if = "Option::is_none")]
    display_operation_id: Option<bool>,

    /// Default models expansion depth; -1 will completely hide the models.
    #[serde(skip_serializing_if = "Option::is_none")]
    default_models_expand_depth: Option<isize>,

    /// Default model expansion depth from model example section.
    #[serde(skip_serializing_if = "Option::is_none")]
    default_model_expand_depth: Option<isize>,

    /// Defines how models is show when API is first rendered.
    #[serde(skip_serializing_if = "Option::is_none")]
    default_model_rendering: Option<String>,

    /// Define whether request duration in milliseconds is displayed for "Try it out" requests.
    #[serde(skip_serializing_if = "Option::is_none")]
    display_request_duration: Option<bool>,

    /// Controls default expansion for operations and tags.
    #[serde(skip_serializing_if = "Option::is_none")]
    doc_expansion: Option<String>,

    /// Defines is filtering of tagged operations allowed with edit box in top bar.
    #[serde(skip_serializing_if = "Option::is_none")]
    filter: Option<bool>,

    /// Controls how many tagged operations are shown. By default all operations are shown.
    #[serde(skip_serializing_if = "Option::is_none")]
    max_displayed_tags: Option<usize>,

    /// Defines whether extensions are shown.
    #[serde(skip_serializing_if = "Option::is_none")]
    show_extensions: Option<bool>,

    /// Defines whether common extensions are shown.
    #[serde(skip_serializing_if = "Option::is_none")]
    show_common_extensions: Option<bool>,

    /// Defines whether "Try it out" section should be enabled by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    try_it_out_enabled: Option<bool>,

    /// Defines whether request snippets section is enabled. If disabled legacy curl snipped
    /// will be used.
    #[serde(skip_serializing_if = "Option::is_none")]
    request_snippets_enabled: Option<bool>,

    /// Oauth redirect url.
    #[serde(skip_serializing_if = "Option::is_none")]
    oauth2_redirect_url: Option<String>,

    /// Defines whether request mutated with `requestInterceptor` will be used to produce curl command
    /// in the UI.
    #[serde(skip_serializing_if = "Option::is_none")]
    show_mutated_request: Option<bool>,

    /// Define supported http request submit methods.
    #[serde(skip_serializing_if = "Option::is_none")]
    supported_submit_methods: Option<Vec<String>>,

    /// Define validator url which is used to validate the Swagger spec. By default the validator swagger.io's
    /// online validator is used. Setting this to none will disable spec validation.
    #[serde(skip_serializing_if = "Option::is_none")]
    validator_url: Option<String>,

    /// Enables passing credentials to CORS requests as defined
    /// [fetch standards](https://fetch.spec.whatwg.org/#credentials).
    #[serde(skip_serializing_if = "Option::is_none")]
    with_credentials: Option<bool>,

    /// Defines whether authorizations is persisted throughout browser refresh and close.
    #[serde(skip_serializing_if = "Option::is_none")]
    persist_authorization: Option<bool>,

    /// [`oauth::Config`] the Swagger UI is using for auth flow.
    #[serde(skip)]
    oauth: Option<oauth::Config>,

    /// The layout of Swagger UI uses, default is `"StandaloneLayout"`
    layout: &'a str,
}

impl<'a> Config<'a> {
    fn new_<I: IntoIterator<Item = U>, U: Into<Url<'a>>>(
        urls: I,
        oauth_config: Option<oauth::Config>,
    ) -> Self {
        let urls = urls.into_iter().map(Into::into).collect::<Vec<Url<'a>>>();
        let urls_len = urls.len();

        Self {
            oauth: oauth_config,
            ..if urls_len == 1 {
                Self::new_config_with_single_url(urls)
            } else {
                Self::new_config_with_multiple_urls(urls)
            }
        }
    }

    fn new_config_with_multiple_urls(urls: Vec<Url<'a>>) -> Self {
        let primary_name = urls
            .iter()
            .find(|url| url.primary)
            .map(|url| url.name.to_string());

        Self {
            urls_primary_name: primary_name,
            urls: urls
                .into_iter()
                .map(|mut url| {
                    if url.name == "" {
                        url.name = Cow::Owned(String::from(&url.url[..]));

                        url
                    } else {
                        url
                    }
                })
                .collect(),
            ..Default::default()
        }
    }

    fn new_config_with_single_url(mut urls: Vec<Url<'a>>) -> Self {
        let url = urls.get_mut(0).map(mem::take).unwrap();
        let primary_name = if url.primary {
            Some(url.name.to_string())
        } else {
            None
        };

        Self {
            urls_primary_name: primary_name,
            url: if url.name == "" {
                Some(url.url.to_string())
            } else {
                None
            },
            urls: if url.name != "" {
                vec![url]
            } else {
                Vec::new()
            },
            ..Default::default()
        }
    }

    /// Constructs a new [`Config`] from [`Iterator`] of [`Url`]s.
    ///
    /// [`Url`]s provided to the [`Config`] will only change the urls Swagger UI is going to use to
    /// fetch the API document. This does not change the URL that is defined with [`SwaggerUi::url`]
    /// or [`SwaggerUi::urls`] which defines the URL the API document is exposed from.
    ///
    /// # Examples
    /// Create new config with 2 api doc urls.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi1.json", "/api-docs/openapi2.json"]);
    /// ```
    pub fn new<I: IntoIterator<Item = U>, U: Into<Url<'a>>>(urls: I) -> Self {
        Self::new_(urls, None)
    }

    /// Constructs a new [`Config`] from [`Iterator`] of [`Url`]s.
    ///
    /// # Examples
    /// Create new config with oauth config.
    /// ```rust
    /// # use utoipa_swagger_ui::{Config, oauth};
    /// let config = Config::with_oauth_config(
    ///     ["/api-docs/openapi1.json", "/api-docs/openapi2.json"],
    ///     oauth::Config::new(),
    /// );
    /// ```
    pub fn with_oauth_config<I: IntoIterator<Item = U>, U: Into<Url<'a>>>(
        urls: I,
        oauth_config: oauth::Config,
    ) -> Self {
        Self::new_(urls, Some(oauth_config))
    }

    /// Configure defaults for current [`Config`].
    ///
    /// A new [`Config`] will be created with given `urls` and its _**default values**_ and
    /// _**url, urls and urls_primary_name**_ will be moved to the current [`Config`] the method
    /// is called on.
    ///
    /// Current config will be returned with configured default values.
    #[cfg(any(feature = "actix-web", feature = "rocket", feature = "axum"))]
    #[cfg_attr(
        doc_cfg,
        doc(cfg(any(feature = "actix-web", feature = "rocket", feature = "axum")))
    )]
    fn configure_defaults<I: IntoIterator<Item = U>, U: Into<Url<'a>>>(mut self, urls: I) -> Self {
        let Config {
            dom_id,
            deep_linking,
            url,
            urls,
            urls_primary_name,
            ..
        } = Config::new(urls);

        self.dom_id = dom_id;
        self.deep_linking = deep_linking;
        self.url = url;
        self.urls = urls;
        self.urls_primary_name = urls_primary_name;

        self
    }

    /// Add url to fetch external configuration from.
    ///
    /// # Examples
    ///
    /// Set external config url.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .config_url("http://url.to.external.config");
    /// ```
    pub fn config_url<S: Into<String>>(mut self, config_url: S) -> Self {
        self.config_url = Some(config_url.into());

        self
    }

    /// Add id of the DOM element where `Swagger UI` will put it's user interface.
    ///
    /// The default value is `#swagger-ui`.
    ///
    /// # Examples
    ///
    /// Set custom dom id where the Swagger UI will place it's content.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"]).dom_id("#my-id");
    /// ```
    pub fn dom_id<S: Into<String>>(mut self, dom_id: S) -> Self {
        self.dom_id = Some(dom_id.into());

        self
    }

    /// Set `query_config_enabled` to allow overriding configuration parameters via url `query`
    /// parameters.
    ///
    /// Default value is `false`.
    ///
    /// # Examples
    ///
    /// Enable query config.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .query_config_enabled(true);
    /// ```
    pub fn query_config_enabled(mut self, query_config_enabled: bool) -> Self {
        self.query_config_enabled = Some(query_config_enabled);

        self
    }

    /// Set `deep_linking` to allow deep linking tags and operations.
    ///
    /// Deep linking will automatically scroll to and expand operation when Swagger UI is
    /// given corresponding url fragment. See more at
    /// [deep linking docs](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/deep-linking.md).
    ///
    /// Deep linking is enabled by default.
    ///
    /// # Examples
    ///
    /// Disable the deep linking.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .deep_linking(false);
    /// ```
    pub fn deep_linking(mut self, deep_linking: bool) -> Self {
        self.deep_linking = Some(deep_linking);

        self
    }

    /// Set `display_operation_id` to `true` to show operation id in the operations list.
    ///
    /// Default value is `false`.
    ///
    /// # Examples
    ///
    /// Allow operation id to be shown.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .display_operation_id(true);
    /// ```
    pub fn display_operation_id(mut self, display_operation_id: bool) -> Self {
        self.display_operation_id = Some(display_operation_id);

        self
    }

    /// Set 'layout' to 'BaseLayout' to only use the base swagger layout without a search header.
    ///
    /// Default value is 'StandaloneLayout'.
    ///
    /// # Examples
    ///
    /// Configure Swagger to use Base Layout instead of Standalone
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .use_base_layout();
    /// ```
    pub fn use_base_layout(mut self) -> Self {
        self.layout = SWAGGER_BASE_LAYOUT;

        self
    }

    /// Add default models expansion depth.
    ///
    /// Setting this to `-1` will completely hide the models.
    ///
    /// # Examples
    ///
    /// Hide all the models.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .default_models_expand_depth(-1);
    /// ```
    pub fn default_models_expand_depth(mut self, default_models_expand_depth: isize) -> Self {
        self.default_models_expand_depth = Some(default_models_expand_depth);

        self
    }

    /// Add default model expansion depth for model on the example section.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .default_model_expand_depth(1);
    /// ```
    pub fn default_model_expand_depth(mut self, default_model_expand_depth: isize) -> Self {
        self.default_model_expand_depth = Some(default_model_expand_depth);

        self
    }

    /// Add `default_model_rendering` to set how models is show when API is first rendered.
    ///
    /// The user can always switch the rendering for given model by clicking the `Model` and `Example Value` links.
    ///
    /// * `example` Makes example rendered first by default.
    /// * `model` Makes model rendered first by default.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .default_model_rendering(r#"["example"*, "model"]"#);
    /// ```
    pub fn default_model_rendering<S: Into<String>>(mut self, default_model_rendering: S) -> Self {
        self.default_model_rendering = Some(default_model_rendering.into());

        self
    }

    /// Set to `true` to show request duration of _**'Try it out'**_ requests _**(in milliseconds)**_.
    ///
    /// Default value is `false`.
    ///
    /// # Examples
    /// Enable request duration of the _**'Try it out'**_ requests.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .display_request_duration(true);
    /// ```
    pub fn display_request_duration(mut self, display_request_duration: bool) -> Self {
        self.display_request_duration = Some(display_request_duration);

        self
    }

    /// Add `doc_expansion` to control default expansion for operations and tags.
    ///
    /// * `list` Will expand only tags.
    /// * `full` Will expand tags and operations.
    /// * `none` Will expand nothing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .doc_expansion(r#"["list"*, "full", "none"]"#);
    /// ```
    pub fn doc_expansion<S: Into<String>>(mut self, doc_expansion: S) -> Self {
        self.doc_expansion = Some(doc_expansion.into());

        self
    }

    /// Add `filter` to allow filtering of tagged operations.
    ///
    /// When enabled top bar will show and edit box that can be used to filter visible tagged operations.
    /// Filter behaves case sensitive manner and matches anywhere inside the tag.
    ///
    /// Default value is `false`.
    ///
    /// # Examples
    ///
    /// Enable filtering.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .filter(true);
    /// ```
    pub fn filter(mut self, filter: bool) -> Self {
        self.filter = Some(filter);

        self
    }

    /// Add `max_displayed_tags` to restrict shown tagged operations.
    ///
    /// By default all operations are shown.
    ///
    /// # Examples
    ///
    /// Display only 4 operations.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .max_displayed_tags(4);
    /// ```
    pub fn max_displayed_tags(mut self, max_displayed_tags: usize) -> Self {
        self.max_displayed_tags = Some(max_displayed_tags);

        self
    }

    /// Set `show_extensions` to adjust whether vendor extension _**`(x-)`**_ fields and values
    /// are shown for operations, parameters, responses and schemas.
    ///
    /// # Example
    ///
    /// Show vendor extensions.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .show_extensions(true);
    /// ```
    pub fn show_extensions(mut self, show_extensions: bool) -> Self {
        self.show_extensions = Some(show_extensions);

        self
    }

    /// Add `show_common_extensions` to define whether common extension
    /// _**`(pattern, maxLength, minLength, maximum, minimum)`**_ fields and values are shown
    /// for parameters.
    ///
    /// # Examples
    ///
    /// Show common extensions.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .show_common_extensions(true);
    /// ```
    pub fn show_common_extensions(mut self, show_common_extensions: bool) -> Self {
        self.show_common_extensions = Some(show_common_extensions);

        self
    }

    /// Add `try_it_out_enabled` to enable _**'Try it out'**_ section by default.
    ///
    /// Default value is `false`.
    ///
    /// # Examples
    ///
    /// Enable _**'Try it out'**_ section by default.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .try_it_out_enabled(true);
    /// ```
    pub fn try_it_out_enabled(mut self, try_it_out_enabled: bool) -> Self {
        self.try_it_out_enabled = Some(try_it_out_enabled);

        self
    }

    /// Set `request_snippets_enabled` to enable request snippets section.
    ///
    /// If disabled legacy curl snipped will be used.
    ///
    /// Default value is `false`.
    ///
    /// # Examples
    ///
    /// Enable request snippets section.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .request_snippets_enabled(true);
    /// ```
    pub fn request_snippets_enabled(mut self, request_snippets_enabled: bool) -> Self {
        self.request_snippets_enabled = Some(request_snippets_enabled);

        self
    }

    /// Add oauth redirect url.
    ///
    /// # Examples
    ///
    /// Add oauth redirect url.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .oauth2_redirect_url("http://my.oauth2.redirect.url");
    /// ```
    pub fn oauth2_redirect_url<S: Into<String>>(mut self, oauth2_redirect_url: S) -> Self {
        self.oauth2_redirect_url = Some(oauth2_redirect_url.into());

        self
    }

    /// Add `show_mutated_request` to use request returned from `requestInterceptor`
    /// to produce curl command in the UI. If set to `false` the request before `requestInterceptor`
    /// was applied will be used.
    ///
    /// # Examples
    ///
    /// Use request after `requestInterceptor` to produce the curl command.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .show_mutated_request(true);
    /// ```
    pub fn show_mutated_request(mut self, show_mutated_request: bool) -> Self {
        self.show_mutated_request = Some(show_mutated_request);

        self
    }

    /// Add supported http methods for _**'Try it out'**_ operation.
    ///
    /// _**'Try it out'**_ will be enabled based on the given list of http methods when
    /// the operation's http method is included within the list.
    /// By giving an empty list will disable _**'Try it out'**_ from all operations but it will
    /// **not** filter operations from the UI.
    ///
    /// By default all http operations are enabled.
    ///
    /// # Examples
    ///
    /// Set allowed http methods explicitly.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .supported_submit_methods(["get", "put", "post", "delete", "options", "head", "patch", "trace"]);
    /// ```
    ///
    /// Allow _**'Try it out'**_ for only GET operations.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .supported_submit_methods(["get"]);
    /// ```
    pub fn supported_submit_methods<I: IntoIterator<Item = S>, S: Into<String>>(
        mut self,
        supported_submit_methods: I,
    ) -> Self {
        self.supported_submit_methods = Some(
            supported_submit_methods
                .into_iter()
                .map(|method| method.into())
                .collect(),
        );

        self
    }

    /// Add validator url which is used to validate the Swagger spec.
    ///
    /// This can also be set to use locally deployed validator for example see
    /// [Validator Badge](https://github.com/swagger-api/validator-badge) for more details.
    ///
    /// By default swagger.io's online validator _**`(https://validator.swagger.io/validator)`**_ will be used.
    /// Setting this to `none` will disable the validator.
    ///
    /// # Examples
    ///
    /// Disable the validator.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .validator_url("none");
    /// ```
    pub fn validator_url<S: Into<String>>(mut self, validator_url: S) -> Self {
        self.validator_url = Some(validator_url.into());

        self
    }

    /// Set `with_credentials` to enable passing credentials to CORS requests send by browser as defined
    /// [fetch standards](https://fetch.spec.whatwg.org/#credentials).
    ///
    /// **Note!** that Swagger UI cannot currently set cookies cross-domain
    /// (see [swagger-js#1163](https://github.com/swagger-api/swagger-js/issues/1163)) -
    /// as a result, you will have to rely on browser-supplied cookies (which this setting enables sending)
    /// that Swagger UI cannot control.
    ///
    /// # Examples
    ///
    /// Enable passing credentials to CORS requests.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .with_credentials(true);
    /// ```
    pub fn with_credentials(mut self, with_credentials: bool) -> Self {
        self.with_credentials = Some(with_credentials);

        self
    }

    /// Set to `true` to enable authorizations to be persisted throughout browser refresh and close.
    ///
    /// Default value is `false`.
    ///
    ///
    /// # Examples
    ///
    /// Persists authorization throughout browser close and refresh.
    /// ```rust
    /// # use utoipa_swagger_ui::Config;
    /// let config = Config::new(["/api-docs/openapi.json"])
    ///     .persist_authorization(true);
    /// ```
    pub fn persist_authorization(mut self, persist_authorization: bool) -> Self {
        self.persist_authorization = Some(persist_authorization);

        self
    }
}

impl Default for Config<'_> {
    fn default() -> Self {
        Self {
            config_url: Default::default(),
            dom_id: Some("#swagger-ui".to_string()),
            url: Default::default(),
            urls_primary_name: Default::default(),
            urls: Default::default(),
            query_config_enabled: Default::default(),
            deep_linking: Some(true),
            display_operation_id: Default::default(),
            default_models_expand_depth: Default::default(),
            default_model_expand_depth: Default::default(),
            default_model_rendering: Default::default(),
            display_request_duration: Default::default(),
            doc_expansion: Default::default(),
            filter: Default::default(),
            max_displayed_tags: Default::default(),
            show_extensions: Default::default(),
            show_common_extensions: Default::default(),
            try_it_out_enabled: Default::default(),
            request_snippets_enabled: Default::default(),
            oauth2_redirect_url: Default::default(),
            show_mutated_request: Default::default(),
            supported_submit_methods: Default::default(),
            validator_url: Default::default(),
            with_credentials: Default::default(),
            persist_authorization: Default::default(),
            oauth: Default::default(),
            layout: SWAGGER_STANDALONE_LAYOUT,
        }
    }
}

impl<'a> From<&'a str> for Config<'a> {
    fn from(s: &'a str) -> Self {
        Self::new([s])
    }
}

impl From<String> for Config<'_> {
    fn from(s: String) -> Self {
        Self::new([s])
    }
}

/// Represents servable file of Swagger UI. This is used together with [`serve`] function
/// to serve Swagger UI files via web server.
#[non_exhaustive]
pub struct SwaggerFile<'a> {
    /// Content of the file as [`Cow`] [`slice`] of bytes.
    pub bytes: Cow<'a, [u8]>,
    /// Content type of the file e.g `"text/xml"`.
    pub content_type: String,
}

/// User friendly way to serve Swagger UI and its content via web server.
///
/// * **path** Should be the relative path to Swagger UI resource within the web server.
/// * **config** Swagger [`Config`] to use for the Swagger UI.
///
/// Typically this function is implemented _**within**_ handler what serves the Swagger UI. Handler itself must
/// match to user defined path that points to the root of the Swagger UI and match everything relatively
/// from the root of the Swagger UI _**(tail path)**_. The relative path from root of the Swagger UI
/// is used to serve [`SwaggerFile`]s. If Swagger UI is served from path `/swagger-ui/` then the `tail`
/// is everything under the `/swagger-ui/` prefix.
///
/// _There are also implementations in [examples of utoipa repository][examples]._
///
/// [examples]: https://github.com/juhaku/utoipa/tree/master/examples
///
/// # Examples
///
/// _**Reference implementation with `actix-web`.**_
/// ```rust
/// # use actix_web::HttpResponse;
/// # use std::sync::Arc;
/// # use utoipa_swagger_ui::Config;
/// // The config should be created in main function or in initialization before
/// // creation of the handler which will handle serving the Swagger UI.
/// let config = Arc::new(Config::from("/api-doc.json"));
///
/// // This "/" is for demonstrative purposes only. The actual path should point to
/// // file within Swagger UI. In real implementation this is the `tail` path from root of the
/// // Swagger UI to the file served.
/// let tail_path = "/";
///
/// fn get_swagger_ui(tail_path: String, config: Arc<Config>) -> HttpResponse {
///   match utoipa_swagger_ui::serve(tail_path.as_ref(), config) {
///       Ok(swagger_file) => swagger_file
///           .map(|file| {
///               HttpResponse::Ok()
///                   .content_type(file.content_type)
///                   .body(file.bytes.to_vec())
///           })
///           .unwrap_or_else(|| HttpResponse::NotFound().finish()),
///       Err(error) => HttpResponse::InternalServerError().body(error.to_string()),
///   }
/// }
/// ```
pub fn serve<'a>(
    path: &str,
    config: Arc<Config<'a>>,
) -> Result<Option<SwaggerFile<'a>>, Box<dyn Error>> {
    let mut file_path = path;

    if file_path.is_empty() || file_path == "/" {
        file_path = "index.html";
    }

    if let Some(file) = SwaggerUiDist::get(file_path) {
        let mut bytes = file.data;

        if file_path == "swagger-initializer.js" {
            let mut file = match String::from_utf8(bytes.to_vec()) {
                Ok(file) => file,
                Err(error) => return Err(Box::new(error)),
            };

            file = format_config(config.as_ref(), file)?;

            if let Some(oauth) = &config.oauth {
                match oauth::format_swagger_config(oauth, file) {
                    Ok(oauth_file) => file = oauth_file,
                    Err(error) => return Err(Box::new(error)),
                }
            }

            bytes = Cow::Owned(file.as_bytes().to_vec())
        };

        Ok(Some(SwaggerFile {
            bytes,
            content_type: mime_guess::from_path(file_path)
                .first_or_octet_stream()
                .to_string(),
        }))
    } else {
        Ok(None)
    }
}

#[inline]
fn format_config(config: &Config, file: String) -> Result<String, Box<dyn Error>> {
    let config_json = match serde_json::to_string_pretty(&config) {
        Ok(config) => config,
        Err(error) => return Err(Box::new(error)),
    };

    // Replace {{config}} with pretty config json and remove the curly brackets `{ }` from beginning and the end.
    Ok(file.replace("{{config}}", &config_json[2..&config_json.len() - 2]))
}

#[cfg(test)]
mod tests {
    use similar::TextDiff;

    use super::*;

    fn assert_diff_equal(expected: &str, new: &str) {
        let diff = TextDiff::from_lines(expected, new);

        assert_eq!(expected, new, "\nDifference:\n{}", diff.unified_diff());
    }

    const TEST_INITIAL_CONFIG: &str = r#"
window.ui = SwaggerUIBundle({
  {{config}},
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ],
});"#;

    #[test]
    fn format_swagger_config_json_single_url() {
        let formatted_config = match format_config(
            &Config::new(["/api-docs/openapi1.json"]),
            String::from(TEST_INITIAL_CONFIG),
        ) {
            Ok(file) => file,
            Err(error) => panic!("{error}"),
        };

        const EXPECTED: &str = r###"
window.ui = SwaggerUIBundle({
    "dom_id": "#swagger-ui",
  "url": "/api-docs/openapi1.json",
  "deepLinking": true,
  "layout": "StandaloneLayout",
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ],
});"###;

        assert_diff_equal(EXPECTED, &formatted_config)
    }

    #[test]
    fn format_swagger_config_json_single_url_with_name() {
        let formatted_config = match format_config(
            &Config::new([Url::new("api-doc1", "/api-docs/openapi1.json")]),
            String::from(TEST_INITIAL_CONFIG),
        ) {
            Ok(file) => file,
            Err(error) => panic!("{error}"),
        };

        const EXPECTED: &str = r###"
window.ui = SwaggerUIBundle({
    "dom_id": "#swagger-ui",
  "urls": [
    {
      "name": "api-doc1",
      "url": "/api-docs/openapi1.json"
    }
  ],
  "deepLinking": true,
  "layout": "StandaloneLayout",
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ],
});"###;

        assert_diff_equal(EXPECTED, &formatted_config);
    }

    #[test]
    fn format_swagger_config_json_single_url_primary() {
        let formatted_config = match format_config(
            &Config::new([Url::with_primary(
                "api-doc1",
                "/api-docs/openapi1.json",
                true,
            )]),
            String::from(TEST_INITIAL_CONFIG),
        ) {
            Ok(file) => file,
            Err(error) => panic!("{error}"),
        };

        const EXPECTED: &str = r###"
window.ui = SwaggerUIBundle({
    "dom_id": "#swagger-ui",
  "urls.primaryName": "api-doc1",
  "urls": [
    {
      "name": "api-doc1",
      "url": "/api-docs/openapi1.json"
    }
  ],
  "deepLinking": true,
  "layout": "StandaloneLayout",
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ],
});"###;

        assert_diff_equal(EXPECTED, &formatted_config);
    }

    #[test]
    fn format_swagger_config_multiple_urls_with_primary() {
        let formatted_config = match format_config(
            &Config::new([
                Url::with_primary("api-doc1", "/api-docs/openapi1.json", true),
                Url::new("api-doc2", "/api-docs/openapi2.json"),
            ]),
            String::from(TEST_INITIAL_CONFIG),
        ) {
            Ok(file) => file,
            Err(error) => panic!("{error}"),
        };

        const EXPECTED: &str = r###"
window.ui = SwaggerUIBundle({
    "dom_id": "#swagger-ui",
  "urls.primaryName": "api-doc1",
  "urls": [
    {
      "name": "api-doc1",
      "url": "/api-docs/openapi1.json"
    },
    {
      "name": "api-doc2",
      "url": "/api-docs/openapi2.json"
    }
  ],
  "deepLinking": true,
  "layout": "StandaloneLayout",
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ],
});"###;

        assert_diff_equal(EXPECTED, &formatted_config);
    }

    #[test]
    fn format_swagger_config_multiple_urls() {
        let formatted_config = match format_config(
            &Config::new(["/api-docs/openapi1.json", "/api-docs/openapi2.json"]),
            String::from(TEST_INITIAL_CONFIG),
        ) {
            Ok(file) => file,
            Err(error) => panic!("{error}"),
        };

        const EXPECTED: &str = r###"
window.ui = SwaggerUIBundle({
    "dom_id": "#swagger-ui",
  "urls": [
    {
      "name": "/api-docs/openapi1.json",
      "url": "/api-docs/openapi1.json"
    },
    {
      "name": "/api-docs/openapi2.json",
      "url": "/api-docs/openapi2.json"
    }
  ],
  "deepLinking": true,
  "layout": "StandaloneLayout",
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ],
});"###;

        assert_diff_equal(EXPECTED, &formatted_config);
    }

    #[test]
    fn format_swagger_config_with_multiple_fields() {
        let formatted_config = match format_config(
            &Config::new(["/api-docs/openapi1.json"])
                .deep_linking(false)
                .dom_id("#another-el")
                .default_model_expand_depth(-1)
                .default_model_rendering(r#"["example"*]"#)
                .default_models_expand_depth(1)
                .display_operation_id(true)
                .display_request_duration(true)
                .filter(true)
                .use_base_layout()
                .doc_expansion(r#"["list"*]"#)
                .max_displayed_tags(1)
                .oauth2_redirect_url("http://auth")
                .persist_authorization(true)
                .query_config_enabled(true)
                .request_snippets_enabled(true)
                .show_common_extensions(true)
                .show_extensions(true)
                .show_mutated_request(true)
                .supported_submit_methods(["get"])
                .try_it_out_enabled(true)
                .validator_url("none")
                .with_credentials(true),
            String::from(TEST_INITIAL_CONFIG),
        ) {
            Ok(file) => file,
            Err(error) => panic!("{error}"),
        };

        const EXPECTED: &str = r###"
window.ui = SwaggerUIBundle({
    "dom_id": "#another-el",
  "url": "/api-docs/openapi1.json",
  "queryConfigEnabled": true,
  "deepLinking": false,
  "displayOperationId": true,
  "defaultModelsExpandDepth": 1,
  "defaultModelExpandDepth": -1,
  "defaultModelRendering": "[\"example\"*]",
  "displayRequestDuration": true,
  "docExpansion": "[\"list\"*]",
  "filter": true,
  "maxDisplayedTags": 1,
  "showExtensions": true,
  "showCommonExtensions": true,
  "tryItOutEnabled": true,
  "requestSnippetsEnabled": true,
  "oauth2RedirectUrl": "http://auth",
  "showMutatedRequest": true,
  "supportedSubmitMethods": [
    "get"
  ],
  "validatorUrl": "none",
  "withCredentials": true,
  "persistAuthorization": true,
  "layout": "BaseLayout",
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ],
});"###;

        assert_diff_equal(EXPECTED, &formatted_config);
    }
}