Skip to main content

nitr_http/config/sections/
docs.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! The `[openapi]` and `[swagger]` sections: the generated API document
7//! and the Swagger UI page that renders it.
8//!
9//! Both parse in every build. Producing the document needs the `openapi`
10//! Cargo feature and the page the `swagger` one; `enabled = true` on a
11//! binary without the feature is refused at startup naming it, the same
12//! way `[tls]` is.
13
14use std::collections::BTreeMap;
15use std::path::PathBuf;
16
17use serde::{Deserialize, Serialize};
18
19/// The generated OpenAPI document (`[openapi]` section).
20///
21/// Off by default: a route map is reconnaissance material, and publishing
22/// it should be a decision. The `nitr openapi` command generates the
23/// document regardless of `enabled` — the flag gates serving, not
24/// generation.
25#[derive(Debug, Clone, Deserialize, Serialize)]
26#[serde(default, deny_unknown_fields)]
27pub struct OpenApiConfig {
28    /// Serve the document at `path`.
29    pub enabled: bool,
30    /// Where the document is served (`/openapi.json`).
31    pub path: String,
32    /// The `servers` list of the document: deployment-level, hence
33    /// configuration rather than script.
34    pub servers: Vec<String>,
35    /// Whether routes without a `doc` table still appear, as bare
36    /// operations. The default documents everything routable; a route
37    /// is kept out with `doc = { hidden = true }`.
38    pub include_undocumented: bool,
39    /// Dev mode only: a file rewritten after each successful rebuild when
40    /// the document changed, so a committed `openapi.json` stays current
41    /// while `nitr dev` runs. Production never writes.
42    pub output: Option<PathBuf>,
43}
44
45impl Default for OpenApiConfig {
46    fn default() -> Self {
47        Self {
48            enabled: false,
49            path: "/openapi.json".into(),
50            servers: Vec::new(),
51            include_undocumented: true,
52            output: None,
53        }
54    }
55}
56
57/// The Swagger UI page (`[swagger]` section).
58///
59/// The page is the vendored Swagger UI bundle served from this binary:
60/// no CDN, no network, and a `Content-Security-Policy` that forbids
61/// inline script. Needs `[openapi] enabled` (or an explicit `spec_url`).
62#[derive(Debug, Clone, Deserialize, Serialize)]
63#[serde(default, deny_unknown_fields)]
64pub struct SwaggerConfig {
65    /// Serve the page at `path`.
66    pub enabled: bool,
67    /// Where the page is served (`/docs`); its assets live under
68    /// `<path>/assets/<version>/`.
69    pub path: String,
70    /// The page `<title>`; defaults to the `app:doc` title.
71    pub title: Option<String>,
72    /// The document the page loads; defaults to `[openapi] path`. A URL
73    /// with an origin needs `allow_external_spec`.
74    pub spec_url: Option<String>,
75    /// Allow `spec_url` on another origin, widening the page's
76    /// `connect-src` to exactly that origin.
77    pub allow_external_spec: bool,
78    /// Swagger UI `deepLinking`.
79    pub deep_linking: bool,
80    /// Swagger UI `docExpansion`: `"list"`, `"full"` or `"none"`.
81    pub doc_expansion: String,
82    /// Swagger UI `filter`: the operation filter box.
83    pub filter: bool,
84    /// Swagger UI `tryItOutEnabled`: whether "Try it out" starts enabled.
85    pub try_it_out: bool,
86    /// Swagger UI `displayRequestDuration`.
87    pub display_request_duration: bool,
88    /// Swagger UI `persistAuthorization`. Off by default: it keeps entered
89    /// tokens in the browser's `localStorage`.
90    pub persist_authorization: bool,
91    /// Swagger UI `displayOperationId`.
92    pub display_operation_id: bool,
93    /// Swagger UI `defaultModelsExpandDepth`.
94    pub default_models_expand_depth: i64,
95    /// Further Swagger UI options, passed verbatim (camelCase keys). May
96    /// not repeat a typed setting above under its camelCase name, nor set
97    /// `url` or `dom_id`, which the page owns.
98    pub options: BTreeMap<String, toml::Value>,
99}
100
101impl Default for SwaggerConfig {
102    fn default() -> Self {
103        Self {
104            enabled: false,
105            path: "/docs".into(),
106            title: None,
107            spec_url: None,
108            allow_external_spec: false,
109            deep_linking: true,
110            doc_expansion: "list".into(),
111            filter: false,
112            try_it_out: false,
113            display_request_duration: false,
114            persist_authorization: false,
115            display_operation_id: false,
116            default_models_expand_depth: 1,
117            options: BTreeMap::new(),
118        }
119    }
120}
121
122/// The typed `[swagger]` settings and the Swagger UI option each one
123/// spells, so `[swagger.options]` cannot carry a second spelling.
124pub(crate) const SWAGGER_TYPED_OPTIONS: &[(&str, &str)] = &[
125    ("deep_linking", "deepLinking"),
126    ("doc_expansion", "docExpansion"),
127    ("filter", "filter"),
128    ("try_it_out", "tryItOutEnabled"),
129    ("display_request_duration", "displayRequestDuration"),
130    ("persist_authorization", "persistAuthorization"),
131    ("display_operation_id", "displayOperationId"),
132    ("default_models_expand_depth", "defaultModelsExpandDepth"),
133];
134
135/// The `[swagger.options]` keys the page owns.
136pub(crate) const SWAGGER_RESERVED_OPTIONS: &[&str] = &["url", "dom_id", "domNode", "spec"];
137
138/// The accepted `doc_expansion` spellings.
139pub(crate) const DOC_EXPANSIONS: &[&str] = &["list", "full", "none"];