mod assets;
mod options;
mod page;
use axum::{
Router,
body::Bytes,
http::{Uri, header},
response::Redirect,
routing::{MethodRouter, get},
};
use serde_json::Value;
use thiserror::Error;
use utoipa::openapi::OpenApi;
use crate::result::{ClassifyError, ErrorCode, ErrorKind};
#[cfg(feature = "rapidoc-embedded")]
pub use assets::EMBEDDED_RAPIDOC_VERSION;
#[cfg(feature = "redoc-embedded")]
pub use assets::EMBEDDED_REDOC_VERSION;
pub use assets::{DocsAssets, DocsUi};
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DocsError {
#[error("invalid documentation mount path: {0}")]
InvalidPath(String),
#[error("invalid documentation script URL: {0}")]
InvalidAssetUrl(String),
#[error("invalid documentation options: {0}")]
InvalidOptions(&'static str),
#[error("documentation template must contain exactly one {0} slot")]
InvalidTemplate(&'static str),
#[error("cannot serialize the OpenAPI document: {0}")]
Serialize(#[from] serde_json::Error),
}
impl ClassifyError for DocsError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
ErrorCode::internal(match self {
Self::InvalidPath(_) => "docs_invalid_path",
Self::InvalidAssetUrl(_) => "docs_invalid_asset_url",
Self::InvalidOptions(_) => "docs_invalid_options",
Self::InvalidTemplate(_) => "docs_invalid_template",
Self::Serialize(_) => "docs_serialization_failed",
})
}
}
#[must_use]
pub struct OpenApiDocs {
document: OpenApi,
path: String,
ui: DocsUi,
title: String,
options: Value,
preset: bool,
template: String,
}
impl std::fmt::Debug for OpenApiDocs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenApiDocs")
.field("path", &self.path)
.field("ui", &self.ui)
.field("title", &self.title)
.field("preset", &self.preset)
.finish_non_exhaustive()
}
}
impl OpenApiDocs {
pub fn new(document: OpenApi, path: impl Into<String>, ui: DocsUi) -> Self {
Self {
title: document.info.title.clone(),
document,
path: path.into(),
ui,
options: serde_json::json!({}),
preset: true,
template: include_str!("template.html").to_owned(),
}
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
pub fn with_options(mut self, options: Value) -> Self {
self.options = options;
self
}
pub fn without_preset(mut self) -> Self {
self.preset = false;
self
}
pub fn with_template(mut self, template: impl Into<String>) -> Self {
self.template = template.into();
self
}
pub fn into_router<S: Clone + Send + Sync + 'static>(self) -> Result<Router<S>, DocsError> {
let mount = mount_path(&self.path)?;
let options = options::resolve(self.options, self.preset, &self.ui)?;
let script_url = self.ui.assets().script_url()?;
let html = page::render(&self.template, &self.title, script_url, self.ui.name())?;
let mut router = Router::new()
.route(
&format!("{mount}/"),
resource("text/html; charset=utf-8", html),
)
.route(
&format!("{mount}/openapi.json"),
resource("application/json", serde_json::to_vec(&self.document)?),
)
.route(
&format!("{mount}/options.json"),
resource("application/json", serde_json::to_vec(&options)?),
)
.route(
&format!("{mount}/init.js"),
resource(
"text/javascript; charset=utf-8",
include_bytes!("init.js").as_slice(),
),
)
.route(
&format!("{mount}/page.css"),
resource(
"text/css; charset=utf-8",
include_bytes!("page.css").as_slice(),
),
);
if !mount.is_empty() {
let leaf = mount.rsplit('/').next().unwrap_or_default().to_owned();
router = router.route(
mount,
get(move |uri: Uri| {
let mut location = format!("{leaf}/");
if let Some(query) = uri.query() {
location.push('?');
location.push_str(query);
}
async move {
(
[(header::CACHE_CONTROL, "private, no-cache")],
Redirect::permanent(&location),
)
}
}),
);
}
Ok(self.ui.into_assets().mount(router, mount))
}
}
fn mount_path(path: &str) -> Result<&str, DocsError> {
let mount = path.strip_suffix('/').unwrap_or(path);
if !path.starts_with('/')
|| !path
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"/-._~".contains(&b))
|| (!mount.is_empty()
&& mount[1..]
.split('/')
.any(|s| s.is_empty() || s == "." || s == ".."))
{
return Err(DocsError::InvalidPath(path.to_owned()));
}
Ok(mount)
}
fn resource<S: Clone + Send + Sync + 'static>(
content_type: &'static str,
bytes: impl Into<Bytes>,
) -> MethodRouter<S> {
let bytes = bytes.into();
get(move || {
let bytes = bytes.clone();
async move {
(
[
(header::CONTENT_TYPE, content_type),
(header::CACHE_CONTROL, "private, no-cache"),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
],
bytes,
)
}
})
}