Skip to main content

fusion_stack/
openapi.rs

1//! The OpenAPI 3.1 document, as the PHP package's `Generator` writes it, for each version.
2//!
3//! Rust has no reflection, so each endpoint is declared with
4//! [`Config::endpoint`](crate::Config::endpoint), keyed by method and URI as `GET /v1/orders`,
5//! with its summary, response, query and request body. The document lists the declared endpoints
6//! each version serves; [`undeclared`] finds API routes that are missing. Resource schemas come
7//! from the registered [`Resource`]s, named as each version names them.
8
9use std::cell::RefCell;
10use std::collections::{BTreeMap, BTreeSet};
11use std::sync::Arc;
12
13use laravel::http::{Request, Response};
14use serde_json::{Map, Value, json};
15
16use crate::errors::{ApiErrorCode, ErrorCode};
17#[cfg(feature = "database")]
18use crate::query::{ApiQuery, Pagination};
19use crate::resources::{Kind, Link, Resource};
20use crate::versioning::{self, ApiVersion, VersionChange};
21use crate::{State, time};
22
23const JSON_API: &str = "application/vnd.api+json";
24
25/// What the OpenAPI document says about one endpoint.
26#[derive(Clone, Default)]
27pub struct Endpoint {
28    summary: Option<String>,
29    description: Option<String>,
30    operation_id: Option<String>,
31    tags: Vec<String>,
32    status: Option<u16>,
33    resource: Option<String>,
34    collection: bool,
35    #[cfg(feature = "database")]
36    query: Option<ApiQuery>,
37    body: Option<(String, Value, Option<Value>)>,
38    scopes: Vec<(String, String)>,
39    hidden: bool,
40}
41
42impl Endpoint {
43    /// An endpoint with a short summary, such as `List orders`.
44    #[must_use]
45    pub fn new(summary: &str) -> Self {
46        Self {
47            summary: Some(summary.to_owned()),
48            ..Self::default()
49        }
50    }
51
52    /// An endpoint without a summary: the document uses its method and path.
53    #[must_use]
54    pub fn unnamed() -> Self {
55        Self::default()
56    }
57
58    /// A longer description, in Markdown.
59    #[must_use]
60    pub fn description(mut self, text: &str) -> Self {
61        self.description = Some(text.to_owned());
62        self
63    }
64
65    /// The operation's ID, such as `orders.invoice`, in place of one made from the method and path.
66    #[must_use]
67    pub fn operation_id(mut self, id: &str) -> Self {
68        self.operation_id = Some(id.to_owned());
69        self
70    }
71
72    /// Tags in place of the path's first segment.
73    #[must_use]
74    pub fn tags<I: IntoIterator<Item = S>, S: Into<String>>(mut self, tags: I) -> Self {
75        self.tags = tags.into_iter().map(Into::into).collect();
76        self
77    }
78
79    /// The success status, when it is not 200 (or 201 for a POST that creates a resource).
80    #[must_use]
81    pub const fn status(mut self, status: u16) -> Self {
82        self.status = Some(status);
83        self
84    }
85
86    /// Responds with one resource of this type.
87    #[must_use]
88    pub fn resource(mut self, kind: &str) -> Self {
89        self.resource = Some(kind.to_owned());
90        self
91    }
92
93    /// Responds with a page of resources.
94    #[must_use]
95    pub const fn collection(mut self) -> Self {
96        self.collection = true;
97        self
98    }
99
100    /// The query behind the endpoint: its include and fields parameters, and for a collection
101    /// its filters, sorts and pages. Responds with the query's resource type.
102    #[cfg(feature = "database")]
103    #[must_use]
104    pub fn query(mut self, query: &ApiQuery) -> Self {
105        self.resource = Some(query.kind.clone());
106        self.query = Some(query.clone());
107        self
108    }
109
110    /// A JSON:API request body: its JSON schema and an example.
111    #[must_use]
112    pub fn json_api_body(mut self, schema: Value, example: Value) -> Self {
113        self.body = Some((JSON_API.to_owned(), schema, Some(example)));
114        self
115    }
116
117    /// A plain JSON request body: its JSON schema and an example.
118    #[must_use]
119    pub fn body(mut self, schema: Value, example: Value) -> Self {
120        self.body = Some(("application/json".to_owned(), schema, Some(example)));
121        self
122    }
123
124    /// A scope the endpoint requires, as its [`RequiresScope`](crate::RequiresScope) middleware
125    /// does, and what it allows.
126    #[must_use]
127    pub fn scope(mut self, scope: &str, description: &str) -> Self {
128        self.scopes.push((scope.to_owned(), description.to_owned()));
129        self
130    }
131
132    /// Leaves the endpoint out of the document.
133    #[must_use]
134    pub const fn hidden(mut self) -> Self {
135        self.hidden = true;
136        self
137    }
138}
139
140/// `api.openapi` in the PHP package.
141#[derive(Clone)]
142pub(crate) struct Settings {
143    pub(crate) title: Option<String>,
144    pub(crate) description: Option<String>,
145    pub(crate) servers: Option<Vec<String>>,
146    pub(crate) version: String,
147    pub(crate) error_codes: Vec<Arc<dyn ErrorCode>>,
148    pub(crate) endpoints: Vec<(String, Endpoint)>,
149}
150
151impl Default for Settings {
152    fn default() -> Self {
153        Self {
154            title: None,
155            description: None,
156            servers: None,
157            version: "1.0.0".to_owned(),
158            error_codes: Vec::new(),
159            endpoints: Vec::new(),
160        }
161    }
162}
163
164/// A route the document covers.
165struct ApiRoute {
166    methods: Vec<String>,
167    uri: String,
168}
169
170/// The declared endpoints, as routes: their methods and URIs, in declaration order.
171fn routes(settings: &Settings) -> Vec<ApiRoute> {
172    let mut routes: Vec<ApiRoute> = Vec::new();
173    for (key, _) in &settings.endpoints {
174        let Some((method, uri)) = key.split_once(' ') else {
175            continue;
176        };
177        let uri = format!("/{}", uri.trim_start_matches('/'));
178        match routes.iter_mut().find(|route| route.uri == uri) {
179            Some(route) => route.methods.push(method.to_uppercase()),
180            None => routes.push(ApiRoute {
181                methods: vec![method.to_uppercase()],
182                uri,
183            }),
184        }
185    }
186    routes
187}
188
189/// The routes with the [`FusionStack`](crate::FusionStack) middleware that no
190/// [`Config::endpoint`](crate::Config::endpoint) describes, as `GET /v1/orders`, for a lint
191/// command: Rust cannot find their handlers, so the document leaves them out.
192#[must_use]
193pub fn undeclared(routes: &laravel::routing::RouteTable) -> Vec<String> {
194    let declared: Vec<String> = crate::STATE
195        .get()
196        .map(|state| {
197            state
198                .config
199                .openapi
200                .endpoints
201                .iter()
202                .map(|(key, _)| key.clone())
203                .collect()
204        })
205        .unwrap_or_default();
206    routes
207        .iter()
208        .filter(|route| {
209            route
210                .middleware
211                .iter()
212                .any(|name| name == "fusion_stack::FusionStack")
213        })
214        .flat_map(|route| {
215            let uri = format!("/{}", route.uri.trim_start_matches('/'));
216            route
217                .methods
218                .iter()
219                .filter(|method| *method != "HEAD")
220                .map(move |method| format!("{method} {uri}"))
221                .collect::<Vec<_>>()
222        })
223        .filter(|key| !declared.contains(key))
224        .collect()
225}
226
227/// The registered Fusion Stack's document for a version (`None` for the latest, or the only
228/// one when versioning is off). `Err` names a version the API does not have.
229///
230/// # Errors
231///
232/// When `version` is not a version of the API, or Fusion Stack is not registered.
233pub fn generate(version: Option<&str>) -> Result<Value, String> {
234    let state = crate::STATE
235        .get()
236        .ok_or_else(|| "Fusion Stack is not registered as a service provider.".to_owned())?;
237    let version = match (&state.registry, version) {
238        (None, _) => None,
239        (Some(registry), None) => Some(registry.latest.clone()),
240        (Some(registry), Some(name)) => Some(
241            registry
242                .named(name)
243                .ok_or_else(|| format!("[{name}] is not a version of this API."))?,
244        ),
245    };
246    Ok(Generator::new(state, version).document(&routes(&state.config.openapi)))
247}
248
249/// Something the API reference has no description for, as `api:docs:lint` lists it.
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub struct Gap {
252    /// `endpoint`, `field`, `filter`, `scope` or `error code`.
253    pub kind: String,
254    /// What has no description, such as `GET /v1/orders` or `orders.status`.
255    pub item: String,
256    /// Where to add one.
257    pub location: String,
258}
259
260/// What the latest version's document has no description for, sorted by kind, item and location.
261///
262/// # Errors
263///
264/// When Fusion Stack is not registered.
265pub fn undocumented() -> Result<Vec<Gap>, String> {
266    let state = crate::STATE
267        .get()
268        .ok_or_else(|| "Fusion Stack is not registered as a service provider.".to_owned())?;
269    let version = state
270        .registry
271        .as_ref()
272        .map(|registry| registry.latest.clone());
273    let mut generator = Generator::new(state, version);
274    generator.document(&routes(&state.config.openapi));
275    Ok(generator
276        .gaps
277        .into_inner()
278        .into_iter()
279        .map(|(kind, item, location)| Gap {
280            kind,
281            item,
282            location,
283        })
284        .collect())
285}
286
287/// The document as PHP's `JSON_PRETTY_PRINT` writes it, indented by four spaces.
288#[must_use]
289pub fn pretty(document: &Value) -> String {
290    let mut body = Vec::new();
291    let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
292    let mut serializer = serde_json::Serializer::with_formatter(&mut body, formatter);
293    let _ = serde::Serialize::serialize(document, &mut serializer);
294    String::from_utf8(body).unwrap_or_default()
295}
296
297/// Serves the document at a route such as `/openapi.json`, for the version in `?version=`, or the
298/// latest. An unknown version is a 404.
299pub async fn serve(request: Request) -> Response {
300    let query = crate::query_string::parse(request.uri().query().unwrap_or_default());
301    let version = query
302        .get("version")
303        .and_then(Value::as_str)
304        .filter(|v| !v.is_empty());
305    match generate(version) {
306        Ok(document) => {
307            let body = pretty(&document);
308            let mut http =
309                laravel::axum::http::Response::new(laravel::axum::body::Body::from(body));
310            http.headers_mut().insert(
311                laravel::http::header::CONTENT_TYPE,
312                laravel::http::HeaderValue::from_static("application/json"),
313            );
314            Response::from_http(http)
315        }
316        Err(_) => Response::new((
317            laravel::http::StatusCode::NOT_FOUND,
318            laravel::http::Json(
319                json!({ "message": "Unknown version. Run api:version:list to see the versions." }),
320            ),
321        )),
322    }
323}
324
325struct Generator<'a> {
326    state: &'a State,
327    version: Option<ApiVersion>,
328    changes: Vec<Arc<dyn VersionChange>>,
329    schemas: BTreeMap<String, Value>,
330    operation_ids: Vec<String>,
331    scopes: BTreeMap<String, String>,
332    /// What the document has no description for, as (kind, item, location).
333    gaps: RefCell<BTreeSet<(String, String, String)>>,
334}
335
336impl<'a> Generator<'a> {
337    fn new(state: &'a State, version: Option<ApiVersion>) -> Self {
338        let changes = match (&state.registry, &version) {
339            (Some(registry), Some(version)) => registry.changes_after(version, None),
340            _ => Vec::new(),
341        };
342        Self {
343            state,
344            version,
345            changes,
346            schemas: BTreeMap::new(),
347            operation_ids: Vec::new(),
348            scopes: BTreeMap::new(),
349            gaps: RefCell::new(BTreeSet::new()),
350        }
351    }
352
353    fn missing(&self, kind: &str, item: String, location: String) {
354        self.gaps
355            .borrow_mut()
356            .insert((kind.to_owned(), item, location));
357    }
358
359    fn settings(&self) -> &Settings {
360        &self.state.config.openapi
361    }
362
363    fn document(&mut self, routes: &[ApiRoute]) -> Value {
364        let mut paths: BTreeMap<String, Map<String, Value>> = BTreeMap::new();
365        for route in routes {
366            for method in &route.methods {
367                let key = format!("{method} {}", route.uri);
368                if let (Some(registry), Some(version)) = (&self.state.registry, &self.version)
369                    && registry
370                        .assert_route_available(
371                            &key,
372                            method,
373                            route.uri.trim_start_matches('/'),
374                            version,
375                        )
376                        .is_err()
377                {
378                    continue;
379                }
380                let endpoint = self
381                    .settings()
382                    .endpoints
383                    .iter()
384                    .find(|(known, _)| *known == key)
385                    .map(|(_, endpoint)| endpoint.clone())
386                    .unwrap_or_default();
387                if endpoint.hidden {
388                    continue;
389                }
390                let operation = self.operation(method, &route.uri, &endpoint);
391                paths
392                    .entry(route.uri.clone())
393                    .or_default()
394                    .insert(method.to_lowercase(), operation);
395            }
396        }
397
398        for (scope, description) in &self.scopes {
399            if description.is_empty() {
400                self.missing("scope", scope.clone(), "RequiresScope::describe".to_owned());
401            }
402        }
403        let own: Vec<String> = self
404            .settings()
405            .error_codes
406            .iter()
407            .filter(|code| code.description().is_empty())
408            .map(|code| code.code().to_owned())
409            .collect();
410        for code in own {
411            self.missing("error code", code, "ErrorCode::description".to_owned());
412        }
413
414        let mut schemas = self.error_schemas();
415        schemas.extend(std::mem::take(&mut self.schemas));
416        let mut components = Map::new();
417        components.insert("schemas".into(), Value::Object(schemas));
418        components.insert(
419            "responses".into(),
420            json!({ "Error": {
421                "description": "An error, in the JSON:API error format.",
422                "content": { JSON_API: { "schema": { "$ref": "#/components/schemas/ErrorDocument" } } },
423            }}),
424        );
425        if self.state.config.auth {
426            components.insert(
427                "securitySchemes".into(),
428                json!({ "bearer": {
429                    "type": "http",
430                    "scheme": "bearer",
431                    "description": format!("An API key (`fs_live_…`) or a token from another configured guard.{}", self.scope_list()),
432                }}),
433            );
434        }
435
436        let servers = self.settings().servers.clone().unwrap_or_else(|| {
437            vec![std::env::var("APP_URL").unwrap_or_else(|_| "http://localhost".to_owned())]
438        });
439        let mut document = Map::new();
440        document.insert("openapi".into(), json!("3.1.0"));
441        document.insert("info".into(), self.info());
442        document.insert(
443            "servers".into(),
444            Value::Array(
445                servers
446                    .into_iter()
447                    .map(|url| json!({ "url": url }))
448                    .collect(),
449            ),
450        );
451        document.insert(
452            "paths".into(),
453            Value::Object(
454                paths
455                    .into_iter()
456                    .map(|(path, ops)| (path, Value::Object(ops)))
457                    .collect(),
458            ),
459        );
460        document.insert("components".into(), Value::Object(components));
461        Value::Object(document)
462    }
463
464    fn info(&self) -> Value {
465        let settings = self.settings();
466        let mut info = Map::new();
467        let title = settings
468            .title
469            .clone()
470            .or_else(|| std::env::var("APP_NAME").ok())
471            .unwrap_or_else(|| "API".to_owned());
472        info.insert("title".into(), json!(title));
473        if let Some(description) = &settings.description {
474            info.insert("description".into(), json!(description));
475        }
476        let version = self
477            .version
478            .as_ref()
479            .map_or_else(|| settings.version.clone(), ToString::to_string);
480        info.insert("version".into(), json!(version));
481        if let (Some(registry), Some(version)) = (&self.state.registry, &self.version)
482            && let Some(deprecation) = registry.deprecation(version)
483        {
484            info.insert("x-deprecated".into(), json!(true));
485            if let Some(sunset) = deprecation.sunset {
486                info.insert("x-sunset".into(), json!(time::date(sunset)));
487            }
488        }
489        Value::Object(info)
490    }
491
492    fn operation(&mut self, method: &str, uri: &str, endpoint: &Endpoint) -> Value {
493        let route = format!("{method} {uri}");
494        let path_parameters: Vec<String> = uri
495            .split('/')
496            .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
497            .map(|name| name.trim_end_matches('?').to_owned())
498            .collect();
499        let resource = endpoint.resource.clone();
500        let collection = endpoint.collection;
501        let status = endpoint.status.unwrap_or(
502            if method == "POST" && resource.is_some() && !collection && path_parameters.is_empty() {
503                201
504            } else {
505                200
506            },
507        );
508        for (scope, description) in &endpoint.scopes {
509            let known = self.scopes.entry(scope.clone()).or_default();
510            if known.is_empty() {
511                known.clone_from(description);
512            }
513        }
514        let scopes: Vec<String> = endpoint
515            .scopes
516            .iter()
517            .map(|(scope, _)| scope.clone())
518            .collect();
519        let notes = endpoint.scopes.iter().map(|(scope, description)| {
520            if description.is_empty() {
521                format!("Requires the `{scope}` scope.")
522            } else {
523                format!("Requires the `{scope}` scope: {description}")
524            }
525        });
526        let description: Vec<String> = endpoint
527            .description
528            .clone()
529            .into_iter()
530            .chain(notes)
531            .collect();
532
533        let mut parameters: Vec<Value> = path_parameters
534            .iter()
535            .map(|name| json!({ "name": name, "in": "path", "required": true, "schema": { "type": "string" } }))
536            .collect();
537        #[cfg(feature = "database")]
538        let has_query = endpoint.query.is_some();
539        #[cfg(not(feature = "database"))]
540        let has_query = false;
541        #[cfg(feature = "database")]
542        if let Some(query) = &endpoint.query {
543            parameters.extend(self.query_parameters(query, collection, &route));
544        }
545        parameters.extend(self.header_parameters(method));
546
547        let mut responses = Map::new();
548        responses.insert(
549            status.to_string(),
550            self.success(status, resource.as_deref(), collection),
551        );
552        let config = &self.state.config;
553        let idempotent =
554            config.idempotency.enabled && config.idempotency.methods.iter().any(|m| m == method);
555        for (error, applies) in [
556            (400, has_query || self.version.is_some()),
557            (401, !scopes.is_empty()),
558            (403, !scopes.is_empty()),
559            (404, !path_parameters.is_empty()),
560            (409, idempotent),
561            (410, self.version.is_some()),
562            (422, endpoint.body.is_some()),
563            (429, config.rate_limit.enabled),
564        ] {
565            if applies {
566                responses.insert(
567                    error.to_string(),
568                    json!({ "$ref": "#/components/responses/Error" }),
569                );
570            }
571        }
572
573        if endpoint.summary.is_none() {
574            self.missing(
575                "endpoint",
576                format!("{method} {uri}"),
577                format!("Config::endpoint(\"{method} {uri}\")"),
578            );
579        }
580        if let Some((media, schema, _)) = &endpoint.body {
581            self.body_gaps(
582                media,
583                schema,
584                endpoint.resource.as_deref(),
585                &format!("{method} {uri}"),
586                &route,
587            );
588        }
589
590        let mut operation = Map::new();
591        operation.insert(
592            "operationId".into(),
593            json!(self.operation_id(endpoint, method, uri)),
594        );
595        operation.insert(
596            "summary".into(),
597            json!(
598                endpoint
599                    .summary
600                    .clone()
601                    .unwrap_or_else(|| format!("{method} {uri}"))
602            ),
603        );
604        if !description.is_empty() {
605            operation.insert("description".into(), json!(description.join("\n\n")));
606        }
607        operation.insert(
608            "tags".into(),
609            json!(if endpoint.tags.is_empty() {
610                tags(uri)
611            } else {
612                endpoint.tags.clone()
613            }),
614        );
615        if !parameters.is_empty() {
616            operation.insert("parameters".into(), Value::Array(parameters));
617        }
618        if let Some((media, schema, example)) = &endpoint.body {
619            let mut content = Map::new();
620            content.insert(
621                "schema".into(),
622                self.downgrade_body_schema(schema.clone(), &route),
623            );
624            if let Some(example) = example {
625                content.insert(
626                    "example".into(),
627                    self.downgrade_document(example.clone(), &route),
628                );
629            }
630            operation.insert(
631                "requestBody".into(),
632                json!({ "required": true, "content": { media.clone(): content } }),
633            );
634        }
635        operation.insert("responses".into(), Value::Object(responses));
636        if config.auth {
637            let security = if scopes.is_empty() {
638                json!([{}, { "bearer": [] }])
639            } else {
640                json!([{ "bearer": dedup(&scopes) }])
641            };
642            operation.insert("security".into(), security);
643        }
644        if !scopes.is_empty() {
645            operation.insert("x-required-scopes".into(), json!(dedup(&scopes)));
646        }
647        Value::Object(operation)
648    }
649
650    fn operation_id(&mut self, endpoint: &Endpoint, method: &str, uri: &str) -> String {
651        let base = endpoint
652            .operation_id
653            .clone()
654            .unwrap_or_else(|| camel(&format!("{} {uri}", method.to_lowercase())));
655        let mut id = base.clone();
656        let mut index = 2;
657        while self.operation_ids.contains(&id) {
658            id = camel(&format!("{} {base}", method.to_lowercase()));
659            if self.operation_ids.contains(&id) {
660                id = format!("{base}{index}");
661            }
662            index += 1;
663        }
664        self.operation_ids.push(id.clone());
665        id
666    }
667
668    /// A type or field as this version names it.
669    fn client_name(&self, kind: &str, field: Option<&str>, route: &str) -> String {
670        let (kind, field) = versioning::downgrade_name(&self.changes, route, kind, field);
671        field.unwrap_or(kind)
672    }
673
674    fn resource(&self, kind: &str) -> Option<&Resource> {
675        self.state.config.resource_named(kind)
676    }
677
678    #[cfg(feature = "database")]
679    fn query_parameters(&self, query: &ApiQuery, collection: bool, route: &str) -> Vec<Value> {
680        let kind = &query.kind;
681        let mut parameters = Vec::new();
682        if !query.includes.is_empty() {
683            let includes: Vec<String> = query
684                .includes
685                .iter()
686                .map(|path| self.client_path(kind, path, route))
687                .collect();
688            parameters.push(query_parameter(
689                "include",
690                &format!(
691                    "Related resources to include, comma-separated. Allowed: {}. Nested paths include their parents.",
692                    includes.join(", ")
693                ),
694                Some(with_parents(&includes)),
695            ));
696        }
697        for (fields_kind, fields) in &query.fields {
698            let client_kind = self.client_name(fields_kind, None, route);
699            let names: Vec<String> = fields
700                .iter()
701                .map(|field| self.client_name(fields_kind, Some(field), route))
702                .collect();
703            parameters.push(query_parameter(
704                &format!("fields[{client_kind}]"),
705                &format!(
706                    "Only these fields of {client_kind}, comma-separated: {}.",
707                    names.join(", ")
708                ),
709                Some(names),
710            ));
711        }
712        if !collection {
713            return parameters;
714        }
715        for filter in &query.filters {
716            let name = self.client_name(kind, Some(&filter.name), route);
717            let described = query
718                .descriptions
719                .iter()
720                .find(|(known, _)| *known == filter.name)
721                .map(|(_, text)| format!(" {text}"))
722                .unwrap_or_default();
723            if described.is_empty() {
724                self.missing(
725                    "filter",
726                    format!("{}.{name}", self.client_name(kind, None, route)),
727                    "ApiQuery::describe".to_owned(),
728                );
729            }
730            for operator in &filter.operators {
731                let (parameter, text) = match operator.as_str() {
732                    "eq" => (
733                        format!("filter[{name}]"),
734                        format!("Only results whose {name} matches."),
735                    ),
736                    "in" => (
737                        format!("filter[{name}][in]"),
738                        format!(
739                            "Only results whose {name} is one of these comma-separated values."
740                        ),
741                    ),
742                    other => (
743                        format!("filter[{name}][{other}]"),
744                        format!("Only results whose {name} is {other} the value."),
745                    ),
746                };
747                parameters.push(query_parameter(
748                    &parameter,
749                    &format!("{text}{described}"),
750                    (operator == "in").then(Vec::new),
751                ));
752            }
753        }
754        if !query.sorts.is_empty() {
755            let sorts: Vec<String> = query
756                .sorts
757                .iter()
758                .map(|sort| self.client_name(kind, Some(sort), route))
759                .collect();
760            let default = if query.default_sort.is_empty() {
761                "by ID".to_owned()
762            } else {
763                format!("by {}", query.default_sort)
764            };
765            let values = sorts
766                .iter()
767                .cloned()
768                .chain(sorts.iter().map(|sort| format!("-{sort}")))
769                .collect();
770            parameters.push(query_parameter(
771                "sort",
772                &format!(
773                    "Comma-separated fields, `-` for descending. Allowed: {}. Defaults to {default}.",
774                    sorts.join(", ")
775                ),
776                Some(values),
777            ));
778        }
779        let config = &self.state.config;
780        parameters.push(json!({ "name": "page[size]", "in": "query", "description": "Results per page.", "schema": {
781            "type": "integer", "minimum": 1, "maximum": config.max_page_size, "default": config.page_size,
782        }}));
783        match query.pagination {
784            Pagination::Offset { .. } => parameters.push(json!({
785                "name": "page[number]", "in": "query", "description": "The page, from 1.",
786                "schema": { "type": "integer", "minimum": 1, "default": 1 },
787            })),
788            Pagination::Cursor => {
789                parameters.push(query_parameter(
790                    "page[after]",
791                    "A cursor from `links.next`.",
792                    None,
793                ));
794                parameters.push(query_parameter(
795                    "page[before]",
796                    "A cursor from `links.prev`.",
797                    None,
798                ));
799            }
800        }
801        parameters
802    }
803
804    /// An include path as this version names its relationships.
805    #[cfg(feature = "database")]
806    fn client_path(&self, kind: &str, path: &str, route: &str) -> String {
807        let mut kind = kind.to_owned();
808        let mut names = Vec::new();
809        for segment in path.split('.') {
810            names.push(self.client_name(&kind, Some(segment), route));
811            match self
812                .resource(&kind)
813                .and_then(|resource| resource.relationships.iter().find(|r| r.name == segment))
814            {
815                Some(relationship) => kind.clone_from(&relationship.related),
816                None => break,
817            }
818        }
819        names.join(".")
820    }
821
822    fn header_parameters(&self, method: &str) -> Vec<Value> {
823        let mut parameters = Vec::new();
824        if let Some(version) = &self.version {
825            parameters.push(json!({
826                "name": "Api-Version", "in": "header",
827                "description": "The API version. Without it, requests get the version the API key is pinned to, or the default version.",
828                "schema": { "type": "string", "example": version.to_string() },
829            }));
830        }
831        let idempotency = &self.state.config.idempotency;
832        if idempotency.enabled && idempotency.methods.iter().any(|known| known == method) {
833            parameters.push(json!({
834                "name": "Idempotency-Key", "in": "header",
835                "description": "A unique value, such as a UUID, to retry the request safely.",
836                "schema": { "type": "string", "maxLength": 255 },
837            }));
838        }
839        parameters
840    }
841
842    fn success(&mut self, status: u16, resource: Option<&str>, collection: bool) -> Value {
843        if status == 204 {
844            return json!({ "description": "No content." });
845        }
846        let Some(kind) = resource else {
847            return json!({ "description": "Success.", "content": { "application/json": { "schema": { "type": "object" } } } });
848        };
849        let reference = self.resource_schema(kind);
850        let mut seen = Vec::new();
851        let mut included = self.included_refs(kind, &mut seen);
852        included.sort();
853        included.dedup();
854        let mut properties = Map::new();
855        properties.insert(
856            "data".into(),
857            if collection {
858                json!({ "type": "array", "items": { "$ref": reference } })
859            } else {
860                json!({ "$ref": reference })
861            },
862        );
863        if !included.is_empty() {
864            let items = if included.len() == 1 {
865                json!({ "$ref": included[0] })
866            } else {
867                json!({ "oneOf": included.iter().map(|r| json!({ "$ref": r })).collect::<Vec<_>>() })
868            };
869            properties.insert(
870                "included".into(),
871                json!({ "type": "array", "items": items }),
872            );
873        }
874        if collection {
875            let link = json!({ "type": ["string", "null"], "format": "uri" });
876            properties.insert(
877                "links".into(),
878                json!({ "type": "object", "properties": { "first": link, "prev": link, "next": link, "last": link } }),
879            );
880            properties.insert(
881                "meta".into(),
882                json!({ "type": "object", "properties": { "page": { "type": "object", "properties": {
883                    "size": { "type": "integer" }, "number": { "type": "integer" }, "total": { "type": "integer" },
884                }}}}),
885            );
886        }
887        json!({
888            "description": if collection { "A page of resources." } else { "The resource." },
889            "content": { JSON_API: { "schema": { "type": "object", "required": ["data"], "properties": properties } } },
890        })
891    }
892
893    /// Registers the schema for a resource type and returns its reference.
894    fn resource_schema(&mut self, kind: &str) -> String {
895        let client_kind = self.client_name(kind, None, "");
896        let name = format!("{}Resource", studly(&client_kind));
897        let reference = format!("#/components/schemas/{name}");
898        if self.schemas.contains_key(&name) {
899            return reference;
900        }
901        self.schemas.insert(name.clone(), json!({}));
902        let Some(resource) = self.resource(kind).cloned() else {
903            self.schemas.insert(
904                name,
905                json!({ "type": "object", "required": ["type", "id"], "properties": {
906                    "type": { "type": "string", "const": client_kind }, "id": { "type": "string" },
907                    "attributes": { "type": "object" }, "relationships": { "type": "object" },
908                    "links": { "type": "object" }, "meta": { "type": "object" },
909                }}),
910            );
911            return reference;
912        };
913
914        let mut attributes = Map::new();
915        for attribute in &resource.attributes {
916            let mut schema = match attribute.kind {
917                Kind::String => json!({ "type": "string" }),
918                Kind::Integer => json!({ "type": "integer" }),
919                Kind::Number => json!({ "type": "number" }),
920                Kind::Boolean => json!({ "type": "boolean" }),
921                Kind::Timestamp => json!({ "type": "string", "format": "date-time" }),
922                Kind::Json => json!({}),
923            };
924            if attribute.nullable
925                && let Some(kind) = schema.get("type").cloned()
926            {
927                schema["type"] = json!([kind, "null"]);
928            }
929            describe(&resource, &attribute.name, &mut schema);
930            self.field_gap(&resource, &client_kind, &attribute.name);
931            attributes.insert(self.client_name(kind, Some(&attribute.name), ""), schema);
932        }
933
934        let mut relationships = Map::new();
935        for relationship in &resource.relationships {
936            let identifier = json!({ "type": "object", "required": ["type", "id"], "properties": {
937                "type": { "type": "string", "const": self.client_name(&relationship.related, None, "") },
938                "id": { "type": "string" },
939            }});
940            let data = match relationship.link {
941                Link::HasMany { .. } => json!({ "type": "array", "items": identifier }),
942                Link::BelongsTo { .. } => json!({ "oneOf": [identifier, { "type": "null" }] }),
943            };
944            let mut schema = json!({ "type": "object", "properties": { "data": data } });
945            describe(&resource, &relationship.name, &mut schema);
946            self.field_gap(&resource, &client_kind, &relationship.name);
947            relationships.insert(self.client_name(kind, Some(&relationship.name), ""), schema);
948        }
949
950        let mut properties = Map::new();
951        properties.insert(
952            "type".into(),
953            json!({ "type": "string", "const": client_kind }),
954        );
955        properties.insert("id".into(), json!({ "type": "string" }));
956        properties.insert(
957            "attributes".into(),
958            json!({ "type": "object", "properties": attributes }),
959        );
960        if !relationships.is_empty() {
961            properties.insert(
962                "relationships".into(),
963                json!({ "type": "object", "properties": relationships }),
964            );
965        }
966        properties.insert("links".into(), json!({ "type": "object" }));
967        properties.insert("meta".into(), json!({ "type": "object" }));
968        self.schemas.insert(
969            name,
970            json!({ "type": "object", "required": ["type", "id"], "properties": properties }),
971        );
972        reference
973    }
974
975    fn field_gap(&self, resource: &Resource, client_kind: &str, field: &str) {
976        let described = resource
977            .descriptions
978            .iter()
979            .any(|(name, description)| name == field && !description.text.is_empty());
980        if !described {
981            self.missing(
982                "field",
983                format!(
984                    "{client_kind}.{}",
985                    self.client_name(&resource.kind, Some(field), "")
986                ),
987                format!("Resource \"{}\"", resource.kind),
988            );
989        }
990    }
991
992    /// Request body fields without a `description` in the declared schema.
993    fn body_gaps(
994        &self,
995        media: &str,
996        schema: &Value,
997        resource: Option<&str>,
998        key: &str,
999        route: &str,
1000    ) {
1001        let location = format!("the body of Config::endpoint(\"{key}\")");
1002        if media == JSON_API {
1003            let kind = resource
1004                .map(|kind| format!("{}.", self.client_name(kind, None, route)))
1005                .unwrap_or_default();
1006            for member in ["attributes", "relationships"] {
1007                if let Some(fields) = schema
1008                    .pointer(&format!("/properties/data/properties/{member}/properties"))
1009                    .and_then(Value::as_object)
1010                {
1011                    for (field, field_schema) in fields {
1012                        if field_schema.get("description").is_none() {
1013                            self.missing("field", format!("{kind}{field}"), location.clone());
1014                        }
1015                    }
1016                }
1017            }
1018        } else if let Some(fields) = schema.get("properties").and_then(Value::as_object) {
1019            for (field, field_schema) in fields {
1020                if field_schema.get("description").is_none() {
1021                    self.missing("field", field.clone(), location.clone());
1022                }
1023            }
1024        }
1025    }
1026
1027    /// References to the resources a document can include: those reachable through relationships.
1028    fn included_refs(&mut self, kind: &str, seen: &mut Vec<String>) -> Vec<String> {
1029        if seen.iter().any(|known| known == kind) {
1030            return Vec::new();
1031        }
1032        seen.push(kind.to_owned());
1033        let related: Vec<String> = self
1034            .resource(kind)
1035            .map(|resource| {
1036                resource
1037                    .relationships
1038                    .iter()
1039                    .map(|r| r.related.clone())
1040                    .collect()
1041            })
1042            .unwrap_or_default();
1043        let mut refs = Vec::new();
1044        for related in related {
1045            refs.push(self.resource_schema(&related));
1046            refs.extend(self.included_refs(&related, seen));
1047        }
1048        refs
1049    }
1050
1051    /// A JSON:API body schema with its attribute and relationship names as this version names
1052    /// them, for the type its `data.type` enum names.
1053    fn downgrade_body_schema(&self, mut schema: Value, route: &str) -> Value {
1054        let Some(kind) = schema
1055            .pointer("/properties/data/properties/type/enum/0")
1056            .and_then(Value::as_str)
1057            .map(str::to_owned)
1058        else {
1059            return schema;
1060        };
1061        for member in ["attributes", "relationships"] {
1062            let Some(section) =
1063                schema.pointer_mut(&format!("/properties/data/properties/{member}"))
1064            else {
1065                continue;
1066            };
1067            if let Some(Value::Object(properties)) = section.get_mut("properties") {
1068                let renamed: Map<String, Value> = std::mem::take(properties)
1069                    .into_iter()
1070                    .map(|(name, value)| (self.client_name(&kind, Some(&name), route), value))
1071                    .collect();
1072                *properties = renamed;
1073            }
1074            if let Some(Value::Array(required)) = section.get_mut("required") {
1075                for name in required.iter_mut() {
1076                    if let Some(text) = name.as_str() {
1077                        *name = json!(self.client_name(&kind, Some(text), route));
1078                    }
1079                }
1080            }
1081        }
1082        schema
1083    }
1084
1085    /// An example document in this version's shape, as a response would be.
1086    fn downgrade_document(&self, mut document: Value, route: &str) -> Value {
1087        let types = versioning::document::types(&document);
1088        for change in self.changes.iter().rev() {
1089            if versioning::applies_to(change.as_ref(), &types, route) {
1090                change.transform_response(&mut document);
1091            }
1092        }
1093        document
1094    }
1095
1096    fn error_schemas(&self) -> Map<String, Value> {
1097        let mut descriptions: BTreeMap<String, String> = BTreeMap::new();
1098        let package = ApiErrorCode::ALL.iter().map(|code| code as &dyn ErrorCode);
1099        let own = self.settings().error_codes.iter().map(AsRef::as_ref);
1100        // Each code once; an application's own code replaces the package's.
1101        for code in package.chain(own) {
1102            let text = if code.description().is_empty() {
1103                format!("{}.", code.title())
1104            } else {
1105                code.description().to_owned()
1106            };
1107            descriptions.insert(code.code().to_owned(), format!("{}: {text}", code.status()));
1108        }
1109        let codes: Vec<&String> = descriptions.keys().collect();
1110        let mut schemas = Map::new();
1111        schemas.insert("Error".into(), json!({ "type": "object", "required": ["status", "code", "title"], "properties": {
1112            "status": { "type": "string", "description": "The HTTP status code." },
1113            "code": { "type": "string", "enum": codes, "description": "A stable, machine-readable error code.", "x-enumDescriptions": descriptions },
1114            "title": { "type": "string" },
1115            "detail": { "type": "string" },
1116            "source": { "type": "object", "properties": {
1117                "pointer": { "type": "string", "description": "A JSON pointer to the request document member at fault." },
1118                "parameter": { "type": "string", "description": "The query parameter at fault." },
1119                "header": { "type": "string", "description": "The request header at fault." },
1120            }},
1121            "links": { "type": "object" },
1122            "meta": { "type": "object", "properties": { "request_id": { "type": "string" } } },
1123        }}));
1124        schemas.insert(
1125            "ErrorDocument".into(),
1126            json!({ "type": "object", "required": ["errors"], "properties": {
1127                "errors": { "type": "array", "items": { "$ref": "#/components/schemas/Error" } },
1128            }}),
1129        );
1130        schemas
1131    }
1132
1133    fn scope_list(&self) -> String {
1134        if self.scopes.is_empty() {
1135            return String::new();
1136        }
1137        let lines: Vec<String> = self
1138            .scopes
1139            .iter()
1140            .map(|(scope, description)| {
1141                if description.is_empty() {
1142                    format!("- `{scope}`")
1143                } else {
1144                    format!("- `{scope}`: {description}")
1145                }
1146            })
1147            .collect();
1148        format!("\n\nScopes:\n\n{}", lines.join("\n"))
1149    }
1150}
1151
1152/// Adds a field's description, and its values with what each means, to its schema.
1153fn describe(resource: &Resource, field: &str, schema: &mut Value) {
1154    let Some((_, description)) = resource.descriptions.iter().find(|(name, _)| name == field)
1155    else {
1156        return;
1157    };
1158    let Value::Object(schema) = schema else {
1159        return;
1160    };
1161    if !description.text.is_empty() {
1162        schema.insert("description".into(), json!(description.text));
1163    }
1164    if !description.values.is_empty() {
1165        schema.insert(
1166            "enum".into(),
1167            json!(
1168                description
1169                    .values
1170                    .iter()
1171                    .map(|(value, _)| value)
1172                    .collect::<Vec<_>>()
1173            ),
1174        );
1175        let meanings: Map<String, Value> = description
1176            .values
1177            .iter()
1178            .map(|(value, meaning)| (value.clone(), json!(meaning)))
1179            .collect();
1180        schema.insert("x-enumDescriptions".into(), Value::Object(meanings));
1181    }
1182}
1183
1184/// A query parameter. With values it is a comma-separated list, described as an array in form
1185/// style, not exploded, so generators can type it; empty values allow any items.
1186fn query_parameter(name: &str, description: &str, values: Option<Vec<String>>) -> Value {
1187    match values {
1188        None => {
1189            json!({ "name": name, "in": "query", "description": description, "schema": { "type": "string" } })
1190        }
1191        Some(values) => {
1192            let items = if values.is_empty() {
1193                json!({ "type": "string" })
1194            } else {
1195                json!({ "type": "string", "enum": values })
1196            };
1197            json!({ "name": name, "in": "query", "description": description, "style": "form", "explode": false, "schema": { "type": "array", "items": items } })
1198        }
1199    }
1200}
1201
1202/// Include paths and their parents, which are allowed too: `customer.orders` adds `customer`.
1203fn with_parents(paths: &[String]) -> Vec<String> {
1204    let mut all: Vec<String> = Vec::new();
1205    for path in paths {
1206        let segments: Vec<&str> = path.split('.').collect();
1207        for end in 1..=segments.len() {
1208            let parent = segments[..end].join(".");
1209            if !all.contains(&parent) {
1210                all.push(parent);
1211            }
1212        }
1213    }
1214    all
1215}
1216
1217fn dedup(values: &[String]) -> Vec<String> {
1218    let mut unique: Vec<String> = Vec::new();
1219    for value in values {
1220        if !unique.contains(value) {
1221            unique.push(value.clone());
1222        }
1223    }
1224    unique
1225}
1226
1227/// The path's first segment that is not a parameter or a version prefix, such as `orders`.
1228fn tags(path: &str) -> Vec<String> {
1229    path.trim_matches('/')
1230        .split('/')
1231        .find(|segment| {
1232            !segment.is_empty()
1233                && !segment.starts_with('{')
1234                && !(segment.len() > 1
1235                    && segment.starts_with('v')
1236                    && segment[1..].bytes().all(|b| b.is_ascii_digit()))
1237        })
1238        .map(|segment| vec![segment.to_owned()])
1239        .unwrap_or_default()
1240}
1241
1242/// Laravel's `Str::camel` of words split at anything that is not a letter or digit.
1243fn camel(text: &str) -> String {
1244    let mut out = String::new();
1245    for (index, word) in text
1246        .split(|c: char| !c.is_ascii_alphanumeric())
1247        .filter(|word| !word.is_empty())
1248        .enumerate()
1249    {
1250        let mut chars = word.chars();
1251        if let Some(first) = chars.next() {
1252            if index == 0 {
1253                out.push(first.to_ascii_lowercase());
1254            } else {
1255                out.push(first.to_ascii_uppercase());
1256            }
1257            out.push_str(chars.as_str());
1258        }
1259    }
1260    out
1261}
1262
1263/// Laravel's `Str::studly` of a type name, such as `order_lines` to `OrderLines`.
1264fn studly(kind: &str) -> String {
1265    kind.split(['-', '.', '_', ' '])
1266        .filter(|word| !word.is_empty())
1267        .map(|word| {
1268            let mut chars = word.chars();
1269            chars.next().map_or_else(String::new, |first| {
1270                first.to_ascii_uppercase().to_string() + chars.as_str()
1271            })
1272        })
1273        .collect()
1274}
1275
1276#[cfg(test)]
1277mod tests {
1278    use super::{camel, studly, tags, with_parents};
1279
1280    #[test]
1281    fn names_match_laravels_string_helpers() {
1282        assert_eq!(camel("get /v1/orders/{order}"), "getV1OrdersOrder");
1283        assert_eq!(camel("post orders.invoice"), "postOrdersInvoice");
1284        assert_eq!(studly("order-statuses"), "OrderStatuses");
1285        assert_eq!(tags("/v1/orders/{order}/cancel"), ["orders"]);
1286        assert_eq!(tags("/v12/{id}"), Vec::<String>::new());
1287        assert_eq!(
1288            with_parents(&["customer.orders".to_owned(), "customer".to_owned()]),
1289            ["customer", "customer.orders"]
1290        );
1291    }
1292}