autumn-web 0.7.0

An opinionated, convention-over-configuration web framework for Rust
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! Fingerprinted asset pipeline for cache-busted static file delivery.
//!
//! In release builds, [`asset_url`] resolves a logical asset path to a
//! content-hashed URL using the manifest written by `autumn build --release`.
//! In development, it returns the plain `/static/...` URL so edits are
//! immediately visible without a build step.
//!
//! # Usage
//!
//! ```rust,ignore
//! use autumn_web::prelude::*;
//!
//! html! {
//!     link rel="stylesheet" href=(asset_url("css/autumn.css"));
//!     // debug:   /static/css/autumn.css
//!     // release: /static/css/autumn.a1b2c3d4.css
//! }
//! ```
//!
//! # Manifest
//!
//! The manifest is written by `autumn build --release` to
//! `static/.autumn-manifest.json`.  It maps logical paths (relative to
//! `static/`) to fingerprinted paths:
//!
//! ```json
//! {
//!   "version": "1",
//!   "files": {
//!     "css/autumn.css": "css/autumn.a1b2c3d4.css"
//!   }
//! }
//! ```

use std::collections::HashMap;
use std::sync::OnceLock;
#[cfg(feature = "embed-assets")]
use std::sync::RwLock;

/// Filename of the fingerprint manifest within the `static/` tree.
#[cfg(any(not(debug_assertions), feature = "embed-assets"))]
const ASSET_MANIFEST_FILE: &str = ".autumn-manifest.json";

/// On-disk format of `static/.autumn-manifest.json`.
#[cfg(any(not(debug_assertions), feature = "embed-assets"))]
#[derive(Debug, serde::Deserialize)]
struct AssetManifest {
    files: HashMap<String, String>,
}

#[cfg(not(debug_assertions))]
static ASSET_MANIFEST: OnceLock<Option<AssetManifest>> = OnceLock::new();

#[cfg(not(debug_assertions))]
fn load_manifest() -> &'static Option<AssetManifest> {
    ASSET_MANIFEST.get_or_init(|| {
        let manifest_path =
            crate::app::project_dir("static", &crate::config::OsEnv).join(ASSET_MANIFEST_FILE);
        let contents = std::fs::read_to_string(manifest_path).ok()?;
        serde_json::from_str(&contents).ok()
    })
}

// ── Vendor asset manifest (.autumn-assets.json) ──────────────────────────────

/// Filename of the vendor asset manifest within the `static/` tree.
pub(crate) const VENDOR_MANIFEST_FILE: &str = ".autumn-assets.json";

/// A single vendored JS dependency recorded in the vendor manifest.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct VendorAsset {
    /// Pinned version string (e.g. `"2.0.4"`).
    pub version: String,
    /// Original download URL.
    pub source: String,
    /// Path relative to `static/` where the file is vendored (e.g. `"js/htmx.min.js"`).
    pub file: String,
    /// `sha384-<base64>` Subresource Integrity hash.
    pub integrity: String,
}

/// On-disk format of `static/.autumn-assets.json`.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VendorManifest {
    /// Format version; currently `"1"`.
    pub version: String,
    /// Map from logical name (e.g. `"htmx"`) to asset metadata.
    pub assets: HashMap<String, VendorAsset>,
}

static VENDOR_MANIFEST: OnceLock<Option<VendorManifest>> = OnceLock::new();

fn load_vendor_manifest() -> Option<&'static VendorManifest> {
    VENDOR_MANIFEST
        .get_or_init(|| {
            // In single-binary builds the embedded dir is the sole source of truth.
            #[cfg(feature = "embed-assets")]
            if embedded_static_dir().is_some() {
                return load_embedded_vendor_manifest();
            }
            let manifest_path =
                crate::app::project_dir("static", &crate::config::OsEnv).join(VENDOR_MANIFEST_FILE);
            let contents = std::fs::read_to_string(manifest_path).ok()?;
            serde_json::from_str(&contents).ok()
        })
        .as_ref()
}

/// Returns `true` when htmx has been pinned via `autumn assets add htmx@…`.
///
/// The router uses this to skip the built-in embedded htmx handler so the
/// vendored file (and its pinned integrity hash) is served by `ServeDir` instead.
pub(crate) fn htmx_is_vendored() -> bool {
    load_vendor_manifest().is_some_and(|m| m.assets.contains_key("htmx"))
}

#[cfg(feature = "embed-assets")]
fn load_embedded_vendor_manifest() -> Option<VendorManifest> {
    EMBEDDED_STATIC
        .get()?
        .0
        .get_file(VENDOR_MANIFEST_FILE)
        .and_then(include_dir::File::contents_utf8)
        .and_then(|s| serde_json::from_str(s).ok())
}

/// Render a `<script>` tag for a vendored JS dependency.
///
/// Resolves the asset URL through [`asset_url`] (fingerprinted in release,
/// plain in dev) and emits `integrity` + `crossorigin="anonymous"` for SRI.
#[cfg(feature = "maud")]
fn render_javascript_tag(asset: &VendorAsset) -> maud::Markup {
    maud::html! {
        script
            src=(asset_url(&asset.file))
            integrity=(asset.integrity)
            crossorigin="anonymous"
            {}
    }
}

/// Render a `<script>` tag for a named vendored JS dependency.
///
/// Looks up `name` in `static/.autumn-assets.json` and emits:
/// ```html
/// <script src="{url}" integrity="{sri}" crossorigin="anonymous"></script>
/// ```
/// where `{url}` is fingerprinted in release builds and plain in dev.
///
/// When `name` is not found in the manifest the helper logs a `tracing::warn!`
/// and returns a visible HTML comment so the gap is discoverable in View Source.
/// In debug builds a `<script>console.error(…)</script>` is also emitted so the
/// error appears in the browser `DevTools` console.
///
/// # Example
///
/// ```rust,ignore
/// use autumn_web::prelude::*;
///
/// html! {
///     head {
///         (javascript_include_tag("htmx"))
///     }
/// }
/// ```
#[cfg(feature = "maud")]
#[must_use]
#[allow(clippy::option_if_let_else)] // side-effecting else branch makes map_or_else harder to read
pub fn javascript_include_tag(name: &str) -> maud::Markup {
    if let Some(asset) = load_vendor_manifest().and_then(|m| m.assets.get(name)) {
        render_javascript_tag(asset)
    } else {
        tracing::warn!(
            asset = name,
            "javascript_include_tag: asset not found in {}; \
             run `autumn assets add {name}@<version>` to pin it",
            VENDOR_MANIFEST_FILE,
        );
        missing_asset_markup(name)
    }
}

/// Diagnostic markup returned when [`javascript_include_tag`] cannot find a
/// named asset.  Always contains an HTML comment visible in View Source; in
/// debug builds also fires `console.error` so `DevTools` catches the gap early.
#[cfg(feature = "maud")]
fn missing_asset_markup(name: &str) -> maud::Markup {
    let comment = format!(
        "<!-- autumn: asset '{name}' not found in {VENDOR_MANIFEST_FILE}; \
         run `autumn assets add {name}@<version>` -->"
    );
    if cfg!(debug_assertions) {
        let console_err = format!(
            "console.error('[autumn] asset not found: {name} \
             \u{2014} run autumn assets add {name}@<version>');"
        );
        maud::html! {
            (maud::PreEscaped(comment))
            script { (maud::PreEscaped(console_err)) }
        }
    } else {
        maud::html! { (maud::PreEscaped(comment)) }
    }
}

// ── Embedded assets (feature = "embed-assets") ──────────────────────────────
//
// When the app registers an embedded `static/` tree via
// [`AppBuilder::embedded_static`](crate::app::AppBuilder::embedded_static),
// the binary is fully self-contained: `asset_url`/`is_manifest_asset` resolve
// against the manifest baked into the binary (no disk read) and `/static/*`
// is served from the embedded bytes. Both the manifest and the files come from
// the *same* build, so fingerprint-vs-manifest drift is impossible.
//
// The embedded path is active regardless of `debug_assertions`: it engages only
// once a dir is registered, so dev builds (which never register one) are
// unaffected and keep serving from disk for hot-reload.

/// A `static/` directory embedded into the binary at compile time.
///
/// Produced by [`embed_static!`](crate::embed_static) and handed to
/// [`AppBuilder::embedded_static`](crate::app::AppBuilder::embedded_static).
#[cfg(feature = "embed-assets")]
#[derive(Clone, Copy)]
pub struct EmbeddedStaticDir(pub &'static include_dir::Dir<'static>);

#[cfg(feature = "embed-assets")]
impl std::fmt::Debug for EmbeddedStaticDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EmbeddedStaticDir")
            .field("path", &self.0.path())
            .finish()
    }
}

#[cfg(feature = "embed-assets")]
static EMBEDDED_STATIC: OnceLock<EmbeddedStaticDir> = OnceLock::new();

#[cfg(feature = "embed-assets")]
static EMBEDDED_MANIFEST: OnceLock<Option<AssetManifest>> = OnceLock::new();

/// Register the embedded `static/` tree as the process-wide asset source.
///
/// Parses the embedded `.autumn-manifest.json` so [`asset_url`] and
/// [`is_manifest_asset`] resolve against it. Called by the framework during
/// `AppBuilder::run` before the router is built; calling it more than once is a
/// no-op (the first registration wins).
#[cfg(feature = "embed-assets")]
pub fn register_embedded_static(dir: EmbeddedStaticDir) {
    let _ = EMBEDDED_STATIC.set(dir);
    let _ = EMBEDDED_MANIFEST.set(
        dir.0
            .get_file(ASSET_MANIFEST_FILE)
            .and_then(include_dir::File::contents_utf8)
            .and_then(|s| serde_json::from_str::<AssetManifest>(s).ok()),
    );
}

/// The registered embedded `static/` dir, if [`register_embedded_static`] ran.
#[cfg(feature = "embed-assets")]
#[must_use]
pub fn embedded_static_dir() -> Option<EmbeddedStaticDir> {
    EMBEDDED_STATIC.get().copied()
}

/// Look up a logical asset path in the embedded manifest, returning the
/// fingerprinted path when present.
#[cfg(feature = "embed-assets")]
fn embedded_manifest_lookup(path: &str) -> Option<String> {
    EMBEDDED_MANIFEST.get()?.as_ref()?.files.get(path).cloned()
}

/// `true` if `rel_path` is a fingerprinted value in the embedded manifest.
#[cfg(feature = "embed-assets")]
fn embedded_is_manifest_asset(rel_path: &str) -> bool {
    EMBEDDED_MANIFEST
        .get()
        .and_then(Option::as_ref)
        .is_some_and(|m| m.files.values().any(|v| v == rel_path))
}

/// Return the URL for a static asset, fingerprinted in release builds.
///
/// - **Debug builds** (`cargo run` / `autumn dev`): returns `/static/{path}`
///   with no manifest lookup so edits are always visible immediately.
/// - **Release builds** (`cargo build --release`): looks up `path` in the
///   manifest produced by `autumn build --release` and returns the
///   content-hashed URL (e.g. `/static/css/autumn.a1b2c3d4.css`).
///   Falls back to `/static/{path}` when the manifest is absent or the path
///   is not listed, so the app keeps serving without fingerprinted assets.
///
/// # Example
///
/// ```rust,ignore
/// link rel="stylesheet" href=(asset_url("css/autumn.css"));
/// // debug:   /static/css/autumn.css
/// // release: /static/css/autumn.a1b2c3d4.css
/// ```
#[must_use]
pub fn asset_url(path: &str) -> String {
    // When an embedded `static/` tree is registered (single-binary build), the
    // embedded manifest is the *only* source of truth — assets are served from
    // the binary, so a miss means the asset isn't fingerprinted and should use
    // the plain embedded path. Never fall through to a disk sidecar manifest,
    // which could otherwise point at a hashed file that was never baked in.
    #[cfg(feature = "embed-assets")]
    {
        if embedded_static_dir().is_some() {
            return embedded_manifest_lookup(path)
                .map_or_else(|| format!("/static/{path}"), |fp| format!("/static/{fp}"));
        }
    }
    #[cfg(debug_assertions)]
    {
        format!("/static/{path}")
    }
    #[cfg(not(debug_assertions))]
    {
        if let Some(manifest) = load_manifest() {
            if let Some(fingerprinted) = manifest.files.get(path) {
                return format!("/static/{fingerprinted}");
            }
        }
        format!("/static/{path}")
    }
}

/// Returns `true` if `rel_path` (the portion of the URL after `/static/`) is
/// listed as a fingerprinted value in the release asset manifest.
///
/// Gating the `immutable` cache header on manifest membership rather than
/// filename pattern alone ensures that user-authored assets whose names
/// happen to match `<stem>.<8hex>.<ext>` (e.g. `vendor.deadbeef.js`) are
/// never given a year-long cache lifetime.
///
/// Always returns `false` in debug builds — the manifest does not exist there.
// Not `const fn`: the body branches on build profile/feature, and the
// release/embedded arms perform non-const lookups.
#[allow(clippy::missing_const_for_fn)]
pub(crate) fn is_manifest_asset(rel_path: &str) -> bool {
    // When an embedded `static/` tree is registered, its manifest is the sole
    // authority for the immutable-cache decision (and is reachable in debug
    // builds too); never consult a disk sidecar manifest in that case.
    #[cfg(feature = "embed-assets")]
    {
        if embedded_static_dir().is_some() {
            return embedded_is_manifest_asset(rel_path);
        }
    }
    #[cfg(not(debug_assertions))]
    {
        load_manifest()
            .as_ref()
            .is_some_and(|m| m.files.values().any(|v| v == rel_path))
    }
    #[cfg(debug_assertions)]
    {
        let _ = rel_path;
        false
    }
}

/// Returns `true` if the URI path segment looks like a fingerprinted asset
/// by filename convention (`<stem>.<8-hex-chars>.<ext>`).
///
/// Only used in tests; the cache middleware uses [`is_manifest_asset`] for
/// production cache decisions.
#[cfg(test)]
pub(crate) fn is_fingerprinted_path(uri_path: &str) -> bool {
    let filename = uri_path.rsplit('/').next().unwrap_or("");
    let parts: Vec<&str> = filename.split('.').collect();
    if parts.len() < 3 {
        return false;
    }
    let hash_candidate = parts[parts.len() - 2];
    hash_candidate.len() == 8
        && hash_candidate
            .bytes()
            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// Cache-control policy for `/static/*` responses.
///
/// Fingerprinted assets (members of the manifest, embedded or on-disk) get a
/// year-long `immutable` lifetime; everything else gets `must-revalidate` so
/// returning visitors always pick up the latest file after a deploy. Manifest
/// membership — rather than filename pattern — gates the `immutable` policy so a
/// user-authored `vendor.deadbeef.js` is never frozen for a year.
///
/// Applied as a middleware layer over both the on-disk (`ServeDir`) and the
/// embedded static-serving paths so the policy is identical regardless of where
/// the bytes come from.
pub async fn asset_cache_control(
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let header = cache_control_for_request(&req);
    let mut resp = next.run(req).await;
    apply_cache_control(&mut resp, header);
    resp
}

/// `Cache-Control` value a `/static/...` request's successful response should
/// carry, or `None` for any request that is not a static-asset request.
///
/// Resolved from the request *before* the response exists so the decision costs
/// no allocation: the old form owned the path in a `String` for the whole
/// downstream call, purely to re-read it afterwards.
///
/// One consequence of resolving up front: [`is_manifest_asset`] now runs for
/// every `/static/...` request rather than only for successful ones, so a `404`
/// for a missing asset can be the call that populates the process-lifetime
/// manifest `OnceLock`. The manifest is written by `autumn build` before the
/// server starts and never changes while it runs, so *which* request warms it
/// is not observable; non-asset requests are unaffected either way, since
/// `strip_prefix` returns `None` before any manifest lookup happens.
fn cache_control_for_request<B>(req: &axum::http::Request<B>) -> Option<&'static str> {
    req.uri().path().strip_prefix("/static/").map(|rel| {
        if is_manifest_asset(rel) {
            "public, max-age=31536000, immutable"
        } else {
            "public, max-age=0, must-revalidate"
        }
    })
}

/// Stamp `header` onto `resp` when the request was for a static asset and the
/// response succeeded. Shared by [`asset_cache_control`] and
/// [`AssetCacheControlFuture`] so the two forms cannot drift.
fn apply_cache_control<B>(resp: &mut axum::http::Response<B>, header: Option<&'static str>) {
    if let Some(header) = header
        && resp.status().is_success()
    {
        resp.headers_mut().insert(
            http::header::CACHE_CONTROL,
            http::HeaderValue::from_static(header),
        );
    }
}

/// Tower [`Layer`](tower::Layer) form of [`asset_cache_control`], used by the
/// framework's ingress stack.
///
/// The `axum::middleware::from_fn` this replaces cost a `Box::pin` of the
/// wrapped async block on every request — every request in the app, not just
/// requests for `/static/...`, because this layer is applied globally — plus a
/// deep clone of the erased service beneath it and a `String` clone of the
/// request path (issue #2214). None of that survives here: the header is a
/// `&'static str` decided up front and the future is the inner service's own.
#[derive(Clone, Copy, Debug)]
pub(crate) struct AssetCacheControlLayer;

impl<S> tower::Layer<S> for AssetCacheControlLayer {
    type Service = AssetCacheControlService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        AssetCacheControlService { inner }
    }
}

/// Tower [`Service`](tower::Service) produced by [`AssetCacheControlLayer`].
#[derive(Clone, Debug)]
pub(crate) struct AssetCacheControlService<S> {
    inner: S,
}

impl<S, ReqBody, ResBody> tower::Service<axum::http::Request<ReqBody>>
    for AssetCacheControlService<S>
where
    S: tower::Service<axum::http::Request<ReqBody>, Response = axum::http::Response<ResBody>>,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = AssetCacheControlFuture<S::Future>;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: axum::http::Request<ReqBody>) -> Self::Future {
        AssetCacheControlFuture {
            header: cache_control_for_request(&req),
            inner: self.inner.call(req),
        }
    }
}

pin_project_lite::pin_project! {
    /// Future returned by [`AssetCacheControlService`]: the inner service's own
    /// future plus the `&'static str` header to stamp on its response.
    pub(crate) struct AssetCacheControlFuture<F> {
        #[pin]
        inner: F,
        header: Option<&'static str>,
    }
}

impl<F, ResBody, E> std::future::Future for AssetCacheControlFuture<F>
where
    F: std::future::Future<Output = Result<axum::http::Response<ResBody>, E>>,
{
    type Output = Result<axum::http::Response<ResBody>, E>;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        let this = self.project();
        let mut response = std::task::ready!(this.inner.poll(cx))?;
        apply_cache_control(&mut response, *this.header);
        std::task::Poll::Ready(Ok(response))
    }
}

/// Best-effort `Content-Type` for a static/embedded asset, derived from its
/// extension. Covers the closed set of asset types Autumn apps ship; unknown
/// extensions fall back to `application/octet-stream`.
///
/// Used both by the embedded-asset serving path and by the static-first
/// (SSG/ISR) middleware, which serves manifest-backed files from `dist/` and
/// needs an accurate MIME type so the response compression layer only encodes
/// compressible content types (and skips binary assets).
#[must_use]
pub(crate) fn content_type_for(path: &str) -> &'static str {
    content_type_for_opt(path).unwrap_or("application/octet-stream")
}

/// Like [`content_type_for`], but returns `Some(mime)` **only** when the final
/// path segment carries a *recognized* asset extension, and `None` otherwise
/// (extensionless input, or an extension not in the closed asset set).
///
/// This lets callers distinguish "the route names a real asset type" from "no
/// idea, fall back to octet-stream". The static-first middleware relies on that
/// distinction: a generated page whose slug merely *contains* a dot
/// (`/posts/release.v1`, `/users/alice@example.com`) has an unrecognized
/// trailing extension, so it returns `None` here and the caller derives the
/// MIME from the served `index.html` file instead of mislabeling HTML as
/// `application/octet-stream`.
///
/// Only the last `/`-delimited segment's extension is inspected, so dotted
/// *ancestor* directories never affect the result.
#[must_use]
pub(crate) fn content_type_for_opt(path: &str) -> Option<&'static str> {
    // Lowercase the extension into a small stack buffer (extensions are short
    // and ASCII) to avoid a per-request heap allocation on the serving path.
    let raw = path
        .rsplit('/')
        .next()
        .unwrap_or("")
        .rsplit_once('.')
        .map_or("", |(_, e)| e);
    let mut buf = [0u8; 8];
    let ext = if raw.is_ascii() && raw.len() <= buf.len() {
        buf[..raw.len()].copy_from_slice(raw.as_bytes());
        buf[..raw.len()].make_ascii_lowercase();
        std::str::from_utf8(&buf[..raw.len()]).unwrap_or("")
    } else {
        "" // unknown long/non-ASCII extension → unrecognized
    };
    let mime = match ext {
        "css" => "text/css; charset=utf-8",
        "js" | "mjs" => "text/javascript; charset=utf-8",
        "json" | "map" => "application/json",
        "html" | "htm" => "text/html; charset=utf-8",
        "txt" => "text/plain; charset=utf-8",
        "xml" => "application/xml",
        "svg" => "image/svg+xml",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "avif" => "image/avif",
        "ico" => "image/x-icon",
        "woff" => "font/woff",
        "woff2" => "font/woff2",
        "ttf" => "font/ttf",
        "otf" => "font/otf",
        "wasm" => "application/wasm",
        _ => return None,
    };
    Some(mime)
}

/// Process-wide cache of computed embedded-asset `ETag`s, keyed by the stable
/// `&'static` byte pointer of the asset's contents.
///
/// SHA-256-hashing a whole asset on every request is a hot-path CPU cost for
/// large full `GET`s. Embedded asset bytes are `&'static`, so their start
/// pointer is a stable per-asset identity for the process lifetime — memoizing
/// the tag against it computes the hash once per asset and reuses it thereafter.
/// Two empty assets can share a pointer, but their content hash is identical, so
/// a collision still returns the correct tag.
#[cfg(feature = "embed-assets")]
static EMBEDDED_ETAG_CACHE: OnceLock<RwLock<HashMap<usize, crate::etag::ETag>>> = OnceLock::new();

/// Return the strong content-hash `ETag` for an embedded asset, computing it on
/// the first serve and reusing the cached value thereafter.
///
/// Preserves the exact tag value/format produced by [`embedded_etag`] so
/// `If-Range` validation is unchanged.
#[cfg(feature = "embed-assets")]
fn embedded_etag_cached(bytes: &[u8]) -> crate::etag::ETag {
    let key = bytes.as_ptr() as usize;
    let cache = EMBEDDED_ETAG_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
    if let Some(etag) = cache.read().unwrap().get(&key) {
        return etag.clone();
    }
    let etag = embedded_etag(bytes);
    cache.write().unwrap().insert(key, etag.clone());
    etag
}

/// Derive a stable **strong** `ETag` from an embedded asset's bytes.
///
/// A content hash gives embedded assets a meaningful `If-Range` (and
/// conditional-GET) validator: the tag changes only when the bytes change, so a
/// client's cached range stays valid across restarts of the same binary.
#[cfg(feature = "embed-assets")]
fn embedded_etag(bytes: &[u8]) -> crate::etag::ETag {
    use sha2::{Digest as _, Sha256};
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let digest = Sha256::digest(bytes);
    let mut hex = String::with_capacity(digest.len() * 2);
    for b in digest {
        hex.push(HEX[(b >> 4) as usize] as char);
        hex.push(HEX[(b & 0x0f) as usize] as char);
    }
    crate::etag::ETag::strong(hex)
}

/// Serve a single file from the registered embedded `static/` tree.
///
/// Returns `404` for path-traversal attempts, the framework manifest
/// (`.autumn-manifest.json`, which must never be exposed), missing files, or
/// when no embedded dir is registered. Other files — including legitimate
/// dotfile assets — are served, matching the on-disk `ServeDir` behavior.
///
/// Honours HTTP `Range` requests (RFC 7233) via [`crate::range`]: a satisfiable
/// `Range` yields `206 Partial Content` with `Content-Range`, an unsatisfiable
/// one yields `416`, and every response advertises `Accept-Ranges: bytes`. A
/// strong content-hash `ETag` gates `If-Range`.
#[cfg(feature = "embed-assets")]
fn embedded_response(rel_path: &str, req_headers: &http::HeaderMap) -> axum::response::Response {
    use axum::response::IntoResponse;

    let is_traversal = rel_path
        .split('/')
        .any(|seg| seg.is_empty() || seg == "." || seg == "..");
    let is_manifest = rel_path
        .rsplit('/')
        .next()
        .is_some_and(|name| name == ASSET_MANIFEST_FILE || name == VENDOR_MANIFEST_FILE);
    if is_traversal || is_manifest {
        return http::StatusCode::NOT_FOUND.into_response();
    }
    let Some(dir) = embedded_static_dir() else {
        return http::StatusCode::NOT_FOUND.into_response();
    };
    dir.0.get_file(rel_path).map_or_else(
        || http::StatusCode::NOT_FOUND.into_response(),
        |file| {
            // `contents()` is `&'static [u8]`; wrap it without a per-request
            // copy so a full response still serves the static bytes directly.
            let bytes = bytes::Bytes::from_static(file.contents());
            let total = bytes.len() as u64;
            let etag = embedded_etag_cached(&bytes);
            let validator = crate::range::Validator::new().with_etag(&etag);
            let resolution = crate::range::resolve(req_headers, total, Some(validator));
            let mut response = crate::range::partial_bytes_response(&resolution, bytes);
            let headers = response.headers_mut();
            headers.insert(
                http::header::CONTENT_TYPE,
                http::HeaderValue::from_static(content_type_for(rel_path)),
            );
            headers.insert(http::header::ETAG, etag.header_value());
            response
        },
    )
}

/// Axum handler serving `/static/{*path}` from the embedded tree.
#[cfg(feature = "embed-assets")]
pub(crate) async fn serve_embedded(
    axum::extract::Path(path): axum::extract::Path<String>,
    headers: http::HeaderMap,
) -> axum::response::Response {
    embedded_response(&path, &headers)
}

/// A standalone router that serves `/static/*` from the registered embedded
/// tree with the [`asset_cache_control`] policy applied.
///
/// The framework wires the embedded handler directly into the typed
/// application router; this helper exposes the same serving behavior as a
/// self-contained `Router` for tests and embedding into custom setups.
#[cfg(feature = "embed-assets")]
pub fn embedded_static_router() -> axum::Router {
    axum::Router::new()
        .route("/static/{*path}", axum::routing::get(serve_embedded))
        .layer(AssetCacheControlLayer)
}

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

    #[test]
    fn asset_url_returns_static_prefix() {
        let url = asset_url("css/autumn.css");
        assert!(
            url.starts_with("/static/"),
            "url must have /static/ prefix: {url}"
        );
        assert!(
            url.contains("autumn.css"),
            "url must contain asset name: {url}"
        );
    }

    #[test]
    fn fingerprinted_path_detected() {
        assert!(is_fingerprinted_path("/static/css/autumn.a1b2c3d4.css"));
        assert!(is_fingerprinted_path("/static/js/app.00000000.js"));
        assert!(is_fingerprinted_path("/static/img/logo.deadbeef.png"));
    }

    #[test]
    fn non_fingerprinted_paths_rejected() {
        assert!(!is_fingerprinted_path("/static/css/autumn.css"));
        assert!(!is_fingerprinted_path("/static/js/htmx.min.js"));
        assert!(!is_fingerprinted_path("/static/img/logo.png"));
        // Hash too short
        assert!(!is_fingerprinted_path("/static/css/autumn.abc.css"));
        // Hash too long
        assert!(!is_fingerprinted_path("/static/css/autumn.a1b2c3d4e5.css"));
        // Hash contains uppercase (not hex-lowercase)
        assert!(!is_fingerprinted_path("/static/css/autumn.A1B2C3D4.css"));
        // No extension
        assert!(!is_fingerprinted_path("/static/file.a1b2c3d4"));
    }

    #[cfg(feature = "maud")]
    #[test]
    fn vendor_manifest_parses_json() {
        let json = r#"{
            "version": "1",
            "assets": {
                "htmx": {
                    "version": "2.0.4",
                    "source": "https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js",
                    "file": "js/htmx.min.js",
                    "integrity": "sha384-testintegrityhash"
                }
            }
        }"#;
        let manifest: VendorManifest = serde_json::from_str(json).unwrap();
        assert_eq!(manifest.version, "1");
        let htmx = manifest.assets.get("htmx").unwrap();
        assert_eq!(htmx.version, "2.0.4");
        assert_eq!(htmx.file, "js/htmx.min.js");
        assert_eq!(htmx.integrity, "sha384-testintegrityhash");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn render_javascript_tag_has_src_integrity_crossorigin() {
        let asset = VendorAsset {
            version: "2.0.4".into(),
            source: "https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js".into(),
            file: "js/htmx.min.js".into(),
            integrity: "sha384-abc123".into(),
        };
        let markup = render_javascript_tag(&asset);
        let html = markup.into_string();
        assert!(
            html.contains("src=\"/static/js/htmx.min.js\""),
            "missing src: {html}"
        );
        assert!(
            html.contains("integrity=\"sha384-abc123\""),
            "missing integrity: {html}"
        );
        assert!(
            html.contains("crossorigin=\"anonymous\""),
            "missing crossorigin: {html}"
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn javascript_include_tag_unknown_name_returns_diagnostic_comment() {
        let markup = javascript_include_tag("__nonexistent_pkg__");
        let html = markup.into_string();
        assert!(
            html.contains("<!-- autumn: asset '__nonexistent_pkg__' not found"),
            "expected HTML comment diagnostic for unknown asset, got: {html}"
        );
    }

    #[cfg(feature = "embed-assets")]
    #[test]
    fn content_type_covers_common_assets() {
        assert_eq!(content_type_for("css/app.css"), "text/css; charset=utf-8");
        assert_eq!(
            content_type_for("js/app.js"),
            "text/javascript; charset=utf-8"
        );
        assert_eq!(content_type_for("img/logo.svg"), "image/svg+xml");
        assert_eq!(content_type_for("img/logo.png"), "image/png");
        assert_eq!(content_type_for("fonts/inter.woff2"), "font/woff2");
        assert_eq!(content_type_for("favicon.ico"), "image/x-icon");
        // Unknown / extensionless fall back to octet-stream.
        assert_eq!(content_type_for("data.bin"), "application/octet-stream");
        assert_eq!(content_type_for("LICENSE"), "application/octet-stream");
    }
}

/// Direct coverage for [`AssetCacheControlService`] (issue #2214).
///
/// The framework's ingress installs the *layer*; the retained
/// [`asset_cache_control`] `async fn` is what every pre-existing test exercises.
/// An end-to-end test cannot cover the layer under default features either: the
/// `/static` route is a `ServeDir` over a `static/` directory this crate does
/// not ship, so every `/static/...` request in the test suite 404s and the
/// success branch — the entire point of this middleware — is never reached.
/// Driving the service directly over a stub inner service closes that.
#[cfg(test)]
mod cache_control_service_tests {
    use super::{AssetCacheControlLayer, cache_control_for_request};
    use axum::body::Body;
    use axum::http::{Request, Response, StatusCode};
    use tower::{Layer, Service, ServiceExt};

    const REVALIDATE: &str = "public, max-age=0, must-revalidate";

    /// Inner service that answers every request with `status` and no
    /// `Cache-Control`, so any header on the way out came from the layer.
    fn responder(
        status: StatusCode,
    ) -> impl Service<Request<Body>, Response = Response<Body>, Error = std::convert::Infallible> + Clone
    {
        tower::service_fn(move |_req: Request<Body>| async move {
            Ok::<_, std::convert::Infallible>(
                Response::builder()
                    .status(status)
                    .body(Body::empty())
                    .expect("response builds"),
            )
        })
    }

    /// `#[allow(future_not_send)]`: `tower::service_fn`'s closure is not
    /// `Sync`, so this helper's future is `!Send`. It only ever runs on a
    /// `#[tokio::test]` current-thread runtime, which never moves it.
    #[allow(clippy::future_not_send)]
    async fn cache_control_for(path: &str, status: StatusCode) -> Option<String> {
        let service = AssetCacheControlLayer.layer(responder(status));
        let response = service
            .oneshot(
                Request::builder()
                    .uri(path)
                    .body(Body::empty())
                    .expect("request builds"),
            )
            .await
            .expect("infallible");
        response
            .headers()
            .get(http::header::CACHE_CONTROL)
            .map(|v| v.to_str().expect("ascii header").to_owned())
    }

    #[tokio::test]
    async fn stamps_successful_static_responses() {
        // Debug builds have no fingerprint manifest, so every asset is the
        // revalidate (non-immutable) case.
        assert_eq!(
            cache_control_for("/static/css/app.css", StatusCode::OK).await,
            Some(REVALIDATE.to_owned()),
        );
    }

    #[tokio::test]
    async fn leaves_non_static_routes_alone() {
        assert_eq!(cache_control_for("/ping", StatusCode::OK).await, None);
        // `/static` without the trailing slash is NOT an asset path — the
        // predicate is a `/static/` prefix, matching the original `starts_with`.
        assert_eq!(cache_control_for("/static", StatusCode::OK).await, None);
        assert_eq!(cache_control_for("/staticky/x", StatusCode::OK).await, None);
    }

    #[tokio::test]
    async fn leaves_unsuccessful_static_responses_alone() {
        for status in [
            StatusCode::NOT_FOUND,
            StatusCode::FOUND,
            StatusCode::INTERNAL_SERVER_ERROR,
        ] {
            assert_eq!(
                cache_control_for("/static/css/app.css", status).await,
                None,
                "only a successful response may be given a Cache-Control"
            );
        }
    }

    /// The request-side half of the decision, isolated: `/static/` exactly
    /// yields an empty relative path and still counts as an asset request,
    /// matching the original `starts_with(..) && strip_prefix(..)` pair.
    #[test]
    fn the_predicate_matches_the_original_starts_with_form() {
        let req = |path: &str| {
            Request::builder()
                .uri(path)
                .body(Body::empty())
                .expect("request builds")
        };
        assert!(cache_control_for_request(&req("/static/")).is_some());
        assert!(cache_control_for_request(&req("/static/a.css")).is_some());
        // Query strings are not part of `Uri::path()`, so they cannot affect it.
        assert!(cache_control_for_request(&req("/static/a.css?v=1")).is_some());
        assert!(cache_control_for_request(&req("/static")).is_none());
        assert!(cache_control_for_request(&req("/")).is_none());
    }
}