Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
build(rust): make crates compile the same on every machine (#8284)
Wolf Mermelstein8452fb9bd466
diff --git a/Cargo.lock b/Cargo.lockindex 2d20502121..13f7661f82 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6416,6 +6416,27 @@ dependencies = ["zeroize",]+[[package]]+name = "dirs"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"+dependencies = [+ "dirs-sys",+]++[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users",+ "windows-sys 0.59.0",+]+[[package]]name = "dispatch2"version = "0.3.1"@@ -10405,7 +10426,6 @@ dependencies = ["qoi","ravif","rayon",- "rgb","tiff","zune-core","zune-jpeg",@@ -11598,9 +11618,9 @@ dependencies = [[[package]]name = "libz-sys"-version = "1.1.29"+version = "1.1.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9"+checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2"dependencies = ["cc","libc",@@ -14435,6 +14455,12 @@ dependencies = ["tokio-stream",]+[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]name = "opus-pure"version = "0.2.1"@@ -16339,6 +16365,16 @@ dependencies = ["bitflags 2.11.1",]+[[package]]+name = "redox_users"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"+dependencies = [+ "libredox",+ "thiserror 2.0.18",+]+[[package]]name = "ref-cast"version = "1.0.25"@@ -16979,6 +17015,7 @@ dependencies = ["proc-macro2","quote","rust-embed-utils",+ "shellexpand","syn 2.0.117","walkdir",]@@ -18223,6 +18260,15 @@ version = "1.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"+[[package]]+name = "shellexpand"+version = "3.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8"+dependencies = [+ "dirs",+]+[[package]]name = "shlex"version = "1.3.0"@@ -19808,7 +19854,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand 2.4.1",- "getrandom 0.3.4",+ "getrandom 0.4.2","once_cell","rustix 1.1.4","windows-sys 0.52.0",@@ -21189,8 +21235,6 @@ dependencies = [[[package]]name = "utoipa-swagger-ui"version = "9.0.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d047458f1b5b65237c2f6dc6db136945667f40a7668627b3490b9513a3d43a55"dependencies = ["axum","base64 0.22.1",@@ -22753,7 +22797,6 @@ dependencies = ["num-complex","num-integer","num-iter",- "num-rational","num-traits","objc2","objc2-foundation",@@ -22785,6 +22828,7 @@ dependencies = ["rig-core","rmcp","rsa",+ "rust-embed-utils","rustc-hash 2.1.2","rustix 1.1.4","rustls",diff --git a/Cargo.toml b/Cargo.tomlindex 788625eff0..8ce2b046aa 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,5 +1,7 @@[workspace]resolver = "2"+# Patched third-party crates ([patch.crates-io]), not workspace members.+exclude = ["vendor"]members = ["crates/access_requests",@@ -287,7 +289,15 @@ http-body-util = "0.1.2"httpdate = "1"hyper = "1"hyper-util = { version = "0.1", features = ["tokio"] }-image = "0.25"+# image's default formats minus "avif": its AVIF encoder pulls in rav1e, whose+# build script records whether it runs in CI, so rav1e and everything above it+# (attachment, image_optimizer, ...) compiled differently on developer machines+# and in CI. Nothing here decodes AVIF (that needs "avif-native"), so AVIF+# inputs already failed before reaching the encoder.+image = { version = "0.25", default-features = false, features = [+ "rayon", "bmp", "dds", "exr", "ff", "gif", "hdr", "ico", "jpeg", "png", "pnm",+ "qoi", "tga", "tiff", "webp",+] }image-webp = "0.2"indexmap = "2"infer = "0.19.0"@@ -446,7 +456,10 @@ utoipa = { version = "5.4.0", features = ["repr","uuid",] }-utoipa-swagger-ui = { version = "9", features = ["axum", "vendored"] }+# debug-embed: debug builds embed Swagger UI instead of compiling in the+# absolute build-directory path they would read it from at runtime, which made+# the crate and every service above it differ per checkout.+utoipa-swagger-ui = { version = "9", features = ["axum", "vendored", "debug-embed"] }uuid = { version = "1.15.1", features = ["fast-rng", "serde", "v4", "v5", "v7"] }webpki-roots = "1.0.10"wiremock = "0.6.5"@@ -502,6 +515,8 @@ subtle = "2.6.1"[patch.crates-io]# Only replaces tungstenite 0.27 (GraphQL subscriptions); 0.28/0.29 stay upstream.tungstenite = { git = "https://github.com/signalapp/tungstenite-rs", rev = "a1837ccfe96b6895a57352d7f0112e4557516c27" }+# Writes a checkout-independent embed folder; see vendor/utoipa-swagger-ui/README-MACRO.md.+utoipa-swagger-ui = { path = "vendor/utoipa-swagger-ui" }# cache-turso's storage tests load thousands of rows into the embedded SQL engine# to assert VM step budgets. Unoptimized, the engine made them the slowest testsdiff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rsindex 3302454649..a2753e74b4 100644--- a/crates/cursor_cloud_agents/src/testing.rs+++ b/crates/cursor_cloud_agents/src/testing.rs@@ -16,7 +16,10 @@ use futures::Stream;use std::sync::{Arc, Mutex};use tokio::sync::mpsc;-/// The recorded-SSE corpus directory.+/// The recorded-SSE corpus directory. Test-only: `env!("CARGO_MANIFEST_DIR")`+/// in the library would compile this checkout's absolute path into it, so it+/// (and every crate above it) would never share a kache entry across machines.+#[cfg(test)]#[must_use]pub fn fixtures_dir() -> std::path::PathBuf {std::path::Path::new(env!("CARGO_MANIFEST_DIR"))@@ -30,6 +33,7 @@ pub fn fixtures_dir() -> std::path::PathBuf {/// # Panics/// On an unreadable file — fixtures are part of the test suite, and a broken/// one should fail loudly.+#[cfg(test)]#[must_use]pub fn fixture_sse(name: &str) -> String {let path = fixtures_dir().join(name);@@ -38,6 +42,7 @@ pub fn fixture_sse(name: &str) -> String {}/// Load original complete SSE records without decoding their payloads.+#[cfg(test)]#[must_use]pub fn fixture_records(name: &str) -> Vec<NativeRecord> {crate::replay::records(&fixture_sse(name))diff --git a/crates/macro_env_var/src/lib.rs b/crates/macro_env_var/src/lib.rsindex 8fdf10855a..ae3321af3b 100644--- a/crates/macro_env_var/src/lib.rs+++ b/crates/macro_env_var/src/lib.rs@@ -217,15 +217,6 @@ macro_rules! env_var {}}- #[doc = "This is a const fn which will panic at compile time if the environment variable is not found"]- #[allow(dead_code)]- $v const fn new_comptime() -> Self {- let val = std::option_env!($crate::paste::paste! { stringify!([<$n:snake:upper>]) });- $crate::paste::paste! {- Self::Comptime(val.expect(concat!("Failed to find the ", stringify!([<$n:snake:upper>]), " variable in environment at compile time")))- }- }-#[doc = "Function used for testing purposes. Allows the caller to create a new Self via a static str"]#[cfg(test)]@@ -338,16 +329,6 @@ macro_rules! env_var {)*}}-- #[doc = "Create a new instance of self with all the internal env vals set at compile time. Will fail to compile if any value is not set at compile time"]- #[allow(dead_code)]- $v const fn new_comptime() -> Self {- Self {- $(- [<$field_name:snake>]: $field_name::new_comptime(),- )*- }- }}}};@@ -489,15 +470,6 @@ macro_rules! maybe_env_var {Some(Self::Runtime(std::sync::Arc::from(res)))}- #[doc = "Returns the value at compile time if present, otherwise `None`"]- #[allow(dead_code)]- $v const fn new_comptime() -> Option<Self> {- match std::option_env!($crate::paste::paste! { stringify!([<$n:snake:upper>]) }) {- Some(val) => Some(Self::Comptime(val)),- None => None,- }- }-#[doc = "Function used for testing purposes. Allows the caller to create a new Self via a static str"]#[cfg(test)]#[allow(dead_code)]@@ -680,16 +652,6 @@ macro_rules! maybe_env_var {)*}}-- #[doc = "Create a new instance of self with all the internal env vals set at compile time. Each field is `Option<T>`."]- #[allow(dead_code)]- $v const fn new_comptime() -> Self {- Self {- $(- [<$field_name:snake>]: $field_name::new_comptime(),- )*- }- }}}};diff --git a/crates/pptx_engine/src/bin/pptx_corpus/corpus.rs b/crates/pptx_engine/src/bin/pptx_corpus/corpus.rsindex 8c296b2f52..d87bdc310e 100644--- a/crates/pptx_engine/src/bin/pptx_corpus/corpus.rs+++ b/crates/pptx_engine/src/bin/pptx_corpus/corpus.rs@@ -1,8 +1,17 @@//! Corpus helpers for the CLI: the shared corpus types and a parallel map.pub use pptx_engine::fidelity::corpus::*;+use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicUsize, Ordering};+/// The default corpus directory (inside the crate). Lives in the binary, not+/// the library: `env!("CARGO_MANIFEST_DIR")` compiles this checkout's absolute+/// path in, and a library carrying it never shares a kache entry across+/// machines.+pub fn default_corpus() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus")+}+/// Maps `f` over `items` on `jobs` threads, keeping order.pub fn par_map<T: Sync, R: Send>(items: &[T], jobs: usize, f: impl Fn(&T) -> R + Sync) -> Vec<R> {let next = AtomicUsize::new(0);diff --git a/crates/pptx_engine/src/fidelity/corpus.rs b/crates/pptx_engine/src/fidelity/corpus.rsindex 1ad7c57eea..6798851c7d 100644--- a/crates/pptx_engine/src/fidelity/corpus.rs+++ b/crates/pptx_engine/src/fidelity/corpus.rs@@ -5,11 +5,6 @@ use serde::{Deserialize, Serialize};use std::collections::BTreeMap;use std::path::{Path, PathBuf};-/// The default corpus directory (inside the crate).-pub fn default_corpus() -> PathBuf {- Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus")-}-/// A deck in the corpus.#[derive(Clone, Debug)]pub struct Deck {diff --git a/crates/pptx_engine/tests/corpus.rs b/crates/pptx_engine/tests/corpus.rsindex 5c2028d9ad..d330c7e52c 100644--- a/crates/pptx_engine/tests/corpus.rs+++ b/crates/pptx_engine/tests/corpus.rs@@ -9,15 +9,19 @@use pptx_engine::Presentation;use pptx_engine::collab::Entries;use pptx_engine::fidelity::corpus::{- Baseline, Deck, FINGERPRINT_WIDTH, default_corpus, discover, fingerprint_changed,- is_lfs_pointer,+ Baseline, Deck, FINGERPRINT_WIDTH, discover, fingerprint_changed, is_lfs_pointer,};use pptx_engine::fidelity::fingerprint;use pptx_engine::font::FontDb;use pptx_engine::opc::Package;+use std::path::{Path, PathBuf};use std::sync::Mutex;use std::sync::atomic::{AtomicUsize, Ordering};+fn default_corpus() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus")+}+/// The bundled fonts, read from the crate's `fonts/` directory.fn fonts() -> FontDb {let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fonts");diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex 6e869b1514..6a6abcb623 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -104,7 +104,6 @@ num-bigint = { version = "0.4" }num-complex = { version = "0.4" }num-integer = { version = "0.1", features = ["i128"] }num-iter = { version = "0.1", default-features = false, features = ["i128", "std"] }-num-rational = { version = "0.4", features = ["num-bigint-std"] }num-traits = { version = "0.2", features = ["i128", "libm"] }once_cell = { version = "1" }opentelemetry = { version = "0.31", default-features = false, features = ["internal-logs", "logs", "metrics", "testing"] }@@ -129,6 +128,7 @@ rig-agent = { version = "0.41", features = ["test-utils"] }rig-core = { version = "0.41", features = ["test-utils"] }rmcp = { version = "1", features = ["auth", "client", "transport-streamable-http-client-reqwest", "transport-streamable-http-server"] }rsa = { version = "0.9", features = ["getrandom", "sha1"] }+rust-embed-utils = { version = "8", default-features = false, features = ["debug-embed"] }rustc-hash = { version = "2" }rustls = { version = "0.23", default-features = false, features = ["logging", "prefer-post-quantum", "ring", "std", "tls12"] }rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "ring", "std"] }@@ -266,7 +266,6 @@ num-bigint = { version = "0.4" }num-complex = { version = "0.4" }num-integer = { version = "0.1", features = ["i128"] }num-iter = { version = "0.1", default-features = false, features = ["i128", "std"] }-num-rational = { version = "0.4", features = ["num-bigint-std"] }num-traits = { version = "0.2", features = ["i128", "libm"] }once_cell = { version = "1" }opentelemetry = { version = "0.31", default-features = false, features = ["internal-logs", "logs", "metrics", "testing"] }@@ -293,6 +292,7 @@ rig-agent = { version = "0.41", features = ["test-utils"] }rig-core = { version = "0.41", features = ["test-utils"] }rmcp = { version = "1", features = ["auth", "client", "transport-streamable-http-client-reqwest", "transport-streamable-http-server"] }rsa = { version = "0.9", features = ["getrandom", "sha1"] }+rust-embed-utils = { version = "8", default-features = false, features = ["debug-embed"] }rustc-hash = { version = "2" }rustls = { version = "0.23", default-features = false, features = ["logging", "prefer-post-quantum", "ring", "std", "tls12"] }rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "ring", "std"] }diff --git a/nix/cloud-storage.nix b/nix/cloud-storage.nixindex 1b8e2f3b0b..956fe40355 100644--- a/nix/cloud-storage.nix+++ b/nix/cloud-storage.nix@@ -116,9 +116,10 @@};# Workspace-root files that crates read across crate boundaries: the- # .sqlx offline cache (sqlx macros resolve it from the workspace root)- # and shared assets under static_assets/ (include_bytes!-ed from workspace- # crates). Included in every pruned source, so a+ # .sqlx offline cache (sqlx macros resolve it from the workspace root),+ # shared assets under static_assets/ (include_bytes!-ed from workspace+ # crates), and the [patch.crates-io] crates under vendor/, which+ # mkDummySrc would otherwise stub out. Included in every pruned source, so a# sqlx prepare still invalidates all leaves — coarser than ideal, but# the query-to-crate mapping is not recoverable from the file names.rootDepsSrc = pkgs.lib.cleanSourceWith {@@ -137,6 +138,9 @@|| (pkgs.lib.hasPrefix ".sqlx/" rel)|| (rel == "static_assets")|| (pkgs.lib.hasPrefix "static_assets/" rel)+ || (rel == "vendor")+ || (rel == "vendor/utoipa-swagger-ui")+ || (pkgs.lib.hasPrefix "vendor/utoipa-swagger-ui/" rel)|| (type == "regular"&& !(pkgs.lib.hasInfix "/" rel)@@ -1001,6 +1005,13 @@donetouch $out'';+ # Deploy builds compile [patch.crates-io] crates from the pruned+ # source, so their real code (not mkDummySrc's stubs) must be there.+ pruned-deploy-src-vendored-patches = pkgs.runCommand "cloud-storage-pruned-vendored-patches" { } ''+ grep -q "fn write_embed_code" \+ ${prunedDeploySrc "service-agent-harness-service" "agent_harness_service"}/vendor/utoipa-swagger-ui/build.rs+ touch $out+ '';fmt = craneLib.cargoFmt {inherit src;pname = "cloud-storage";diff --git a/vendor/utoipa-swagger-ui/CHANGELOG.md b/vendor/utoipa-swagger-ui/CHANGELOG.mdnew file mode 100644index 0000000000..26c6337b44--- /dev/null+++ b/vendor/utoipa-swagger-ui/CHANGELOG.md@@ -0,0 +1,189 @@+# Changelog - utoipa-swagger-ui++## 9.0.2 - Sun 25 May 2025++### Fixed++* Avoid cloning ApiDoc on every request for axum (https://github.com/juhaku/utoipa/pull/1393)++### Changed++* Update build dependency `zip` to v3.0 (https://github.com/juhaku/utoipa/pull/1391)++## 9.0.1 - Fri 4 Apr 2025++### Fixed++* fix(swagger-ui): fix build for breaking zip crate 2.6.0 change (#1363)+* fix: mismatch error from InvalidArchive (#1343)++## 9.0.0 - Thu 16 2025++### Changed++* Re-release 8.1.1 since axum upgrade is a breaking change (https://github.com/juhaku/utoipa/pull/1295)++## 8.1.1 - Jan 6 2025++### Changed++* Update axum to v0.8 (https://github.com/juhaku/utoipa/pull/1269)++### Fixed++* Add debug implementation for SwaggerUi (https://github.com/juhaku/utoipa/pull/1276)++## 8.1.0 - Dec 19 2024++### Added++* Add basic auth support for actix, rocket, axum (https://github.com/juhaku/utoipa/pull/1221)+* Add `cache` feature to cache swagger ui zip in build script (https://github.com/juhaku/utoipa/pull/1214)+* Allow disabling syntax highlighting (https://github.com/juhaku/utoipa/pull/1188)++## 8.0.3 - Oct 23 2024++### Fixed++* Fixed version number from docs main page++## 8.0.2 - Oct 21 2024++### Fixed++* Fix regression due to a985d8c1340f80ab69b2b0e5de799df98d567732 (https://github.com/juhaku/utoipa/pull/1155)++## 8.0.1 - Oct 16 2024++### Changed++* Update Swagger UI with latest release 5.7.14 (https://github.com/juhaku/utoipa/pull/1142)++## 8.0.0 - Oct 14 2024++### Added++* Add typos to CI (https://github.com/juhaku/utoipa/pull/1036)+* Add macros feature flag (https://github.com/juhaku/utoipa/pull/1015)++### Fixed++* Fix testing without explicit features (https://github.com/juhaku/utoipa/pull/1041)+* Fix building utoipa-axum & utoipa-swagger-ui (https://github.com/juhaku/utoipa/pull/1038)+* Fix utoipa-swagger-ui-vendored crates link++### Changed++* Remove commit commit id from changelogs (https://github.com/juhaku/utoipa/pull/1077)+* Update to rc version+* Always use system `curl` by default (https://github.com/juhaku/utoipa/pull/1045)+* Remove Redirect Causing Invalid URIs for Swagger UIs Server on / (https://github.com/juhaku/utoipa/pull/1043)+* Use fs::read to overwrite swagger UI contents (https://github.com/juhaku/utoipa/pull/1022)+* Update next beta versions+* Chore update docs and relax `url` version (https://github.com/juhaku/utoipa/pull/1001)+* Bump up versions (https://github.com/juhaku/utoipa/pull/998)+* Update versions+* Update utoipa-swagger-ui vendored dependency++## 7.1.0 - May 22 2024++### Added++* Add vendored Swagger UI for utoipa (https://github.com/juhaku/utoipa/pull/941)++### Changed++* Update utoipa-swagger-ui vendored dependency+* Update utoipa-swagger-ui-vendored version+* Include res for crates+* Update min Rust version and utoipa-swagger-ui version++## 7.0.3 - May 22 2024++### Fixed++* Fix docs.rs build++## 7.0.2 - May 21 2024++### Added++* Add missing windows check to utoipa-swagger-ui build.rs+* Add nest `OpenApi` support (https://github.com/juhaku/utoipa/pull/930)++### Changed++* Update `utoipa-swagger-ui` versions (https://github.com/juhaku/utoipa/pull/938)+* Enhance utoipa-swagger-ui build (https://github.com/juhaku/utoipa/pull/936)+* Use CARGO_HTTP_CAINFO CA file in build script if present (https://github.com/juhaku/utoipa/pull/935)+* Improve file:// url parsing (https://github.com/juhaku/utoipa/pull/925)+* Make SWAGGER_UI_DOWNLOAD_URL support file:// urls (https://github.com/juhaku/utoipa/pull/923)++## 7.0.1 - May 7 2024++### Changed++* Make reqwest to use rustls instead of openssl (https://github.com/juhaku/utoipa/pull/912)++## 7.0.0 - May 5 2024++### Added++* Add `default-features = false` to the optional axum dependency to avoid pulling in tokio in non-tokio environments (https://github.com/juhaku/utoipa/pull/874)++### Fixed++* Fix spelling (https://github.com/juhaku/utoipa/pull/846)++### Changed++* Seems like the zip_next is nowadays just zip again+* Update docs and next versions+* Update default Swagger UI version (https://github.com/juhaku/utoipa/pull/905)+* Replace `zip` with `zip_next` (https://github.com/juhaku/utoipa/pull/889)+* **`breaking`** Add flex to `utoipa-swagger-ui` build (https://github.com/juhaku/utoipa/pull/845)++## 6.0.0 - Jan 6 2024++### Changed++* Update next versions+* Allowing utoipa/utoipa-swagger-ui successfully build on Windows and made path proc macro attribute more permissive (https://github.com/juhaku/utoipa/pull/830)+* Update Rocket v0.5 (https://github.com/juhaku/utoipa/pull/825)+* Generate embed code instead of using interpolation (https://github.com/juhaku/utoipa/pull/828)+* Misc document improvements (https://github.com/juhaku/utoipa/pull/814)++## 5.0.0 - Nov 28 2023++### Changed++* Update next versions+* Axum 0.7 bindings (https://github.com/juhaku/utoipa/pull/807)++## 4.0.0 - Oct 7 2023++### Changed++* Update utoipa versions **min. utoipa `4`**++## 3.1.6 - Oct 7 2023++### Added++* Add rapidoc support (https://github.com/juhaku/utoipa/pull/723)++### Fixed++* Fix: panic on missing trailing / in rocket environment (https://github.com/juhaku/utoipa/pull/645) (#757)++### Changed++* Update next versions and dependencies++## 3.1.5 - Aug 6 2023++### Changed++* Update utoipa-swagger-ui version+* Update Swagger UI to 5.3.1+* Update README.md docsdiff --git a/vendor/utoipa-swagger-ui/Cargo.toml b/vendor/utoipa-swagger-ui/Cargo.tomlnew file mode 100644index 0000000000..dd67481492--- /dev/null+++ b/vendor/utoipa-swagger-ui/Cargo.toml@@ -0,0 +1,157 @@+# Vendored from crates.io utoipa-swagger-ui 9.0.2 (macro: see README-MACRO.md).+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2021"+rust-version = "1.75"+name = "utoipa-swagger-ui"+version = "9.0.2"+authors = ["Juha Kukkonen"]+build = "build.rs"+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "Swagger UI for utoipa"+readme = "README.md"+keywords = [+ "swagger-ui",+ "openapi",+ "documentation",+]+categories = ["web-programming"]+license = "MIT OR Apache-2.0"+repository = "https://github.com/juhaku/utoipa"++[package.metadata.docs.rs]+features = [+ "actix-web",+ "axum",+ "rocket",+ "vendored",+ "cache",+]+no-default-features = true+rustdoc-args = [+ "--cfg",+ "doc_cfg",+]++[features]+cache = [+ "dep:dirs",+ "dep:sha2",+]+debug = []+debug-embed = ["rust-embed/debug-embed"]+default = ["url"]+reqwest = ["dep:reqwest"]+url = ["dep:url"]+vendored = ["dep:utoipa-swagger-ui-vendored"]++[lib]+name = "utoipa_swagger_ui"+path = "src/lib.rs"++[dependencies.actix-web]+version = "4"+features = ["macros"]+optional = true+default-features = false++[dependencies.axum]+version = "0.8.0"+features = ["json"]+optional = true+default-features = false++[dependencies.base64]+version = "0.22.1"++[dependencies.mime_guess]+version = "2.0"++[dependencies.rocket]+version = "0.5"+features = ["json"]+optional = true++[dependencies.rust-embed]+version = "8"+features = ["interpolate-folder-path"]++[dependencies.serde]+version = "1.0"+features = [+ "derive",+ "rc",+]++[dependencies.serde_json]+version = "1.0"++[dependencies.utoipa]+version = "5.0.0"+features = ["macros"]+default-features = false++[dev-dependencies.http]+version = "1.2"++[dev-dependencies.similar]+version = "2.5"++[dev-dependencies.tokio]+version = "1"+features = ["macros"]++[dev-dependencies.tower]+version = "0.5"++[build-dependencies.dirs]+version = "6.0"+optional = true++[build-dependencies.regex]+version = "1.7"++[build-dependencies.reqwest]+version = "0.12"+features = [+ "blocking",+ "rustls-tls",+]+optional = true+default-features = false++[build-dependencies.sha2]+version = "0.10"+optional = true++[build-dependencies.url]+version = "2"+optional = true++[build-dependencies.utoipa-swagger-ui-vendored]+version = "0.1"+optional = true++[build-dependencies.zip]+version = "3.0"+features = ["deflate"]+default-features = false++[lints.rust.unexpected_cfgs]+level = "warn"+priority = 0+check-cfg = ["cfg(doc_cfg)"]diff --git a/vendor/utoipa-swagger-ui/LICENSE-APACHE b/vendor/utoipa-swagger-ui/LICENSE-APACHEnew file mode 100644index 0000000000..f49a4e16e6--- /dev/null+++ b/vendor/utoipa-swagger-ui/LICENSE-APACHE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.\ No newline at end of filediff --git a/vendor/utoipa-swagger-ui/LICENSE-MIT b/vendor/utoipa-swagger-ui/LICENSE-MITnew file mode 100644index 0000000000..2ccf0a699a--- /dev/null+++ b/vendor/utoipa-swagger-ui/LICENSE-MIT@@ -0,0 +1,22 @@+The MIT License (MIT)++Copyright © 2021+++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the “Software”), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.diff --git a/vendor/utoipa-swagger-ui/README-MACRO.md b/vendor/utoipa-swagger-ui/README-MACRO.mdnew file mode 100644index 0000000000..a5b4ac2922--- /dev/null+++ b/vendor/utoipa-swagger-ui/README-MACRO.md@@ -0,0 +1,14 @@+# utoipa-swagger-ui 9.0.2, patched++Upstream's build script writes `#[folder = "<absolute OUT_DIR>/…"]` into the+code it generates. rustc keeps that attribute literal in the crate's metadata,+and `--remap-path-prefix` does not rewrite string literals, so the compiled+crate differed in every checkout. Every service above it, and their test+binaries, then had a different kache key on each machine and in CI.++The functional change: the build script writes `$OUT_DIR/…` and rust-embed's+`interpolate-folder-path` expands it at compile time. Drop this copy once+upstream emits a relative or interpolated folder.++`Cargo.toml` also drops the author's email from `authors`, which the+repository's PII scan rejects.diff --git a/vendor/utoipa-swagger-ui/README.md b/vendor/utoipa-swagger-ui/README.mdnew file mode 100644index 0000000000..04352da793--- /dev/null+++ b/vendor/utoipa-swagger-ui/README.md@@ -0,0 +1,124 @@+# utoipa-swagger-ui++[](https://github.com/juhaku/utoipa/actions/workflows/build.yaml)+[](https://crates.io/crates/utoipa-swagger-ui)+[](https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/)+++This crate implements necessary boilerplate code to serve Swagger UI via web server. It+works as a bridge for serving the OpenAPI documentation created with+[utoipa](https://docs.rs/utoipa/) library in the Swagger UI.++**Currently implemented boilerplate for:**++* **actix-web** `version >= 4`+* **rocket** `version >=0.5`+* **axum** `version >=0.7`++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 a bit more manual implementation to be done. See+more details at [serve](https://docs.rs/utoipa-swagger-ui/latest/utoipa_swagger_ui/fn.serve.html) or+[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 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.+* **`reqwest`** Use `reqwest` for downloading Swagger UI according to the `SWAGGER_UI_DOWNLOAD_URL` environment+ variable. This is only enabled by default on _Windows_.+* **`url`** Enabled by default for parsing and encoding the download URL.+* **`vendored`** Enables vendored Swagger UI via `utoipa-swagger-ui-vendored` crate.+* **`cache`** Enables caching of the Swagger UI download in `utoipa-swagger-ui` during the build process.+* **`debug`**: Implement debug trait for SwaggerUi and other types.++## Install++Use only the raw types without any boilerplate implementation.++```toml+[dependencies]+utoipa-swagger-ui = "9"+```++Enable actix-web framework with Swagger UI you could define the dependency as follows.++```toml+[dependencies]+utoipa-swagger-ui = { version = "9", features = ["actix-web"] }+```++**Note!** Also remember that you already have defined `utoipa` dependency in your `Cargo.toml`++## Build Config++> [!IMPORTANT]+> _`utoipa-swagger-ui` crate will by default try to use system `curl` package for downloading the Swagger UI. It+> can optionally be downloaded with `reqwest` by enabling `reqwest` feature. Reqwest can be useful for platform+> independent builds however bringing quite a few unnecessary dependencies just to download a file.+> If the `SWAGGER_UI_DOWNLOAD_URL` is a file path then no downloading will happen._++> [!TIP]+> Use **`vendored`** feature flag to use vendored Swagger UI. This is especially useful for no network+> environments.++**The following configuration env variables are available at build time:**++ * `SWAGGER_UI_DOWNLOAD_URL`: Defines the url from where to download the swagger-ui zip file.++ * Current Swagger UI version: <https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.17.14.zip>+ * [All available Swagger UI versions](https://github.com/swagger-api/swagger-ui/tags)++ * `SWAGGER_UI_OVERWRITE_FOLDER`: Defines an _optional_ absolute path to a directory containing files+ to overwrite the Swagger UI files. Typically you might want to overwrite `index.html`.++## 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).++```rust+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).++```rust+#[rocket::launch]+fn rocket() -> Rocket<Build> {+ 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).++```rust+let app = Router::new()+ .merge(SwaggerUi::new("/swagger-ui")+ .url("/api-docs/openapi.json", ApiDoc::openapi()));+```++## License++Licensed under either of [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT) license at your option.++Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate+by you, shall be dual licensed, without any additional terms or conditions.diff --git a/vendor/utoipa-swagger-ui/build.rs b/vendor/utoipa-swagger-ui/build.rsnew file mode 100644index 0000000000..09d5799ca4--- /dev/null+++ b/vendor/utoipa-swagger-ui/build.rs@@ -0,0 +1,382 @@+use std::{+ env,+ error::Error,+ fs::{self, File},+ io::{self, Cursor, Read, Seek},+ path::{Path, PathBuf},+};++use regex::Regex;+use zip::{result::ZipError, ZipArchive};++/// the following env variables control the build process:+/// 1. SWAGGER_UI_DOWNLOAD_URL:+/// + the url from where to download the swagger-ui zip file if starts with http:// or https://+/// + the file path from where to copy the swagger-ui zip file if starts with file://+/// + default value is SWAGGER_UI_DOWNLOAD_URL_DEFAULT+/// + for other versions, check https://github.com/swagger-api/swagger-ui/tags+/// 2. SWAGGER_UI_OVERWRITE_FOLDER+/// + absolute path to a folder containing files to overwrite the default swagger-ui files++const SWAGGER_UI_DOWNLOAD_URL_DEFAULT: &str =+ "https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.17.14.zip";++const SWAGGER_UI_DOWNLOAD_URL: &str = "SWAGGER_UI_DOWNLOAD_URL";+const SWAGGER_UI_OVERWRITE_FOLDER: &str = "SWAGGER_UI_OVERWRITE_FOLDER";++#[cfg(feature = "cache")]+fn sha256(data: &[u8]) -> String {+ use sha2::{Digest, Sha256};+ let mut hasher = Sha256::new();+ hasher.update(data);+ let hash = hasher.finalize();+ format!("{:x}", hash).to_uppercase()+}++#[cfg(feature = "cache")]+fn get_cache_dir() -> Option<PathBuf> {+ dirs::cache_dir().map(|p| p.join("utoipa-swagger-ui"))+}++fn main() {+ let target_dir = env::var("OUT_DIR").unwrap();+ println!("OUT_DIR: {target_dir}");++ let url =+ env::var(SWAGGER_UI_DOWNLOAD_URL).unwrap_or(SWAGGER_UI_DOWNLOAD_URL_DEFAULT.to_string());++ println!("{SWAGGER_UI_DOWNLOAD_URL}: {url}");++ let mut swagger_zip = get_zip_archive(&url, &target_dir);+ let zip_top_level_folder = swagger_zip+ .extract_dist(&target_dir)+ .expect("should extract dist");+ println!("zip_top_level_folder: {:?}", zip_top_level_folder);++ replace_default_url_with_config(&target_dir, &zip_top_level_folder);++ write_embed_code(&target_dir, &zip_top_level_folder);++ let overwrite_folder =+ PathBuf::from(env::var(SWAGGER_UI_OVERWRITE_FOLDER).unwrap_or("overwrite".to_string()));++ if overwrite_folder.exists() {+ println!("{SWAGGER_UI_OVERWRITE_FOLDER}: {overwrite_folder:?}");++ for entry in fs::read_dir(overwrite_folder).unwrap() {+ let entry = entry.unwrap();+ let path_in = entry.path();+ println!("replacing file: {:?}", path_in.clone());+ overwrite_target_file(&target_dir, &zip_top_level_folder, path_in);+ }+ } else {+ println!("{SWAGGER_UI_OVERWRITE_FOLDER} not found: {overwrite_folder:?}");+ }+}++enum SwaggerZip {+ #[allow(unused)]+ Bytes(ZipArchive<Cursor<&'static [u8]>>),+ File(ZipArchive<File>),+}++impl SwaggerZip {+ fn extract_dist(&mut self, target_dir: &str) -> Result<String, ZipError> {+ // Inner function that's generic over the type of zip files+ fn extract<R: Seek + Read>(+ zip: &mut ZipArchive<R>,+ target_dir: &str,+ ) -> Result<String, ZipError> {+ let mut zip_top_level_folder = String::new();++ for index in 0..zip.len() {+ let mut file = zip.by_index(index)?;+ let filepath = file+ .enclosed_name()+ .ok_or(ZipError::InvalidArchive("invalid path file".into()))?;++ if index == 0 {+ zip_top_level_folder = filepath+ .iter()+ .take(1)+ .map(|x| x.to_str().unwrap_or_default())+ .collect::<String>();+ }++ let next_folder = filepath+ .iter()+ .skip(1)+ .take(1)+ .map(|x| x.to_str().unwrap_or_default())+ .collect::<String>();++ if next_folder == "dist" {+ let directory = [&target_dir].iter().collect::<PathBuf>();+ let out_path = directory.join(filepath);++ if file.name().ends_with('/') {+ fs::create_dir_all(&out_path)?;+ } else {+ if let Some(p) = out_path.parent() {+ if !p.exists() {+ fs::create_dir_all(p)?;+ }+ }+ let mut out_file = fs::File::create(&out_path)?;+ io::copy(&mut file, &mut out_file)?;+ }+ // Get and Set permissions+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Some(mode) = file.unix_mode() {+ fs::set_permissions(&out_path, fs::Permissions::from_mode(mode))?;+ }+ }+ }+ }++ Ok(zip_top_level_folder)+ }++ match self {+ Self::File(file) => extract(file, target_dir),+ Self::Bytes(bytes) => extract(bytes, target_dir),+ }+ }+}++fn get_zip_archive(url: &str, target_dir: &str) -> SwaggerZip {+ let zip_filename = url.split('/').last().unwrap().to_string();+ #[allow(unused_mut)]+ let mut zip_path = [target_dir, &zip_filename].iter().collect::<PathBuf>();++ if env::var("CARGO_FEATURE_VENDORED").is_ok() {+ #[cfg(not(feature = "vendored"))]+ unreachable!("Cannot get vendored Swagger UI without `vendored` flag");++ #[cfg(feature = "vendored")]+ {+ println!("using vendored Swagger UI");+ let vendred_bytes = utoipa_swagger_ui_vendored::SWAGGER_UI_VENDORED;+ let zip = ZipArchive::new(io::Cursor::new(vendred_bytes))+ .expect("failed to open vendored Swagger UI");+ SwaggerZip::Bytes(zip)+ }+ } else if url.starts_with("file:") {+ #[cfg(feature = "url")]+ let mut file_path = url::Url::parse(url).unwrap().to_file_path().unwrap();+ #[cfg(not(feature = "url"))]+ let mut file_path = {+ use std::str::FromStr;+ PathBuf::from_str(url).unwrap()+ };+ file_path = fs::canonicalize(file_path).expect("swagger ui download path should exists");++ // with file protocol utoipa swagger ui should compile when file changes+ println!("cargo:rerun-if-changed={:?}", file_path);++ println!("start copy to : {:?}", zip_path);+ fs::copy(file_path, zip_path.clone()).unwrap();++ let swagger_ui_zip =+ File::open([target_dir, &zip_filename].iter().collect::<PathBuf>()).unwrap();+ let zip = ZipArchive::new(swagger_ui_zip)+ .expect("failed to open file protocol copied Swagger UI");+ SwaggerZip::File(zip)+ } else if url.starts_with("http://") || url.starts_with("https://") {+ // with http protocol we update when the 'SWAGGER_UI_DOWNLOAD_URL' changes+ println!("cargo:rerun-if-env-changed={SWAGGER_UI_DOWNLOAD_URL}");++ // Update zip_path to point to the resolved cache directory+ #[cfg(feature = "cache")]+ {+ // Compute cache key based hashed URL + crate version+ let mut cache_key = String::new();+ cache_key.push_str(url);+ cache_key.push_str(&env::var("CARGO_PKG_VERSION").unwrap_or_default());+ let cache_key = sha256(cache_key.as_bytes());+ // Store the cache in the cache_key directory inside the OS's default cache folder+ let mut cache_dir = if let Some(dir) = get_cache_dir() {+ dir.join("swagger-ui").join(&cache_key)+ } else {+ println!("cargo:warning=Could not determine cache directory, using OUT_DIR");+ PathBuf::from(env::var("OUT_DIR").unwrap())+ };+ if fs::create_dir_all(&cache_dir).is_err() {+ cache_dir = env::var("OUT_DIR").unwrap().into();+ }+ zip_path = cache_dir.join(&zip_filename);+ }++ if zip_path.exists() {+ println!("using cached zip path from : {:?}", zip_path);+ } else {+ println!("start download to : {:?}", zip_path);+ download_file(url, zip_path.clone()).expect("failed to download Swagger UI");+ }+ let swagger_ui_zip = File::open(zip_path).unwrap();+ let zip = ZipArchive::new(swagger_ui_zip).expect("failed to open downloaded Swagger UI");+ SwaggerZip::File(zip)+ } else {+ panic!("`vendored` feature not enabled and invalid {SWAGGER_UI_DOWNLOAD_URL}: {url} -> must start with http:// | https:// | file:");+ }+}++fn replace_default_url_with_config(target_dir: &str, zip_top_level_folder: &str) {+ let regex = Regex::new(r#"(?ms)url:.*deep.*true,"#).unwrap();++ let path = [+ target_dir,+ zip_top_level_folder,+ "dist",+ "swagger-initializer.js",+ ]+ .iter()+ .collect::<PathBuf>();++ let mut swagger_initializer = fs::read_to_string(&path).unwrap();+ swagger_initializer = swagger_initializer.replace("layout: \"StandaloneLayout\"", "");++ let replaced_swagger_initializer = regex.replace(&swagger_initializer, "{{config}},");++ fs::write(&path, replaced_swagger_initializer.as_ref()).unwrap();+}++fn write_embed_code(target_dir: &str, zip_top_level_folder: &str) {+ let contents = format!(+ r#"+// This file is auto-generated during compilation, do not modify+#[derive(RustEmbed)]+#[folder = r"$OUT_DIR/{}/dist/"]+struct SwaggerUiDist;+"#,+ zip_top_level_folder+ );+ let path = [target_dir, "embed.rs"].iter().collect::<PathBuf>();+ fs::write(path, contents).unwrap();+}++fn download_file(url: &str, path: PathBuf) -> Result<(), Box<dyn Error>> {+ let reqwest_feature = env::var("CARGO_FEATURE_REQWEST");+ println!("reqwest feature: {reqwest_feature:?}");+ if reqwest_feature.is_ok() {+ #[cfg(feature = "reqwest")]+ download_file_reqwest(url, path)?;+ Ok(())+ } else {+ println!("trying to download using `curl` system package");+ download_file_curl(url, path.as_path())+ }+}++#[cfg(feature = "reqwest")]+fn download_file_reqwest(url: &str, path: PathBuf) -> Result<(), Box<dyn Error>> {+ let mut client_builder = reqwest::blocking::Client::builder();++ if let Ok(cainfo) = env::var("CARGO_HTTP_CAINFO") {+ match parse_ca_file(&cainfo) {+ Ok(cert) => client_builder = client_builder.add_root_certificate(cert),+ Err(e) => println!(+ "failed to load certificate from CARGO_HTTP_CAINFO `{cainfo}`, attempting to download without it. Error: {e:?}",+ ),+ }+ }++ let client = client_builder.build()?;++ let mut response = client.get(url).send()?;+ let mut file = File::create(path)?;+ io::copy(&mut response, &mut file)?;+ Ok(())+}++#[cfg(feature = "reqwest")]+fn parse_ca_file(path: &str) -> Result<reqwest::Certificate, Box<dyn Error>> {+ let mut buf = Vec::new();+ use io::Read;+ File::open(path)?.read_to_end(&mut buf)?;+ let cert = reqwest::Certificate::from_pem(&buf)?;+ Ok(cert)+}++fn download_file_curl<T: AsRef<Path>>(url: &str, target_dir: T) -> Result<(), Box<dyn Error>> {+ // Not using `CARGO_CFG_TARGET_OS` because of the possibility of cross-compilation.+ // When targeting `x86_64-pc-windows-gnu` on Linux for example, `cfg!()` in the+ // build script still reports `target_os = "linux"`, which is desirable.+ let curl_bin_name = if cfg!(target_os = "windows") {+ // powershell aliases `curl` to `Invoke-WebRequest`+ "curl.exe"+ } else {+ "curl"+ };++ #[cfg(feature = "url")]+ let url = url::Url::parse(url)?;++ let mut args = Vec::with_capacity(6);+ args.extend([+ "-sSL",+ "-o",+ target_dir+ .as_ref()+ .as_os_str()+ .to_str()+ .expect("target dir should be valid utf-8"),+ #[cfg(feature = "url")]+ {+ url.as_str()+ },+ #[cfg(not(feature = "url"))]+ url,+ ]);+ let cacert = env::var("CARGO_HTTP_CAINFO").unwrap_or_default();+ if !cacert.is_empty() {+ args.extend(["--cacert", &cacert]);+ }++ let download = std::process::Command::new(curl_bin_name)+ .args(args)+ .spawn()+ .and_then(|mut child| child.wait());++ Ok(download+ .and_then(|status| {+ if status.success() {+ Ok(())+ } else {+ Err(std::io::Error::new(+ io::ErrorKind::Other,+ format!("curl download file exited with error status: {status}"),+ ))+ }+ })+ .map_err(|error| {+ if error.kind() == io::ErrorKind::NotFound {+ io::Error::new(error.kind(), format!("`{curl_bin_name}` command not found"))+ } else {+ error+ }+ })+ .map_err(Box::new)?)+}++fn overwrite_target_file(target_dir: &str, swagger_ui_dist_zip: &str, path_in: PathBuf) {+ let filename = path_in.file_name().unwrap().to_str().unwrap();+ println!("overwrite file: {:?}", path_in.file_name().unwrap());++ let content = fs::read(path_in.clone());++ match content {+ Ok(content) => {+ let path = [target_dir, swagger_ui_dist_zip, "dist", filename]+ .iter()+ .collect::<PathBuf>();++ fs::write(path, content).unwrap();+ }+ Err(_) => {+ println!("cannot read content from file: {:?}", path_in);+ }+ }+}diff --git a/vendor/utoipa-swagger-ui/src/actix.rs b/vendor/utoipa-swagger-ui/src/actix.rsnew file mode 100644index 0000000000..eb56b64ca8--- /dev/null+++ b/vendor/utoipa-swagger-ui/src/actix.rs@@ -0,0 +1,135 @@+#![cfg(feature = "actix-web")]++use std::future;++use actix_web::{+ dev::{HttpServiceFactory, Service, ServiceResponse},+ guard::Get,+ web,+ web::Data,+ HttpResponse, Resource, Responder as ActixResponder,+};+use base64::Engine;++use crate::{ApiDoc, BasicAuth, Config, SwaggerUi};++impl HttpServiceFactory for SwaggerUi {+ fn register(self, config: &mut actix_web::dev::AppService) {+ let mut urls = self+ .urls+ .into_iter()+ .map(|(url, openapi)| {+ register_api_doc_url_resource(url.url.as_ref(), ApiDoc::Utoipa(openapi), config);+ url+ })+ .collect::<Vec<_>>();+ let external_api_docs = self.external_urls.into_iter().map(|(url, api_doc)| {+ register_api_doc_url_resource(url.url.as_ref(), ApiDoc::Value(api_doc), config);+ url+ });+ urls.extend(external_api_docs);++ let swagger_resource = Resource::new(self.path.as_ref())+ .guard(Get())+ .app_data(Data::new(if let Some(config) = self.config.clone() {+ if config.url.is_some() || !config.urls.is_empty() {+ config+ } else {+ config.configure_defaults(urls)+ }+ } else {+ Config::new(urls)+ }))+ .wrap_fn(move |req, srv| {+ if let Some(BasicAuth { username, password }) = self+ .config+ .as_ref()+ .and_then(|config| config.basic_auth.clone())+ {+ let encoded_credentials = format!(+ "Basic {}",+ base64::prelude::BASE64_STANDARD.encode(format!("{username}:{password}"))+ );+ if let Some(auth_header) = req.headers().get("Authorization") {+ if auth_header.to_str().unwrap() == encoded_credentials {+ return srv.call(req);+ }+ }+ return Box::pin(future::ready(Ok(ServiceResponse::new(+ req.request().clone(),+ HttpResponse::Unauthorized()+ .insert_header(("WWW-Authenticate", "Basic realm=\":\""))+ .finish(),+ ))));+ }+ srv.call(req)+ })+ .to(serve_swagger_ui);++ HttpServiceFactory::register(swagger_resource, config);+ }+}++fn register_api_doc_url_resource(url: &str, api: ApiDoc, config: &mut actix_web::dev::AppService) {+ async fn get_api_doc(api_doc: web::Data<ApiDoc>) -> impl ActixResponder {+ HttpResponse::Ok().json(api_doc.as_ref())+ }++ let url_resource = Resource::new(url)+ .guard(Get())+ .app_data(Data::new(api))+ .to(get_api_doc);+ HttpServiceFactory::register(url_resource, config);+}++async fn serve_swagger_ui(path: web::Path<String>, data: web::Data<Config<'_>>) -> HttpResponse {+ match super::serve(&path.into_inner(), data.into_inner()) {+ 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()),+ }+}++#[cfg(test)]+mod tests {+ use actix_web::{http::StatusCode, test, App};+ use base64::prelude::BASE64_STANDARD;++ use super::*;+ #[actix_web::test]+ async fn mount_onto_path_with_slash() {+ let swagger_ui = SwaggerUi::new("/swagger-ui/{_:.*}");++ let app = test::init_service(App::new().service(swagger_ui)).await;+ let req = test::TestRequest::get().uri("/swagger-ui/").to_request();+ let resp = test::call_service(&app, req).await;++ assert!(resp.status().is_success());+ }++ #[actix_web::test]+ async fn basic_auth() {+ let swagger_ui =+ SwaggerUi::new("/swagger-ui/{_:.*}").config(Config::default().basic_auth(BasicAuth {+ username: "admin".to_string(),+ password: "password".to_string(),+ }));++ let app = test::init_service(App::new().service(swagger_ui)).await;+ let req = test::TestRequest::get().uri("/swagger-ui/").to_request();+ let resp = test::call_service(&app, req).await;+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ let encoded_credentials = BASE64_STANDARD.encode("admin:password");+ let req = test::TestRequest::get()+ .uri("/swagger-ui/")+ .insert_header(("Authorization", format!("Basic {}", encoded_credentials)))+ .to_request();+ let resp = test::call_service(&app, req).await;+ assert!(resp.status().is_success());+ }+}diff --git a/vendor/utoipa-swagger-ui/src/axum.rs b/vendor/utoipa-swagger-ui/src/axum.rsnew file mode 100644index 0000000000..453044c551--- /dev/null+++ b/vendor/utoipa-swagger-ui/src/axum.rs@@ -0,0 +1,228 @@+#![cfg(feature = "axum")]++use std::sync::Arc;++use axum::{+ body::Body,+ extract::Path,+ http::{HeaderMap, Request, Response, StatusCode},+ middleware::{self, Next},+ response::IntoResponse,+ routing, Extension, Json, Router,+};+use base64::{prelude::BASE64_STANDARD, Engine};++use crate::{ApiDoc, BasicAuth, Config, SwaggerUi, Url};++impl<S> From<SwaggerUi> for Router<S>+where+ S: Clone + Send + Sync + 'static,+{+ fn from(swagger_ui: SwaggerUi) -> Self {+ let urls_capacity = swagger_ui.urls.len();+ let external_urls_capacity = swagger_ui.external_urls.len();++ let (router, urls) = swagger_ui.urls.into_iter().fold(+ (+ Router::<S>::new(),+ Vec::<Url>::with_capacity(urls_capacity + external_urls_capacity),+ ),+ |router_and_urls, (url, openapi)| {+ add_api_doc_to_urls(router_and_urls, (url, Arc::new(ApiDoc::Utoipa(openapi))))+ },+ );+ let (router, urls) = swagger_ui.external_urls.into_iter().fold(+ (router, urls),+ |router_and_urls, (url, openapi)| {+ add_api_doc_to_urls(router_and_urls, (url, Arc::new(ApiDoc::Value(openapi))))+ },+ );++ let config = if let Some(config) = swagger_ui.config {+ if config.url.is_some() || !config.urls.is_empty() {+ config+ } else {+ config.configure_defaults(urls)+ }+ } else {+ Config::new(urls)+ };++ let handler = routing::get(serve_swagger_ui).layer(Extension(Arc::new(config.clone())));+ let path: &str = swagger_ui.path.as_ref();++ let mut router = if path == "/" {+ router+ .route(path, handler.clone())+ .route(&format!("{}{{*rest}}", path), handler)+ } else {+ let path = if path.ends_with('/') {+ &path[..path.len() - 1]+ } else {+ path+ };+ debug_assert!(!path.is_empty());++ let slash_path = format!("{}/", path);+ router+ .route(+ path,+ routing::get(|| async move { axum::response::Redirect::to(&slash_path) }),+ )+ .route(&format!("{}/", path), handler.clone())+ .route(&format!("{}/{{*rest}}", path), handler)+ };++ if let Some(BasicAuth { username, password }) = config.basic_auth {+ let username = Arc::new(username);+ let password = Arc::new(password);+ let basic_auth_middleware =+ move |headers: HeaderMap, req: Request<Body>, next: Next| {+ let username = username.clone();+ let password = password.clone();+ async move {+ if let Some(header) = headers.get("Authorization") {+ if let Ok(header_str) = header.to_str() {+ let base64_encoded_credentials =+ BASE64_STANDARD.encode(format!("{}:{}", &username, &password));+ if header_str == format!("Basic {}", base64_encoded_credentials) {+ return Ok::<Response<Body>, StatusCode>(next.run(req).await);+ }+ }+ }+ Ok::<Response<Body>, StatusCode>(+ (+ StatusCode::UNAUTHORIZED,+ [("WWW-Authenticate", "Basic realm=\":\"")],+ )+ .into_response(),+ )+ }+ };+ router = router.layer(middleware::from_fn(basic_auth_middleware));+ }++ router+ }+}++fn add_api_doc_to_urls<S>(+ router_and_urls: (Router<S>, Vec<Url<'static>>),+ url: (Url<'static>, Arc<ApiDoc>),+) -> (Router<S>, Vec<Url<'static>>)+where+ S: Clone + Send + Sync + 'static,+{+ let (router, mut urls) = router_and_urls;+ let (url, openapi) = url;+ (+ router.route(+ url.url.as_ref(),+ routing::get(move || async { Json(openapi) }),+ ),+ {+ urls.push(url);+ urls+ },+ )+}++async fn serve_swagger_ui(+ path: Option<Path<String>>,+ Extension(state): Extension<Arc<Config<'static>>>,+) -> impl IntoResponse {+ let tail = match path.as_ref() {+ Some(tail) => tail,+ None => "",+ };++ match super::serve(tail, state) {+ Ok(file) => file+ .map(|file| {+ (+ StatusCode::OK,+ [("Content-Type", file.content_type)],+ file.bytes,+ )+ .into_response()+ })+ .unwrap_or_else(|| StatusCode::NOT_FOUND.into_response()),+ Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use http::header::AUTHORIZATION;+ use http::HeaderValue;+ use tower::util::ServiceExt;++ #[tokio::test]+ async fn mount_onto_root() {+ let app = Router::<()>::from(SwaggerUi::new("/"));+ let response = app.clone().oneshot(get("/")).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let response = app.clone().oneshot(get("/swagger-ui.css")).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn mount_onto_path_ends_with_slash() {+ let app = Router::<()>::from(SwaggerUi::new("/swagger-ui/"));+ let response = app.clone().oneshot(get("/swagger-ui")).await.unwrap();+ assert_eq!(response.status(), StatusCode::SEE_OTHER);+ let response = app.clone().oneshot(get("/swagger-ui/")).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let request = get("/swagger-ui/swagger-ui.css");+ let response = app.clone().oneshot(request).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn mount_onto_path_not_end_with_slash() {+ let app = Router::<()>::from(SwaggerUi::new("/swagger-ui"));+ let response = app.clone().oneshot(get("/swagger-ui")).await.unwrap();+ assert_eq!(response.status(), StatusCode::SEE_OTHER);+ let response = app.clone().oneshot(get("/swagger-ui/")).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let request = get("/swagger-ui/swagger-ui.css");+ let response = app.clone().oneshot(request).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn basic_auth() {+ let swagger_ui =+ SwaggerUi::new("/swagger-ui").config(Config::default().basic_auth(BasicAuth {+ username: "admin".to_string(),+ password: "password".to_string(),+ }));+ let app = Router::<()>::from(swagger_ui);+ let response = app.clone().oneshot(get("/swagger-ui")).await.unwrap();+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ let encoded_credentials = BASE64_STANDARD.encode("admin:password");+ let authorization = format!("Basic {}", encoded_credentials);+ let request = authorized_get("/swagger-ui", &authorization);+ let response = app.clone().oneshot(request).await.unwrap();+ assert_eq!(response.status(), StatusCode::SEE_OTHER);+ let request = authorized_get("/swagger-ui/", &authorization);+ let response = app.clone().oneshot(request).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let request = authorized_get("/swagger-ui/swagger-ui.css", &authorization);+ let response = app.clone().oneshot(request).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ }++ fn get(url: &str) -> Request<Body> {+ Request::builder().uri(url).body(Body::empty()).unwrap()+ }++ fn authorized_get(url: &str, authorization: &str) -> Request<Body> {+ Request::builder()+ .uri(url)+ .header(AUTHORIZATION, HeaderValue::from_str(authorization).unwrap())+ .body(Body::empty())+ .unwrap()+ }+}diff --git a/vendor/utoipa-swagger-ui/src/lib.rs b/vendor/utoipa-swagger-ui/src/lib.rsnew file mode 100644index 0000000000..35e5bebe2f--- /dev/null+++ b/vendor/utoipa-swagger-ui/src/lib.rs@@ -0,0 +1,1931 @@+#![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`+//! * **axum** `version >=0.7`+//!+//! 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.+//! * **`reqwest`** Use `reqwest` for downloading Swagger UI according to the `SWAGGER_UI_DOWNLOAD_URL` environment+//! variable. This is only enabled by default on _Windows_.+//! * **`url`** Enabled by default for parsing and encoding the download URL.+//! * **`vendored`** Enables vendored Swagger UI via `utoipa-swagger-ui-vendored` crate.+//!+//! # Install+//!+//! Use only the raw types without any boiler plate implementation.+//! ```toml+//! [dependencies]+//! utoipa-swagger-ui = "9"+//! ```+//!+//! Enable actix-web framework with Swagger UI you could define the dependency as follows.+//! ```toml+//! [dependencies]+//! utoipa-swagger-ui = { version = "9", features = ["actix-web"] }+//! ```+//!+//! **Note!** Also remember that you already have defined `utoipa` dependency in your `Cargo.toml`+//!+//! ## Build Config+//!+//! <div class="warning">+//!+//! **Note!** _`utoipa-swagger-ui` crate will by default try to use system `curl` package for downloading the Swagger UI. It+//! can optionally be downloaded with `reqwest` by enabling `reqwest` feature. On Windows the `reqwest` feature+//! is enabled by default. Reqwest can be useful for platform independent builds however bringing quite a few+//! unnecessary dependencies just to download a file. If the `SWAGGER_UI_DOWNLOAD_URL` is a file path then no+//! downloading will happen._+//!+//! </div>+//!+//! <div class="warning">+//!+//! **Tip!** Use **`vendored`** feature flag to use vendored Swagger UI. This is especially useful for no network+//! environments.+//!+//! </div>+//!+//! **The following configuration env variables are available at build time:**+//!+//! * `SWAGGER_UI_DOWNLOAD_URL`: Defines the url from where to download the swagger-ui zip file.+//!+//! * Current Swagger UI version: <https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.17.14.zip>+//! * [All available Swagger UI versions](https://github.com/swagger-api/swagger-ui/tags)+//!+//! * `SWAGGER_UI_OVERWRITE_FOLDER`: Defines an _optional_ absolute path to a directory containing files+//! to overwrite the Swagger UI files. Typically you might want to overwrite `index.html`.+//!+//! # 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};+//! # use utoipa_swagger_ui::SwaggerUi;+//! # use utoipa::OpenApi;+//!# #[derive(OpenApi)]+//!# #[openapi()]+//!# struct ApiDoc;+//!#+//!# fn inner<S>()+//!# where+//!# S: Clone + Send + Sync + 'static,+//!# {+//! let app = Router::<S>::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;++include!(concat!(env!("OUT_DIR"), "/embed.rs"));++/// Entry point for serving Swagger UI and api docs in application. It 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, the [`Config`] can be also be 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>,++ /// Defines syntax highlighting specific options.+ #[serde(skip_serializing_if = "Option::is_none")]+ syntax_highlight: Option<SyntaxHighlight>,++ /// The layout of Swagger UI uses, default is `"StandaloneLayout"`.+ layout: &'a str,++ /// Basic authentication configuration. If configured, the Swagger UI will prompt for basic auth credentials.+ #[serde(skip_serializing_if = "Option::is_none")]+ basic_auth: Option<BasicAuth>,+}++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+ }++ /// Set a specific configuration for syntax highlighting responses+ /// and curl commands.+ ///+ /// By default, swagger-ui does syntax highlighting of responses+ /// and curl commands. This may consume considerable resources in+ /// the browser when executed on large responses.+ ///+ /// # Example+ ///+ /// Disable syntax highlighting.+ /// ```rust+ /// # use utoipa_swagger_ui::Config;+ /// let config = Config::new(["/api-docs/openapi.json"])+ /// .with_syntax_highlight(false);+ /// ```+ pub fn with_syntax_highlight<H: Into<SyntaxHighlight>>(mut self, syntax_highlight: H) -> Self {+ self.syntax_highlight = Some(syntax_highlight.into());++ self+ }++ /// Set basic authentication configuration.+ /// If configured, the Swagger UI will prompt for basic auth credentials.+ /// username and password are required. "{username}:{password}" will be base64 encoded and added to the "Authorization" header.+ /// If not provided or wrong credentials are provided, the user will be prompted again.+ /// # Examples+ ///+ /// Configure basic authentication.+ /// ```rust+ /// # use utoipa_swagger_ui::Config;+ /// # use utoipa_swagger_ui::BasicAuth;+ /// let config = Config::new(["/api-docs/openapi.json"])+ /// .basic_auth(BasicAuth { username: "admin".to_string(), password: "password".to_string() });+ /// ```+ pub fn basic_auth(mut self, basic_auth: BasicAuth) -> Self {+ self.basic_auth = Some(basic_auth);++ 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(),+ syntax_highlight: Default::default(),+ layout: SWAGGER_STANDALONE_LAYOUT,+ basic_auth: Default::default(),+ }+ }+}++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])+ }+}++/// Basic auth options for Swagger UI. By providing `BasicAuth` to `Config::basic_auth` the access to the+/// Swagger UI can be restricted behind given basic authentication.+#[derive(Serialize, Clone)]+#[cfg_attr(feature = "debug", derive(Debug))]+pub struct BasicAuth {+ /// Username for the `BasicAuth`+ pub username: String,+ /// Password of the _`username`_ for the `BasicAuth`+ pub password: String,+}++/// Represents settings related to syntax highlighting of payloads and+/// cURL commands.+#[derive(Serialize, Clone)]+#[cfg_attr(feature = "debug", derive(Debug))]+#[non_exhaustive]+pub struct SyntaxHighlight {+ /// Boolean telling whether syntax highlighting should be+ /// activated or not. Defaults to `true`.+ pub activated: bool,+ /// Highlight.js syntax coloring theme to use.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub theme: Option<&'static str>,+}++impl Default for SyntaxHighlight {+ fn default() -> Self {+ Self {+ activated: true,+ theme: None,+ }+ }+}++impl From<bool> for SyntaxHighlight {+ fn from(value: bool) -> Self {+ Self {+ activated: value,+ ..Default::default()+ }+ }+}++impl SyntaxHighlight {+ /// Explicitly specifies whether syntax highlighting is to be+ /// activated or not. Defaults to true.+ pub fn activated(mut self, activated: bool) -> Self {+ self.activated = activated;+ self+ }++ /// Explicitly specifies the+ /// [Highlight.js](https://highlightjs.org/) coloring theme to+ /// utilize for syntax highlighting.+ pub fn theme(mut self, theme: &'static str) -> Self {+ self.theme = Some(theme);+ self+ }+}++/// 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]))+}++/// Is used to provide general way to deliver multiple types of OpenAPI docs via `utoipa-swagger-ui`.+#[cfg(any(feature = "actix-web", feature = "rocket", feature = "axum"))]+#[derive(Clone)]+enum ApiDoc {+ Utoipa(utoipa::openapi::OpenApi),+ Value(serde_json::Value),+}++// Delegate serde's `Serialize` to the variant itself.+#[cfg(any(feature = "actix-web", feature = "rocket", feature = "axum"))]+impl Serialize for ApiDoc {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ match self {+ Self::Value(value) => value.serialize(serializer),+ Self::Utoipa(utoipa) => utoipa.serialize(serializer),+ }+ }+}++#[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);+ }++ #[test]+ fn format_swagger_config_with_syntax_highlight_default() {+ let formatted_config = match format_config(+ &Config::new(["/api-docs/openapi1.json"])+ .with_syntax_highlight(SyntaxHighlight::default()),+ 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,+ "syntaxHighlight": {+ "activated": true+ },+ "layout": "StandaloneLayout",+ presets: [+ SwaggerUIBundle.presets.apis,+ SwaggerUIStandalonePreset+ ],+ plugins: [+ SwaggerUIBundle.plugins.DownloadUrl+ ],+});"###;++ assert_diff_equal(EXPECTED, &formatted_config);+ }++ #[test]+ fn format_swagger_config_with_syntax_highlight_on() {+ let formatted_config = match format_config(+ &Config::new(["/api-docs/openapi1.json"]).with_syntax_highlight(true),+ 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,+ "syntaxHighlight": {+ "activated": true+ },+ "layout": "StandaloneLayout",+ presets: [+ SwaggerUIBundle.presets.apis,+ SwaggerUIStandalonePreset+ ],+ plugins: [+ SwaggerUIBundle.plugins.DownloadUrl+ ],+});"###;++ assert_diff_equal(EXPECTED, &formatted_config);+ }++ #[test]+ fn format_swagger_config_with_syntax_highlight_off() {+ let formatted_config = match format_config(+ &Config::new(["/api-docs/openapi1.json"]).with_syntax_highlight(false),+ 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,+ "syntaxHighlight": {+ "activated": false+ },+ "layout": "StandaloneLayout",+ presets: [+ SwaggerUIBundle.presets.apis,+ SwaggerUIStandalonePreset+ ],+ plugins: [+ SwaggerUIBundle.plugins.DownloadUrl+ ],+});"###;++ assert_diff_equal(EXPECTED, &formatted_config);+ }++ #[test]+ fn format_swagger_config_with_syntax_highlight_default_with_theme() {+ let formatted_config = match format_config(+ &Config::new(["/api-docs/openapi1.json"])+ .with_syntax_highlight(SyntaxHighlight::default().theme("monokai")),+ 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,+ "syntaxHighlight": {+ "activated": true,+ "theme": "monokai"+ },+ "layout": "StandaloneLayout",+ presets: [+ SwaggerUIBundle.presets.apis,+ SwaggerUIStandalonePreset+ ],+ plugins: [+ SwaggerUIBundle.plugins.DownloadUrl+ ],+});"###;++ assert_diff_equal(EXPECTED, &formatted_config);+ }+}diff --git a/vendor/utoipa-swagger-ui/src/oauth.rs b/vendor/utoipa-swagger-ui/src/oauth.rsnew file mode 100644index 0000000000..cb2068724a--- /dev/null+++ b/vendor/utoipa-swagger-ui/src/oauth.rs@@ -0,0 +1,315 @@+//! Implements Swagger UI [oauth configuration](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/oauth2.md) options.++use std::collections::HashMap;++use serde::Serialize;++const END_MARKER: &str = "//</editor-fold>";++/// Object used to alter Swagger UI oauth settings.+///+/// # Examples+///+/// ```rust+/// # use utoipa_swagger_ui::oauth;+/// let config = oauth::Config::new()+/// .client_id("client-id")+/// .use_pkce_with_authorization_code_grant(true);+/// ```+#[non_exhaustive]+#[derive(Default, Clone, Serialize)]+#[cfg_attr(feature = "debug", derive(Debug))]+#[serde(rename_all = "camelCase")]+pub struct Config {+ /// oauth client_id the Swagger UI is using for auth flow.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub client_id: Option<String>,++ /// oauth client_secret the Swagger UI is using for auth flow.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub client_secret: Option<String>,++ /// oauth realm the Swagger UI is using for auth flow.+ /// realm query parameter (for oauth1) added to authorizationUrl and tokenUrl.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub realm: Option<String>,++ /// oauth app_name the Swagger UI is using for auth flow.+ /// application name, displayed in authorization popup.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub app_name: Option<String>,++ /// oauth scope_separator the Swagger UI is using for auth flow.+ /// scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub scope_separator: Option<String>,++ /// oauth scopes the Swagger UI is using for auth flow.+ /// [`Vec<String>`] of initially selected oauth scopes, default is empty.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub scopes: Option<Vec<String>>,++ /// oauth additional_query_string_params the Swagger UI is using for auth flow.+ /// [`HashMap<String, String>`] of additional query parameters added to authorizationUrl and tokenUrl.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub additional_query_string_params: Option<HashMap<String, String>>,++ /// oauth use_basic_authentication_with_access_code_grant the Swagger UI is using for auth flow.+ /// Only activated for the accessCode flow. During the authorization_code request to the tokenUrl,+ /// pass the [Client Password](https://tools.ietf.org/html/rfc6749#section-2.3.1) using the HTTP Basic Authentication scheme+ /// (Authorization header with Basic base64encode(client_id + client_secret)).+ /// The default is false.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub use_basic_authentication_with_access_code_grant: Option<bool>,++ /// oauth use_pkce_with_authorization_code_grant the Swagger UI is using for auth flow.+ /// Only applies to authorizationCode flows. [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636)+ /// brings enhanced security for OAuth public clients.+ /// The default is false.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub use_pkce_with_authorization_code_grant: Option<bool>,+}++impl Config {+ /// Create a new [`Config`] for oauth auth flow.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new();+ /// ```+ pub fn new() -> Self {+ Self {+ ..Default::default()+ }+ }++ /// Add client_id into [`Config`].+ ///+ /// Method takes one argument which exposes the client_id to the user.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .client_id("client-id");+ /// ```+ pub fn client_id(mut self, client_id: &str) -> Self {+ self.client_id = Some(String::from(client_id));++ self+ }++ /// Add client_secret into [`Config`].+ ///+ /// Method takes one argument which exposes the client_secret to the user.+ /// 🚨 Never use this parameter in your production environment.+ /// It exposes crucial security information. This feature is intended for dev/test environments only. 🚨+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .client_secret("client-secret");+ /// ```+ pub fn client_secret(mut self, client_secret: &str) -> Self {+ self.client_secret = Some(String::from(client_secret));++ self+ }++ /// Add realm into [`Config`].+ ///+ /// Method takes one argument which exposes the realm to the user.+ /// realm query parameter (for oauth1) added to authorizationUrl and tokenUrl.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .realm("realm");+ /// ```+ pub fn realm(mut self, realm: &str) -> Self {+ self.realm = Some(String::from(realm));++ self+ }++ /// Add app_name into [`Config`].+ ///+ /// Method takes one argument which exposes the app_name to the user.+ /// application name, displayed in authorization popup.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .app_name("app-name");+ /// ```+ pub fn app_name(mut self, app_name: &str) -> Self {+ self.app_name = Some(String::from(app_name));++ self+ }++ /// Add scope_separator into [`Config`].+ ///+ /// Method takes one argument which exposes the scope_separator to the user.+ /// scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20).+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .scope_separator(",");+ /// ```+ pub fn scope_separator(mut self, scope_separator: &str) -> Self {+ self.scope_separator = Some(String::from(scope_separator));++ self+ }++ /// Add scopes into [`Config`].+ ///+ /// Method takes one argument which exposes the scopes to the user.+ /// [`Vec<String>`] of initially selected oauth scopes, default is empty.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .scopes(vec![String::from("openid")]);+ /// ```+ pub fn scopes(mut self, scopes: Vec<String>) -> Self {+ self.scopes = Some(scopes);++ self+ }++ /// Add additional_query_string_params into [`Config`].+ ///+ /// Method takes one argument which exposes the additional_query_string_params to the user.+ /// [`HashMap<String, String>`] of additional query parameters added to authorizationUrl and tokenUrl.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// # use std::collections::HashMap;+ /// let config = oauth::Config::new()+ /// .additional_query_string_params(HashMap::from([(String::from("a"), String::from("1"))]));+ /// ```+ pub fn additional_query_string_params(+ mut self,+ additional_query_string_params: HashMap<String, String>,+ ) -> Self {+ self.additional_query_string_params = Some(additional_query_string_params);++ self+ }++ /// Add use_basic_authentication_with_access_code_grant into [`Config`].+ ///+ /// Method takes one argument which exposes the use_basic_authentication_with_access_code_grant to the user.+ /// Only activated for the accessCode flow. During the authorization_code request to the tokenUrl,+ /// pass the [Client Password](https://tools.ietf.org/html/rfc6749#section-2.3.1) using the HTTP Basic Authentication scheme+ /// (Authorization header with Basic base64encode(client_id + client_secret)).+ /// The default is false.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .use_basic_authentication_with_access_code_grant(true);+ /// ```+ pub fn use_basic_authentication_with_access_code_grant(+ mut self,+ use_basic_authentication_with_access_code_grant: bool,+ ) -> Self {+ self.use_basic_authentication_with_access_code_grant =+ Some(use_basic_authentication_with_access_code_grant);++ self+ }++ /// Add use_pkce_with_authorization_code_grant into [`Config`].+ ///+ /// Method takes one argument which exposes the use_pkce_with_authorization_code_grant to the user.+ /// Only applies to authorizationCode flows. [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636)+ /// brings enhanced security for OAuth public clients.+ /// The default is false.+ ///+ /// # Examples+ ///+ /// ```rust+ /// # use utoipa_swagger_ui::oauth;+ /// let config = oauth::Config::new()+ /// .use_pkce_with_authorization_code_grant(true);+ /// ```+ pub fn use_pkce_with_authorization_code_grant(+ mut self,+ use_pkce_with_authorization_code_grant: bool,+ ) -> Self {+ self.use_pkce_with_authorization_code_grant = Some(use_pkce_with_authorization_code_grant);++ self+ }+}++pub(crate) fn format_swagger_config(config: &Config, file: String) -> serde_json::Result<String> {+ let init_string = format!(+ "{}\nui.initOAuth({});",+ END_MARKER,+ serde_json::to_string_pretty(config)?+ );+ Ok(file.replace(END_MARKER, &init_string))+}++#[cfg(test)]+mod tests {+ use super::*;++ const TEST_CONTENT: &str = r###""+ //<editor-fold desc=\"Changeable Configuration Block\">+ window.ui = SwaggerUIBundle({+ {{urls}},+ dom_id: '#swagger-ui',+ deepLinking: true,+ presets: [+ SwaggerUIBundle.presets.apis,+ SwaggerUIStandalonePreset+ ],+ plugins: [+ SwaggerUIBundle.plugins.DownloadUrl+ ],+ layout: "StandaloneLayout"+ });+ //</editor-fold>+ ""###;++ #[test]+ fn format_swagger_config_oauth() {+ let config = Config {+ client_id: Some(String::from("my-special-client")),+ ..Default::default()+ };+ let file = super::format_swagger_config(&config, TEST_CONTENT.to_string()).unwrap();++ let expected = r#"+ui.initOAuth({+ "clientId": "my-special-client"+});"#;+ assert!(+ file.contains(expected),+ "expected file to contain {expected}, was {file}"+ )+ }+}diff --git a/vendor/utoipa-swagger-ui/src/rocket.rs b/vendor/utoipa-swagger-ui/src/rocket.rsnew file mode 100644index 0000000000..bd62e5e418--- /dev/null+++ b/vendor/utoipa-swagger-ui/src/rocket.rs@@ -0,0 +1,217 @@+#![cfg(feature = "rocket")]++use std::{borrow::Cow, io::Cursor, sync::Arc};++use base64::{prelude::BASE64_STANDARD, Engine};+use rocket::{+ http::{Header, Status},+ request::{self, FromRequest},+ response::{status::NotFound, Responder as RocketResponder},+ route::{Handler, Outcome},+ serde::json::Json,+ Data as RocketData, Request, Response, Route,+};++use crate::{ApiDoc, BasicAuth, Config, SwaggerFile, SwaggerUi};++impl From<SwaggerUi> for Vec<Route> {+ fn from(swagger_ui: SwaggerUi) -> Self {+ let mut routes =+ Vec::<Route>::with_capacity(swagger_ui.urls.len() + 1 + swagger_ui.external_urls.len());+ let mut api_docs =+ Vec::<Route>::with_capacity(swagger_ui.urls.len() + swagger_ui.external_urls.len());++ let urls = swagger_ui+ .urls+ .into_iter()+ .map(|(url, openapi)| (url, ApiDoc::Utoipa(openapi)))+ .chain(+ swagger_ui+ .external_urls+ .into_iter()+ .map(|(url, api_doc)| (url, ApiDoc::Value(api_doc))),+ )+ .map(|(url, openapi)| {+ api_docs.push(Route::new(+ rocket::http::Method::Get,+ &url.url,+ ServeApiDoc(openapi),+ ));+ url+ });++ routes.push(Route::new(+ rocket::http::Method::Get,+ swagger_ui.path.as_ref(),+ ServeSwagger(+ swagger_ui.path.clone(),+ Arc::new(if let Some(config) = swagger_ui.config {+ if config.url.is_some() || !config.urls.is_empty() {+ config+ } else {+ config.configure_defaults(urls)+ }+ } else {+ Config::new(urls)+ }),+ ),+ ));+ routes.extend(api_docs);++ routes+ }+}++#[derive(Clone)]+struct ServeApiDoc(ApiDoc);++#[rocket::async_trait]+impl Handler for ServeApiDoc {+ async fn handle<'r>(&self, request: &'r Request<'_>, _: RocketData<'r>) -> Outcome<'r> {+ Outcome::from(request, Json(self.0.clone()))+ }+}++#[derive(Clone)]+struct ServeSwagger(Cow<'static, str>, Arc<Config<'static>>);++#[rocket::async_trait]+impl Handler for ServeSwagger {+ async fn handle<'r>(&self, request: &'r Request<'_>, _: RocketData<'r>) -> Outcome<'r> {+ if let Some(basic_auth) = &self.1.clone().basic_auth {+ let request_guard = request.guard::<BasicAuth>().await;+ match request_guard {+ request::Outcome::Success(BasicAuth { username, password })+ if username == basic_auth.username && password == basic_auth.password =>+ {+ ()+ }+ _ => return Outcome::from(request, BasicAuthErrorResponse),+ }+ }++ let mut base_path = self.0.as_ref();+ if let Some(index) = self.0.find('<') {+ base_path = &base_path[..index];+ }++ let request_path = request.uri().path().as_str();+ let request_path = match request_path.strip_prefix(base_path) {+ Some(stripped) => stripped,+ None => return Outcome::from(request, RedirectResponder(base_path.into())),+ };+ match super::serve(request_path, self.1.clone()) {+ Ok(swagger_file) => swagger_file+ .map(|file| Outcome::from(request, file))+ .unwrap_or_else(|| Outcome::from(request, NotFound("Swagger UI file not found"))),+ Err(error) => Outcome::from(+ request,+ rocket::response::status::Custom(Status::InternalServerError, error.to_string()),+ ),+ }+ }+}++pub struct BasicAuthErrorResponse;++impl<'r, 'o: 'r> RocketResponder<'r, 'o> for BasicAuthErrorResponse {+ fn respond_to(self, _: &'r Request<'_>) -> rocket::response::Result<'o> {+ Response::build()+ .status(Status::Unauthorized)+ .header(Header::new("WWW-Authenticate", "Basic realm=\":\""))+ .ok()+ }+}++impl<'r, 'o: 'r> RocketResponder<'r, 'o> for SwaggerFile<'o> {+ fn respond_to(self, _: &'r Request<'_>) -> rocket::response::Result<'o> {+ Ok(Response::build()+ .header(Header::new("Content-Type", self.content_type))+ .sized_body(self.bytes.len(), Cursor::new(self.bytes.to_vec()))+ .status(Status::Ok)+ .finalize())+ }+}++struct RedirectResponder(String);+impl<'r, 'a: 'r> RocketResponder<'r, 'a> for RedirectResponder {+ fn respond_to(self, _request: &'r Request<'_>) -> rocket::response::Result<'a> {+ Response::build()+ .status(Status::Found)+ .raw_header("Location", self.0)+ .ok()+ }+}++#[rocket::async_trait]+impl<'r> FromRequest<'r> for BasicAuth {+ type Error = ();++ async fn from_request(req: &'r Request<'_>) -> request::Outcome<BasicAuth, ()> {+ match req.headers().get_one("Authorization") {+ None => request::Outcome::Error((Status::BadRequest, ())),+ Some(credentials) => {+ if let Some(basic_auth) = credentials+ .strip_prefix("Basic ")+ .and_then(|s| BASE64_STANDARD.decode(s).ok())+ .and_then(|b| String::from_utf8(b).ok())+ .and_then(|s| {+ if let Some((username, password)) = s.split_once(':') {+ Some(BasicAuth {+ username: username.to_string(),+ password: password.to_string(),+ })+ } else {+ None+ }+ })+ {+ request::Outcome::Success(basic_auth)+ } else {+ request::Outcome::Error((Status::BadRequest, ()))+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use rocket::local::blocking::Client;++ use crate::BasicAuth;++ use super::*;++ #[test]+ fn mount_onto_path_not_end_with_slash() {+ let routes: Vec<Route> = SwaggerUi::new("/swagger-ui").into();+ let rocket = rocket::build().mount("/", routes);+ let client = Client::tracked(rocket).unwrap();+ let response = client.get("/swagger-ui").dispatch();+ assert_eq!(response.status(), Status::Ok);+ }++ #[test]+ fn basic_auth() {+ let swagger_ui =+ SwaggerUi::new("/swagger-ui").config(Config::default().basic_auth(BasicAuth {+ username: "admin".to_string(),+ password: "password".to_string(),+ }));+ let routes: Vec<Route> = swagger_ui.into();+ let rocket = rocket::build().mount("/", routes);+ let client = Client::tracked(rocket).unwrap();+ let response = client.get("/swagger-ui").dispatch();+ assert_eq!(response.status(), Status::Unauthorized);+ let encoded_credentials = BASE64_STANDARD.encode("admin:password");+ let response = client+ .get("/swagger-ui")+ .header(Header::new(+ "Authorization",+ format!("Basic {}", encoded_credentials),+ ))+ .dispatch();+ assert_eq!(response.status(), Status::Ok);+ }+}