Skip to main content

fusion_stack/
docs.rs

1//! The API reference and changelog pages, as the PHP package's `DocsController` serves them at
2//! `api.docs.path`: Scalar (or Redoc) over the OpenAPI document of each offered version, and
3//! the changelog rendered from each version's changes.
4
5use laravel::http::{Request, Response};
6use serde_json::{Map, Value, json};
7
8use crate::errors::{ApiError, ApiErrorCode};
9use crate::versioning::{ApiVersion, HEADER, VersionChange};
10use crate::{State, time};
11
12const SCALAR_CSS: &str = include_str!("../resources/docs/scalar.css");
13
14// Each renderer's script at a fixed version, with the hash of that file, as the PHP package's
15// `api.docs` has them. The page runs whatever these URLs serve, so the browser checks the hash.
16const SCALAR_URL: &str =
17    "https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.86.1/dist/browser/standalone.js";
18const SCALAR_INTEGRITY: &str =
19    "sha384-v1p/+OBXCeOjkLrNN8uhg7ZOlv9i0cnHZzvLyo2n6tk/P+xsqdL3Lqj89PT3V1Ly";
20const REDOC_URL: &str = "https://cdn.redoc.ly/redoc/v2.5.4/bundles/redoc.standalone.js";
21const REDOC_INTEGRITY: &str =
22    "sha384-w447zOpYfw/1Tv/5AK9NfHTlQIqE3RVR6KY62jCyy9zNDgO64cMwGGP1Fj0zJVf5";
23
24/// Which page renders the reference.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Renderer {
27    /// Scalar, which switches between versions itself.
28    Scalar,
29    /// Redoc, which shows one version, with a select to reload the page with another.
30    Redoc,
31}
32
33/// `api.docs` in the PHP package. Mount the pages with [`routes`].
34#[derive(Clone)]
35pub struct Docs {
36    pub(crate) path: String,
37    renderer: Renderer,
38    scalar_url: String,
39    scalar_integrity: Option<String>,
40    scalar_config: Map<String, Value>,
41    redoc_url: String,
42    redoc_integrity: Option<String>,
43    pub(crate) lint_fails: bool,
44}
45
46impl Default for Docs {
47    fn default() -> Self {
48        Self {
49            path: "docs".to_owned(),
50            renderer: Renderer::Scalar,
51            scalar_url: SCALAR_URL.to_owned(),
52            scalar_integrity: Some(SCALAR_INTEGRITY.to_owned()),
53            scalar_config: Map::new(),
54            redoc_url: REDOC_URL.to_owned(),
55            redoc_integrity: Some(REDOC_INTEGRITY.to_owned()),
56            lint_fails: false,
57        }
58    }
59}
60
61impl Docs {
62    /// The defaults: Scalar at `/docs`.
63    #[must_use]
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    /// Where [`routes`] mounts the pages (`api.docs.path`, `docs`).
69    #[must_use]
70    pub fn path(mut self, path: &str) -> Self {
71        path.trim_matches('/').clone_into(&mut self.path);
72        self
73    }
74
75    /// Which page renders the reference (`api.docs.renderer`).
76    #[must_use]
77    pub const fn renderer(mut self, renderer: Renderer) -> Self {
78        self.renderer = renderer;
79        self
80    }
81
82    /// Where Scalar is loaded from (`api.docs.scalar.url`): a fixed version on jsDelivr unless
83    /// set. The default's hash does not fit another file, so this loads `url` unchecked until
84    /// [`scalar_integrity`](Self::scalar_integrity) gives its hash.
85    #[must_use]
86    pub fn scalar_url(mut self, url: &str) -> Self {
87        url.clone_into(&mut self.scalar_url);
88        self.scalar_integrity = None;
89        self
90    }
91
92    /// The hash of the file at [`scalar_url`](Self::scalar_url), such as `sha384-…`
93    /// (`api.docs.scalar.integrity`). The browser only runs the script when it matches, so a
94    /// file that changed on the CDN never runs on the reference. Call it after `scalar_url`.
95    #[must_use]
96    pub fn scalar_integrity(mut self, integrity: &str) -> Self {
97        self.scalar_integrity = Some(integrity.to_owned());
98        self
99    }
100
101    /// Options for `Scalar.createApiReference` (`api.docs.scalar.config`), such as `theme`.
102    /// Without a `theme` or `customCss`, the reference uses Fusion Stack's colours. Scalar's
103    /// developer toolbar and AI assistant are off unless set here.
104    #[must_use]
105    pub fn scalar_config(mut self, config: Map<String, Value>) -> Self {
106        self.scalar_config = config;
107        self
108    }
109
110    /// Whether `api:docs:lint` exits with an error when anything has no description, for CI
111    /// (`api.docs.lint` set to `fail`). It only warns by default.
112    #[must_use]
113    pub const fn lint_fails(mut self, fails: bool) -> Self {
114        self.lint_fails = fails;
115        self
116    }
117
118    /// Where Redoc is loaded from (`api.docs.redoc.url`): a fixed version on Redoc's CDN unless
119    /// set. The default's hash does not fit another file, so this loads `url` unchecked until
120    /// [`redoc_integrity`](Self::redoc_integrity) gives its hash.
121    #[must_use]
122    pub fn redoc_url(mut self, url: &str) -> Self {
123        url.clone_into(&mut self.redoc_url);
124        self.redoc_integrity = None;
125        self
126    }
127
128    /// The hash of the file at [`redoc_url`](Self::redoc_url), such as `sha384-…`
129    /// (`api.docs.redoc.integrity`). Call it after `redoc_url`.
130    #[must_use]
131    pub fn redoc_integrity(mut self, integrity: &str) -> Self {
132        self.redoc_integrity = Some(integrity.to_owned());
133        self
134    }
135}
136
137/// Registers the reference at `/{path}`, each version's document at `/{path}/openapi.json`, and
138/// the changelog at `/{path}/changelog`. Wrap the call in a group to add middleware, such as
139/// authentication.
140pub fn routes(route: &mut laravel::routing::Router) {
141    let path = crate::STATE.get().map_or_else(
142        || Docs::default().path,
143        |state| state.config.docs.path.clone(),
144    );
145    route.prefix(&format!("/{path}")).group(|route| {
146        route.get("/", reference);
147        route.get("/openapi.json", openapi);
148        route.get("/changelog", changelog);
149    });
150}
151
152/// A version the docs offer.
153struct Offered {
154    version: ApiVersion,
155    label: String,
156    latest: bool,
157}
158
159/// A document the reference lists.
160struct Document {
161    title: String,
162    slug: String,
163    url: String,
164    default: bool,
165}
166
167fn state() -> laravel::Result<&'static State> {
168    crate::STATE.get().map(AsRef::as_ref).ok_or_else(|| {
169        ApiError::new(
170            ApiErrorCode::ServerError,
171            "Fusion Stack is not registered as a service provider.",
172        )
173        .into_error()
174    })
175}
176
177/// The released versions that are not retired, newest first, or `None` while versioning is off.
178fn offered(state: &State) -> Option<Vec<Offered>> {
179    let registry = state.registry.as_ref()?;
180    let now = time::now();
181    Some(
182        registry
183            .history()
184            .into_iter()
185            .filter(|(version, _)| {
186                !registry.is_unreleased(version) && !registry.is_retired(version, now)
187            })
188            .map(|(version, _)| {
189                let latest = *version == registry.latest;
190                // Short enough for Scalar's switcher, which truncates longer labels.
191                let note = if latest {
192                    Some("latest".to_owned())
193                } else {
194                    registry.deprecation(version).map(|deprecation| {
195                        deprecation.sunset.map_or_else(
196                            || "deprecated".to_owned(),
197                            |sunset| format!("sunset {}", time::date(sunset)),
198                        )
199                    })
200                };
201                Offered {
202                    version: version.clone(),
203                    label: note
204                        .map_or_else(|| version.to_string(), |note| format!("{version} ({note})")),
205                    latest,
206                }
207            })
208            .collect(),
209    )
210}
211
212fn url(request: &Request, state: &State, page: &str) -> String {
213    let base = format!("{}/{}", request.origin(), state.config.docs.path);
214    if page.is_empty() {
215        base
216    } else {
217        format!("{base}/{page}")
218    }
219}
220
221fn title(state: &State) -> String {
222    state
223        .config
224        .openapi
225        .title
226        .clone()
227        .or_else(|| std::env::var("APP_NAME").ok())
228        .filter(|title| !title.is_empty())
229        .unwrap_or_else(|| "API reference".to_owned())
230}
231
232/// `2026-11-30.atlas` as `2026-11-30-atlas`, for Scalar's URLs and the Redoc select.
233fn slug(version: &str) -> String {
234    let mut slug = String::new();
235    for character in version.to_lowercase().chars() {
236        if character.is_alphanumeric() {
237            slug.push(character);
238        } else if !slug.is_empty() && !slug.ends_with('-') {
239            slug.push('-');
240        }
241    }
242    slug.trim_end_matches('-').to_owned()
243}
244
245/// The reference page.
246///
247/// # Errors
248///
249/// When Fusion Stack is not registered.
250pub async fn reference(request: Request) -> laravel::Result<Response> {
251    let state = state()?;
252    let openapi = url(&request, state, "openapi.json");
253    let documents: Vec<Document> = match offered(state) {
254        None => vec![Document {
255            title: title(state),
256            slug: "api".to_owned(),
257            url: openapi,
258            default: true,
259        }],
260        Some(versions) => versions
261            .into_iter()
262            .map(|entry| Document {
263                slug: slug(&entry.version.to_string()),
264                url: format!(
265                    "{openapi}?version={}",
266                    query_value(&entry.version.to_string())
267                ),
268                title: entry.label,
269                default: entry.latest,
270            })
271            .collect(),
272    };
273    Ok(match state.config.docs.renderer {
274        Renderer::Scalar => scalar(state, &documents),
275        Renderer::Redoc => redoc(&request, state, &documents),
276    })
277}
278
279/// The OpenAPI document for `?version=`, or the latest, with a link to the changelog.
280///
281/// # Errors
282///
283/// A 404 for a version the docs do not offer.
284pub async fn openapi(request: Request) -> laravel::Result<Response> {
285    let state = state()?;
286    let version = match offered(state) {
287        None => None,
288        Some(versions) => {
289            let query = crate::query_string::parse(request.uri().query().unwrap_or_default());
290            match query.get("version").and_then(Value::as_str) {
291                None => None,
292                Some(requested) => {
293                    let named = state.registry.as_ref().and_then(|r| r.named(requested));
294                    if !versions
295                        .iter()
296                        .any(|entry| Some(&entry.version) == named.as_ref())
297                    {
298                        return Err(ApiError::new(
299                            ApiErrorCode::NotFound,
300                            format!("The docs do not offer API version [{requested}]."),
301                        )
302                        .into_error());
303                    }
304                    Some(requested.to_owned())
305                }
306            }
307        }
308    };
309    let mut document = crate::openapi::generate(version.as_deref())
310        .map_err(|message| ApiError::new(ApiErrorCode::NotFound, message).into_error())?;
311    if state.registry.is_some()
312        && let Some(info) = document.get_mut("info").and_then(Value::as_object_mut)
313    {
314        let link = format!(
315            "[Changelog]({}): what changed in each version.",
316            url(&request, state, "changelog")
317        );
318        let description = info
319            .get("description")
320            .and_then(Value::as_str)
321            .unwrap_or_default();
322        info.insert(
323            "description".into(),
324            json!(format!("{description}\n\n{link}").trim()),
325        );
326    }
327    let mut http = laravel::axum::http::Response::new(laravel::axum::body::Body::from(
328        serde_json::to_vec(&document).unwrap_or_default(),
329    ));
330    http.headers_mut().insert(
331        laravel::http::header::CONTENT_TYPE,
332        laravel::http::HeaderValue::from_static("application/json"),
333    );
334    Ok(Response::from_http(http))
335}
336
337/// The changelog page.
338///
339/// # Errors
340///
341/// A 404 while versioning is off.
342pub async fn changelog(request: Request) -> laravel::Result<Response> {
343    let state = state()?;
344    if state.registry.is_none() {
345        return Err(ApiError::new(
346            ApiErrorCode::NotFound,
347            "The API has no versions, so it has no changelog.",
348        )
349        .into_error());
350    }
351    let html = markdown_to_html(&markdown(false));
352    let back = escape(&url(&request, state, ""));
353    Ok(page(
354        &format!("Changelog · {}", title(state)),
355        &format!(
356            r#"<style>
357  :root {{ color-scheme: light dark; --fg: #1c1326; --muted: #5f5468; --line: #efe4db; --code: #fbf6f2; --link: #c2410c; --bg: #ffffff; }}
358  @media (prefers-color-scheme: dark) {{ :root {{ --fg: #f6eefb; --muted: #b3a6c0; --line: #2a2035; --code: #1d1528; --link: #ff8a5c; --bg: #140e1c; }} }}
359  html {{ background: var(--bg); }}
360  body {{ font: 16px/1.65 system-ui, sans-serif; color: var(--fg); max-width: 46rem; margin: 2.5rem auto; padding: 0 1.25rem; }}
361  h1 {{ letter-spacing: -0.02em; }}
362  h2 {{ margin-top: 2rem; padding-top: 1rem; border-top: 1px solid var(--line); letter-spacing: -0.01em; }}
363  li {{ color: var(--muted); }}
364  code {{ font: 0.875em ui-monospace, monospace; color: var(--fg); background: var(--code); padding: 0.1em 0.35em; border-radius: 4px; }}
365  a {{ color: var(--link); text-underline-offset: 3px; }}
366</style>
367<nav><a href="{back}">← API reference</a></nav>
368{html}"#
369        ),
370    ))
371}
372
373/// The changelog as Markdown: each released version's breaking changes, newest first, as the
374/// PHP package's `api:changelog` writes it. `unreleased` also lists versions newer than the
375/// latest. Empty while versioning is off or Fusion Stack is not registered.
376#[must_use]
377pub fn markdown(unreleased: bool) -> String {
378    let Some(registry) = crate::STATE.get().and_then(|state| state.registry.as_ref()) else {
379        return String::new();
380    };
381    let now = time::now();
382    let history: Vec<_> = registry
383        .history()
384        .into_iter()
385        .filter(|(version, _)| unreleased || !registry.is_unreleased(version))
386        .collect();
387    let guide = registry
388        .upgrade_guide_url
389        .as_ref()
390        .map(|url| format!(" See the [upgrade guide]({url})."))
391        .unwrap_or_default();
392    let mut lines = vec![
393        "# Changelog".to_owned(),
394        String::new(),
395        format!(
396            "Breaking changes in each API version, newest first. Requests choose a version with the `{}` header.{guide}",
397            header_name()
398        ),
399    ];
400    let oldest = history.len().saturating_sub(1);
401    for (index, (version, changes)) in history.iter().enumerate() {
402        lines.extend([String::new(), format!("## {version}"), String::new()]);
403        let status = registry.status(version, now);
404        if !status.is_empty() {
405            let mut characters = status.chars();
406            let first = characters
407                .next()
408                .map(|c| c.to_uppercase().collect::<String>());
409            lines.extend([
410                format!("_{}{}._", first.unwrap_or_default(), characters.as_str()),
411                String::new(),
412            ]);
413        }
414        if changes.is_empty() {
415            lines.push(
416                if index == oldest {
417                    "The first version."
418                } else {
419                    "No breaking changes."
420                }
421                .to_owned(),
422            );
423            continue;
424        }
425        for change in *changes {
426            lines.push(format!("- {}", describe(change.as_ref(), version)));
427        }
428    }
429    lines.join("\n") + "\n"
430}
431
432/// `Api-Version`, as the header is written.
433fn header_name() -> String {
434    HEADER
435        .split('-')
436        .map(|part| {
437            let mut characters = part.chars();
438            characters
439                .next()
440                .map(|first| first.to_uppercase().chain(characters).collect::<String>())
441                .unwrap_or_default()
442        })
443        .collect::<Vec<_>>()
444        .join("-")
445}
446
447/// The change's description, or what it does to routes when it has none.
448fn describe(change: &dyn VersionChange, version: &ApiVersion) -> String {
449    if !change.description().is_empty() {
450        return change.description().to_owned();
451    }
452    let route = |pattern: &&str| {
453        if pattern.contains('*') {
454            format!("`{pattern}`")
455        } else {
456            (*pattern).to_owned()
457        }
458    };
459    let legacy: Vec<&str> = change
460        .legacy_handlers()
461        .into_iter()
462        .map(|(pattern, _)| pattern)
463        .collect();
464    let parts: Vec<String> = change
465        .added_routes()
466        .iter()
467        .map(|r| format!("Added {}", route(r)))
468        .chain(
469            change
470                .removed_routes()
471                .iter()
472                .map(|r| format!("Removed {}", route(r))),
473        )
474        .chain(
475            change
476                .unavailable_to_older_versions()
477                .iter()
478                .map(|r| format!("{} is unavailable to versions before {version}", route(r))),
479        )
480        .chain(legacy.iter().map(|r| {
481            format!(
482                "{} changed; versions before {version} keep the previous behaviour",
483                route(r)
484            )
485        }))
486        .collect();
487    if parts.is_empty() {
488        "A breaking change.".to_owned()
489    } else {
490        parts.join("; ")
491    }
492}
493
494/// Markdown as HTML, dropping raw HTML and links to anything but web and mail addresses, as
495/// the PHP package renders it with `html_input: strip` and `allow_unsafe_links: false`.
496fn markdown_to_html(markdown: &str) -> String {
497    use pulldown_cmark::{Event, Parser, Tag};
498
499    let events = Parser::new(markdown).filter_map(|event| match event {
500        Event::Html(_) | Event::InlineHtml(_) => None,
501        Event::Start(Tag::Link {
502            link_type,
503            dest_url,
504            title,
505            id,
506        }) => {
507            let lower = dest_url.to_lowercase();
508            let unsafe_link = ["javascript:", "vbscript:", "file:", "data:"]
509                .iter()
510                .any(|scheme| lower.starts_with(scheme));
511            Some(Event::Start(Tag::Link {
512                link_type,
513                dest_url: if unsafe_link { "".into() } else { dest_url },
514                title,
515                id,
516            }))
517        }
518        event => Some(event),
519    });
520    let mut html = String::new();
521    pulldown_cmark::html::push_html(&mut html, events);
522    html
523}
524
525fn scalar(state: &State, documents: &[Document]) -> Response {
526    let options = &state.config.docs.scalar_config;
527    // The page is the application's own, so Scalar's toolbar and AI assistant, which promote
528    // Scalar's services, are off unless the application turns them on.
529    let mut configuration = Map::new();
530    configuration.insert("showDeveloperTools".into(), json!("never"));
531    configuration.insert("agent".into(), json!({ "disabled": true }));
532    if !options.contains_key("theme") && !options.contains_key("customCss") {
533        configuration.insert("theme".into(), json!("none"));
534        configuration.insert("customCss".into(), json!(SCALAR_CSS));
535    }
536    for (key, value) in options {
537        configuration.insert(key.clone(), value.clone());
538    }
539    configuration.insert(
540        "sources".into(),
541        Value::Array(
542            documents
543                .iter()
544                .map(|document| {
545                    json!({ "title": document.title, "slug": document.slug, "url": document.url, "default": document.default })
546                })
547                .collect(),
548        ),
549    );
550    configuration.insert("metaData".into(), json!({ "title": title(state) }));
551    let docs = &state.config.docs;
552    let script = script(&docs.scalar_url, docs.scalar_integrity.as_deref());
553    let configuration = json_in_html(&Value::Object(configuration));
554    page(
555        &title(state),
556        &format!(
557            "<div id=\"app\"></div>\n{script}\n<script>Scalar.createApiReference('#app', {configuration})</script>"
558        ),
559    )
560}
561
562/// Redoc shows one document, so a select reloads the page with another version.
563fn redoc(request: &Request, state: &State, documents: &[Document]) -> Response {
564    let query = crate::query_string::parse(request.uri().query().unwrap_or_default());
565    let requested = query.get("version").and_then(Value::as_str).map(slug);
566    let selected = documents
567        .iter()
568        .position(|document| Some(&document.slug) == requested.as_ref())
569        .or_else(|| documents.iter().position(|document| document.default))
570        .unwrap_or(0);
571    let options: String = documents
572        .iter()
573        .enumerate()
574        .map(|(index, document)| {
575            format!(
576                "<option value=\"{}\"{}>{}</option>",
577                escape(&document.slug),
578                if index == selected { " selected" } else { "" },
579                escape(&document.title)
580            )
581        })
582        .collect();
583    let switcher = if state.registry.is_none() {
584        String::new()
585    } else {
586        format!(
587            "<label>Version <select onchange=\"location.search = '?version=' + encodeURIComponent(this.value)\">{options}</select></label>\n<a href=\"{}\">Changelog</a>",
588            escape(&url(request, state, "changelog"))
589        )
590    };
591    let url = json_in_html(&json!(documents.get(selected).map(|d| d.url.as_str())));
592    let docs = &state.config.docs;
593    let script = script(&docs.redoc_url, docs.redoc_integrity.as_deref());
594    page(
595        &title(state),
596        &format!(
597            r#"<style>
598  body {{ margin: 0; }}
599  header {{ display: flex; gap: 1.25rem; align-items: center; padding: 0.6rem 1.25rem; border-bottom: 1px solid #efe4db; font: 14px system-ui, sans-serif; color: #1c1326; }}
600  header a {{ color: #c2410c; }}
601  header strong {{ margin-right: auto; }}
602</style>
603<header><strong>{}</strong>{switcher}</header>
604<div id="redoc"></div>
605{script}
606<script>Redoc.init({url}, {{}}, document.getElementById('redoc'))</script>"#,
607            escape(&title(state))
608        ),
609    )
610}
611
612/// The element that loads a renderer's script. With an `integrity` hash the browser refuses a
613/// file that is not the one the hash was made from.
614fn script(url: &str, integrity: Option<&str>) -> String {
615    match integrity.filter(|integrity| !integrity.is_empty()) {
616        Some(integrity) => format!(
617            "<script src=\"{}\" integrity=\"{}\" crossorigin=\"anonymous\"></script>",
618            escape(url),
619            escape(integrity)
620        ),
621        None => format!("<script src=\"{}\"></script>", escape(url)),
622    }
623}
624
625fn page(title: &str, body: &str) -> Response {
626    let mut http = laravel::axum::http::Response::new(laravel::axum::body::Body::from(format!(
627        "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <title>{}</title>\n</head>\n<body>\n{body}\n</body>\n</html>",
628        escape(title)
629    )));
630    http.headers_mut().insert(
631        laravel::http::header::CONTENT_TYPE,
632        laravel::http::HeaderValue::from_static("text/html; charset=utf-8"),
633    );
634    Response::from_http(http)
635}
636
637/// JSON safe inside a `<script>` element, as PHP's `JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS`.
638/// These characters appear only inside JSON strings, so escaping them everywhere is safe.
639fn json_in_html(value: &Value) -> String {
640    serde_json::to_string(value)
641        .unwrap_or_default()
642        .replace('<', "\\u003C")
643        .replace('>', "\\u003E")
644        .replace('&', "\\u0026")
645        .replace('\'', "\\u0027")
646}
647
648/// HTML-escapes text, as Laravel's `e()`.
649fn escape(text: &str) -> String {
650    text.replace('&', "&amp;")
651        .replace('<', "&lt;")
652        .replace('>', "&gt;")
653        .replace('"', "&quot;")
654        .replace('\'', "&#039;")
655}
656
657/// A query string value, with the characters that would end it encoded.
658fn query_value(value: &str) -> String {
659    value
660        .replace('%', "%25")
661        .replace('&', "%26")
662        .replace('#', "%23")
663        .replace('+', "%2B")
664        .replace(' ', "%20")
665}
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670
671    #[test]
672    fn slugs_versions_for_scalar() {
673        assert_eq!(slug("2026-11-30.atlas"), "2026-11-30-atlas");
674        assert_eq!(slug("2026-06-01"), "2026-06-01");
675    }
676
677    #[test]
678    fn strips_raw_html_and_unsafe_links() {
679        let html = markdown_to_html(
680            "<script>alert(1)</script>\n\n- a <img src=x onerror=alert(1)> [x](javascript:alert(1)) [y](https://e.org)",
681        );
682        assert!(!html.contains("<script>"), "{html}");
683        assert!(!html.contains("<img"), "{html}");
684        assert!(!html.contains("javascript:"), "{html}");
685        assert!(html.contains(r#"<a href="https://e.org">y</a>"#), "{html}");
686    }
687
688    #[test]
689    fn loads_scripts_at_a_fixed_version_with_their_hash() {
690        let docs = Docs::new();
691        assert_eq!(
692            script(&docs.scalar_url, docs.scalar_integrity.as_deref()),
693            format!(
694                r#"<script src="{SCALAR_URL}" integrity="{SCALAR_INTEGRITY}" crossorigin="anonymous"></script>"#
695            )
696        );
697        assert_eq!(
698            script(&docs.redoc_url, docs.redoc_integrity.as_deref()),
699            format!(
700                r#"<script src="{REDOC_URL}" integrity="{REDOC_INTEGRITY}" crossorigin="anonymous"></script>"#
701            )
702        );
703        // A version in the URL, so the CDN cannot serve a newer file at it.
704        assert!(SCALAR_URL.contains("@1.86.1/") && REDOC_URL.contains("/v2.5.4/"));
705    }
706
707    #[test]
708    fn another_url_is_not_checked_against_the_default_hash() {
709        // The default hash would make the browser refuse any other file.
710        let docs = Docs::new()
711            .scalar_url("/vendor/scalar.js?a=1&b=2")
712            .redoc_url("/vendor/redoc.js");
713        assert_eq!(
714            script(&docs.scalar_url, docs.scalar_integrity.as_deref()),
715            r#"<script src="/vendor/scalar.js?a=1&amp;b=2"></script>"#
716        );
717        assert_eq!(
718            script(&docs.redoc_url, docs.redoc_integrity.as_deref()),
719            r#"<script src="/vendor/redoc.js"></script>"#
720        );
721
722        let docs = docs
723            .scalar_integrity("sha384-own")
724            .redoc_integrity("sha384-\"own");
725        assert_eq!(
726            script(&docs.scalar_url, docs.scalar_integrity.as_deref()),
727            r#"<script src="/vendor/scalar.js?a=1&amp;b=2" integrity="sha384-own" crossorigin="anonymous"></script>"#
728        );
729        assert_eq!(
730            script(&docs.redoc_url, docs.redoc_integrity.as_deref()),
731            r#"<script src="/vendor/redoc.js" integrity="sha384-&quot;own" crossorigin="anonymous"></script>"#
732        );
733    }
734
735    #[test]
736    fn keeps_json_inside_script_elements() {
737        assert_eq!(
738            json_in_html(&json!({ "css": "</style><b>'&'" })),
739            r#"{"css":"\u003C/style\u003E\u003Cb\u003E\u0027\u0026\u0027"}"#
740        );
741    }
742}