slabs-html 0.2.0

Hypermedia SSR HTML battery: compile-time maud markup, Turbo-style HTML streams, layouts, and CSRF tokens
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Compile-time HTML rendering, document layout, HTMX helpers, and CSRF tokens for Slabs.
//!
//! This crate re-exports [`html!`] (aliased as `maud!` in `slabs::prelude`) so handlers build
//! auto-escaped HTML at compile time with zero runtime template engine.
//!
//! # Document layout
//!
//! [`document`] renders a complete HTML5 page with native view transitions
//! (`@view-transition { navigation: auto; }`), vendored Basecoat UI styles and scripts
//! (`/_slabs/vendor/basecoat.min.css` and `/_slabs/vendor/basecoat.min.js`), HTMX 2 with the SSE
//! and Idiomorph extensions (`hx-ext="morph"` on `<body>`), and Alpine.js 3.
//! Pass app-compiled Tailwind CSS v4 stylesheets (for example `&ctx.assets.stylesheet_urls()`) and
//! module scripts via the `stylesheets` and `scripts` arguments.
//! All frontend assets are self-hosted with zero CDN or Node runtime requirement.
//!
//! # HTMX helpers
//!
//! The [`htmx`] module emits standard `HX-*` headers and `hx-swap-oob` fragments:
//!
//! - [`htmx::redirect`] triggers a full navigation via `HX-Redirect`.
//! - [`htmx::with_trigger`] attaches an `HX-Trigger` client event header to a fragment.
//! - [`htmx::oob`], [`htmx::oob_replace`], and [`htmx::oob_delete`] wrap out-of-band DOM swaps.
//! - [`htmx::is_htmx`] and [`htmx::wants_json`] inspect `HX-Request` and `Accept` headers.
//!
//! # CSRF protection
//!
//! Use [`csrf_token`] to mint a signed token bound to a session scope and [`verify_csrf`] to check
//! submitted tokens.
//!
//! # Usage
//!
//! ```rust,no_run
//! use axum::http::HeaderMap;
//! use axum::response::IntoResponse;
//! use slabs_html::{document, html, htmx};
//!
//! fn render_notice(headers: &HeaderMap, styles: &[String]) -> axum::response::Response {
//!     let fragment = html! {
//!         p id="notice" { "Saved." }
//!     };
//!
//!     if htmx::is_htmx(headers) {
//!         return htmx::oob_replace("notice", fragment).into_response();
//!     }
//!
//!     document("Notice", styles, &[], fragment).into_response()
//! }
//! ```

use axum::response::{IntoResponse, Response};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use http::{header, HeaderMap, HeaderValue, StatusCode};
use serde::{Deserialize, Serialize};
use slabs_auth::Auth;
use slabs_core::{SlabError, SlabResult};

pub use maud::{html, Markup, PreEscaped, Render, DOCTYPE};

/// Cookie name used to store one-shot signed flash messages.
pub const FLASH_COOKIE_NAME: &str = "slabs_flash";

/// Severity level for a one-shot [`Flash`] banner message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FlashKind {
    /// Confirmation that an action succeeded.
    Success,
    /// Neutral informational notice.
    Info,
    /// Non-fatal cautionary notice.
    Warning,
    /// Error or failure notice.
    Error,
}

/// One-shot feedback message carried across a redirect in a signed cookie.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Flash {
    /// Severity level determining how the banner is styled.
    pub kind: FlashKind,
    /// Human-readable feedback text displayed to the user.
    pub message: String,
}

impl Flash {
    /// Create a [`FlashKind::Success`] flash message.
    #[must_use]
    pub fn success(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Success,
            message: message.into(),
        }
    }

    /// Create a [`FlashKind::Info`] flash message.
    #[must_use]
    pub fn info(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Info,
            message: message.into(),
        }
    }

    /// Create a [`FlashKind::Warning`] flash message.
    #[must_use]
    pub fn warning(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Warning,
            message: message.into(),
        }
    }

    /// Create a [`FlashKind::Error`] flash message.
    #[must_use]
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Error,
            message: message.into(),
        }
    }
}

/// Escape `&`, `<`, `>`, `"`, and `'` into HTML entities for manually assembled strings.
///
/// Prefer [`html!`] (`maud!` in `slabs::prelude`), which auto-escapes interpolated values at
/// compile time.
pub fn escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#x27;"),
            _ => out.push(ch),
        }
    }
    out
}

/// Standard HTMX 2 helpers for `HX-*` headers, `hx-swap-oob` fragments, and signed flash cookies.
pub mod htmx {
    use super::{
        header, html, Auth, Cookie, CookieJar, Flash, HeaderMap, HeaderValue, IntoResponse, Markup,
        PreEscaped, Response, SameSite, StatusCode, FLASH_COOKIE_NAME, URL_SAFE_NO_PAD,
    };
    use base64::Engine as _;

    /// Store a signed one-shot [`Flash`] message in the `slabs_flash` cookie (`HttpOnly`, `SameSite=Lax`, `Path=/`).
    #[must_use = "return the updated CookieJar in your response so the flash cookie is sent"]
    pub fn set_flash(auth: &Auth, jar: CookieJar, flash: &Flash) -> CookieJar {
        let Ok(json) = serde_json::to_vec(flash) else {
            return jar;
        };
        let encoded = URL_SAFE_NO_PAD.encode(json);
        let sig = auth.sign(&format!("flash:{encoded}"));
        let cookie = Cookie::build((FLASH_COOKIE_NAME, format!("{encoded}.{sig}")))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(auth.cookie_secure())
            .build();
        jar.add(cookie)
    }

    /// Read and verify the signed `slabs_flash` cookie, removing it from `jar` if present.
    ///
    /// Returns `(jar, None)` when the cookie is absent, malformed, or fails HMAC verification.
    #[must_use = "return the updated CookieJar in your response so the flash cookie is cleared"]
    pub fn take_flash(auth: &Auth, jar: CookieJar) -> (CookieJar, Option<Flash>) {
        let Some(raw) = jar.get(FLASH_COOKIE_NAME).map(|c| c.value().to_string()) else {
            return (jar, None);
        };

        let removal = Cookie::build((FLASH_COOKIE_NAME, ""))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(auth.cookie_secure())
            .build();
        let jar = jar.remove(removal);

        let flash = decode_flash(auth, &raw);
        (jar, flash)
    }

    /// Set a signed [`Flash`] cookie and return `303 See Other` with both `Location` and `HX-Redirect`.
    ///
    /// Works identically for standard browser form posts and HTMX requests. Falls back to `"/"`
    /// if `location` is not a valid HTTP header value.
    pub fn flash_redirect(auth: &Auth, jar: CookieJar, location: &str, flash: &Flash) -> Response {
        let jar = set_flash(auth, jar, flash);
        let target =
            HeaderValue::from_str(location).unwrap_or_else(|_| HeaderValue::from_static("/"));
        let mut headers = HeaderMap::new();
        headers.insert(header::LOCATION, target.clone());
        headers.insert("hx-redirect", target);
        (StatusCode::SEE_OTHER, jar, headers).into_response()
    }

    fn decode_flash(auth: &Auth, raw: &str) -> Option<Flash> {
        let (encoded, sig) = raw.split_once('.')?;
        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
            return None;
        }
        if !auth.verify_signature(&format!("flash:{encoded}"), sig) {
            return None;
        }
        let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
        serde_json::from_slice(&bytes).ok()
    }

    /// Return a `200 OK` response with `HX-Redirect` so HTMX performs a full navigation.
    ///
    /// Falls back to `"/"` if `path` is not a valid HTTP header value.
    pub fn redirect(path: &str) -> Response {
        let mut headers = HeaderMap::new();
        headers.insert(
            "hx-redirect",
            HeaderValue::from_str(path).unwrap_or_else(|_| HeaderValue::from_static("/")),
        );
        (StatusCode::OK, headers).into_response()
    }

    /// Return a `200 OK` HTML fragment with an `HX-Trigger` client event header.
    pub fn with_trigger(markup: Markup, event: &str) -> Response {
        let mut headers = HeaderMap::new();
        if let Ok(val) = HeaderValue::from_str(event) {
            headers.insert("hx-trigger", val);
        }
        (StatusCode::OK, headers, markup).into_response()
    }

    /// Wrap `inner` in an HTMX out-of-band swap container (`hx-swap-oob`).
    ///
    /// `swap` accepts any HTMX swap strategy such as `"beforeend"`, `"afterbegin"`, `"innerHTML"`,
    /// `"outerHTML"`, or `"true"`. A leading `#` on `target_id` is stripped automatically.
    pub fn oob(target_id: &str, swap: &str, inner: Markup) -> Markup {
        let clean_id = target_id.trim_start_matches('#');
        let attr = format!("{swap}:#{clean_id}");
        html! {
            div hx-swap-oob=(attr) { (PreEscaped(inner.into_string())) }
        }
    }

    /// Emit an HTMX out-of-band delete instruction (`hx-swap-oob="delete"`) for `target_id`.
    ///
    /// A leading `#` on `target_id` is stripped automatically.
    pub fn oob_delete(target_id: &str) -> Markup {
        let clean_id = target_id.trim_start_matches('#');
        html! {
            div id=(clean_id) hx-swap-oob="delete" {}
        }
    }

    /// Emit an HTMX out-of-band `outerHTML` swap targeting `target_id`.
    ///
    /// A leading `#` on `target_id` is stripped automatically.
    pub fn oob_replace(target_id: &str, inner: Markup) -> Markup {
        let clean_id = target_id.trim_start_matches('#');
        html! {
            div hx-swap-oob=(format!("outerHTML:#{clean_id}")) { (PreEscaped(inner.into_string())) }
        }
    }

    /// Return `true` when the request carries `HX-Request: true`.
    pub fn is_htmx(headers: &HeaderMap) -> bool {
        headers
            .get("hx-request")
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v == "true")
    }

    /// Return `true` when the `Accept` header contains `application/json`.
    pub fn wants_json(headers: &HeaderMap) -> bool {
        headers
            .get(header::ACCEPT)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.contains("application/json"))
    }
}

/// Render a Basecoat alert banner for an optional [`Flash`] message.
///
/// Renders a `<div class="alert" role="status">` when `flash` is `Some`, applying
/// `data-variant="destructive"` for [`FlashKind::Error`], or empty [`Markup`] when `None`.
#[must_use]
pub fn flash_banner(flash: Option<&Flash>) -> Markup {
    let Some(flash) = flash else {
        return html! {};
    };
    let (kind_str, variant) = match flash.kind {
        FlashKind::Success => ("success", None),
        FlashKind::Info => ("info", None),
        FlashKind::Warning => ("warning", None),
        FlashKind::Error => ("error", Some("destructive")),
    };
    html! {
        div class="alert" role="status" data-flash-kind=(kind_str) data-variant=[variant] {
            section {
                p { (flash.message) }
            }
        }
    }
}

/// Render a complete HTML5 page around `body` using compile-time [`Markup`].
///
/// Loads native view transitions (`@view-transition { navigation: auto; }`), PWA manifest and
/// theme metadata, Basecoat UI (`/_slabs/vendor/basecoat.min.css` and
/// `/_slabs/vendor/basecoat.min.js`), HTMX 2 with SSE and Idiomorph (`hx-ext="morph"` on
/// `<body>`), Alpine.js 3 (`/_slabs/vendor/alpine.min.js`), and a non-blocking service-worker
/// registration script at the end of `<body>`. Pass app-compiled Tailwind CSS v4 URLs in
/// `stylesheets` (such as `&ctx.assets.stylesheet_urls()`) and ES module URLs in `scripts`.
pub fn document(title: &str, stylesheets: &[String], scripts: &[String], body: Markup) -> Markup {
    html! {
        (DOCTYPE)
        html lang="en" class="dark" {
            head {
                meta charset="utf-8";
                meta name="viewport" content="width=device-width, initial-scale=1";
                link rel="manifest" href="/manifest.webmanifest";
                meta name="theme-color" content="#1a1b26";
                meta name="apple-mobile-web-app-capable" content="yes";
                title { (title) }
                style { (PreEscaped("@view-transition { navigation: auto; }")) }
                link rel="stylesheet" href="/_slabs/vendor/basecoat.min.css";
                @for href in stylesheets {
                    link rel="stylesheet" href=(href);
                }
                script src="/_slabs/vendor/htmx.min.js" defer {}
                script src="/_slabs/vendor/htmx-ext-sse.js" defer {}
                script src="/_slabs/vendor/idiomorph-ext.min.js" defer {}
                script src="/_slabs/vendor/basecoat.min.js" defer {}
                script src="/_slabs/vendor/alpine.min.js" defer {}
                @for src in scripts {
                    script type="module" src=(src) defer {}
                }
            }
            body class="min-h-screen bg-background text-foreground antialiased" hx-ext="morph" {
                (PreEscaped(body.into_string()))
                script {
                    (PreEscaped("if('serviceWorker' in navigator){window.addEventListener('load',function(){navigator.serviceWorker.register('/service-worker.js').catch(function(){});});}"))
                }
            }
        }
    }
}

/// Generate an HMAC-signed CSRF token bound to `scope` (such as a session ID or `"anon"`).
///
/// Returns `<nonce>.<signature>`, where the signature covers `"{scope}:{nonce}"`.
pub fn csrf_token(auth: &Auth, scope: &str) -> String {
    let nonce = slabs_core::id::new("csrf");
    let payload = format!("{scope}:{nonce}");
    let sig = auth.sign(&payload);
    format!("{nonce}.{sig}")
}

/// Verify a submitted CSRF token against `scope`.
///
/// Returns a `403 Forbidden` [`SlabError`] if the token format or signature is invalid.
pub fn verify_csrf(auth: &Auth, scope: &str, token: &str) -> SlabResult<()> {
    let Some((nonce, sig)) = token.split_once('.') else {
        return Err(SlabError::forbidden("invalid csrf token format"));
    };
    let payload = format!("{scope}:{nonce}");
    if auth.verify_signature(&payload, sig) {
        Ok(())
    } else {
        Err(SlabError::forbidden("csrf token verification failed"))
    }
}

/// Render untrusted `CommonMark` and GitHub-flavored Markdown into safe [`Markup`].
///
/// Enables tables, strikethrough, task lists, and heading attributes. Drops raw HTML blocks and
/// inline HTML tags so untrusted authors cannot inject `<script>`, `on*` event handlers, or
/// HTMX/Alpine attributes (`hx-*`, `x-data`, `x-init`). Rewrites unsafe link or image URL schemes
/// (`javascript:`, `vbscript:`, `data:`) to `"#"`.
pub fn render_markdown(input: &str) -> Markup {
    use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};

    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);

    let parser = Parser::new_ext(input, options).filter_map(|event| match event {
        Event::Html(_) | Event::InlineHtml(_) => None,
        Event::Start(Tag::Link {
            link_type,
            dest_url,
            title,
            id,
        }) => Some(Event::Start(Tag::Link {
            link_type,
            dest_url: sanitize_url(&dest_url).into(),
            title,
            id,
        })),
        Event::Start(Tag::Image {
            link_type,
            dest_url,
            title,
            id,
        }) => Some(Event::Start(Tag::Image {
            link_type,
            dest_url: sanitize_url(&dest_url).into(),
            title,
            id,
        })),
        Event::End(TagEnd::Link) => Some(Event::End(TagEnd::Link)),
        other => Some(other),
    });

    let mut html_out = String::with_capacity(input.len() + 64);
    pulldown_cmark::html::push_html(&mut html_out, parser);
    PreEscaped(html_out)
}

fn sanitize_url(raw: &str) -> String {
    let trimmed = raw.trim();
    let lower = trimmed.to_ascii_lowercase();
    if lower.starts_with("http://")
        || lower.starts_with("https://")
        || lower.starts_with("mailto:")
        || lower.starts_with('/')
        || lower.starts_with('#')
        || !lower.contains(':')
    {
        trimmed.to_string()
    } else {
        "#".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn render_markdown_renders_gfm_and_blocks_xss_and_htmx_injection() {
        let md = "# Title\n\n<script>alert(1)</script>\n<div hx-get=\"/evil\" x-init=\"pwn()\">bad</div>\n\n[ok](https://example.com) and [bad](javascript:alert(1))\n\n| A | B |\n| - | - |\n| 1 | 2 |\n";
        let rendered = render_markdown(md).into_string();
        assert!(rendered.contains("<h1>Title</h1>"));
        assert!(rendered.contains("<table>"));
        assert!(rendered.contains("href=\"https://example.com\""));
        assert!(!rendered.contains("<script>"));
        assert!(!rendered.contains("hx-get"));
        assert!(!rendered.contains("x-init"));
        assert!(!rendered.contains("javascript:"));
    }

    #[test]
    fn flash_roundtrip_and_one_shot_consumption() {
        let auth = Auth::for_signing("test-flash-secret-key", false);
        let flash = Flash::success("Saved changes.");

        let jar = htmx::set_flash(&auth, CookieJar::new(), &flash);
        let cookie = jar.get(FLASH_COOKIE_NAME).expect("flash cookie set");
        assert_eq!(cookie.path(), Some("/"));
        assert_eq!(cookie.http_only(), Some(true));
        assert_eq!(cookie.same_site(), Some(SameSite::Lax));

        let (jar, taken) = htmx::take_flash(&auth, jar);
        assert_eq!(taken, Some(flash));
        assert!(jar.get(FLASH_COOKIE_NAME).is_none());

        let (_jar, second) = htmx::take_flash(&auth, jar);
        assert_eq!(second, None);
    }

    #[test]
    fn flash_rejects_tampered_cookie_and_clears_it() {
        let auth = Auth::for_signing("test-flash-secret-key", false);
        let jar = htmx::set_flash(&auth, CookieJar::new(), &Flash::info("Hello"));
        let raw = jar.get(FLASH_COOKIE_NAME).unwrap().value().to_string();
        let (encoded, sig) = raw.split_once('.').unwrap();
        let flipped = if sig.starts_with('0') { '1' } else { '0' };
        let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);

        let mut tampered_headers = HeaderMap::new();
        tampered_headers.insert(
            header::COOKIE,
            HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={tampered}")).unwrap(),
        );
        let tampered_jar = CookieJar::from_headers(&tampered_headers);

        let (cleared_jar, taken) = htmx::take_flash(&auth, tampered_jar);
        assert_eq!(taken, None);
        assert!(cleared_jar.get(FLASH_COOKIE_NAME).is_none());
    }

    #[test]
    fn flash_redirect_sets_see_other_location_hx_redirect_and_cookie() {
        let auth = Auth::for_signing("test-flash-secret-key", false);
        let resp = htmx::flash_redirect(
            &auth,
            CookieJar::new(),
            "/rooms",
            &Flash::warning("Room archived"),
        );

        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            resp.headers()
                .get(header::LOCATION)
                .and_then(|v| v.to_str().ok()),
            Some("/rooms")
        );
        assert_eq!(
            resp.headers()
                .get("hx-redirect")
                .and_then(|v| v.to_str().ok()),
            Some("/rooms")
        );
        let set_cookie = resp
            .headers()
            .get(header::SET_COOKIE)
            .and_then(|v| v.to_str().ok())
            .expect("Set-Cookie header present");
        assert!(set_cookie.contains("slabs_flash="));
        assert!(set_cookie.contains("HttpOnly"));
        assert!(set_cookie.contains("SameSite=Lax"));
        assert!(set_cookie.contains("Path=/"));
    }

    #[test]
    fn flash_banner_renders_accessible_alert_or_empty() {
        assert_eq!(flash_banner(None).into_string(), "");

        let ok_html = flash_banner(Some(&Flash::success("Item <saved>"))).into_string();
        assert!(ok_html.contains("class=\"alert\""));
        assert!(ok_html.contains("role=\"status\""));
        assert!(ok_html.contains("data-flash-kind=\"success\""));
        assert!(ok_html.contains("Item &lt;saved&gt;"));
        assert!(!ok_html.contains("data-variant=\"destructive\""));

        let err_html = flash_banner(Some(&Flash::error("Failed"))).into_string();
        assert!(err_html.contains("role=\"status\""));
        assert!(err_html.contains("data-flash-kind=\"error\""));
        assert!(err_html.contains("data-variant=\"destructive\""));
        assert!(err_html.contains("Failed"));
    }

    #[test]
    fn document_includes_pwa_head_tags_and_service_worker_registration() {
        let rendered = document("Campfire", &[], &[], html! { main { "Hi" } }).into_string();
        assert!(rendered.contains("<link rel=\"manifest\" href=\"/manifest.webmanifest\">"));
        assert!(rendered.contains("<meta name=\"theme-color\" content=\"#1a1b26\">"));
        assert!(rendered.contains("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"));
        assert!(rendered.contains(
            "if('serviceWorker' in navigator){window.addEventListener('load',function(){navigator.serviceWorker.register('/service-worker.js').catch(function(){});});}"
        ));
    }
}