assets.rs
⎇
Raw
1//! Static frontend assets: embedded at compile time (`--features embedded`)
2//! or read from disk in the dev flow (Trunk's output dir or $FBNG_DIST).
3
4#[cfg(not(feature = "embedded"))]
5use std::path::PathBuf;
6
7#[cfg(feature = "embedded")]
8mod embedded {
9 use rust_embed::RustEmbed;
10
11 #[derive(RustEmbed)]
12 #[folder = "dist/"]
13 pub struct Assets;
14}
15
16/// Look up an asset by (slash-separated) path.
17/// Returns (bytes, content-type, cache-control).
18pub(crate) fn get_asset(path: &str) -> Option<(Vec<u8>, String, String)> {
19 let (bytes, from_disk) = read(path)?;
20 let mime = mime_guess::from_path(path)
21 .first_or_octet_stream()
22 .to_string();
23 let cache = if from_disk || path == "index.html" {
24 "no-cache".to_string()
25 } else {
26 // Trunk hashes asset file names, so they are safe to cache forever.
27 "public, max-age=31536000, immutable".to_string()
28 };
29 Some((bytes, mime, cache))
30}
31
32#[cfg(feature = "embedded")]
33fn read(path: &str) -> Option<(Vec<u8>, bool)> {
34 embedded::Assets::get(path).map(|c| (c.data.to_vec(), false))
35}
36
37#[cfg(not(feature = "embedded"))]
38fn dev_dist_dir() -> PathBuf {
39 std::env::var_os("FBNG_DIST")
40 .map(PathBuf::from)
41 .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../web/dist"))
42}
43
44#[cfg(not(feature = "embedded"))]
45fn read(path: &str) -> Option<(Vec<u8>, bool)> {
46 let p = dev_dist_dir().join(path);
47 if p.is_file() {
48 std::fs::read(&p).ok().map(|b| (b, true))
49 } else {
50 None
51 }
52}
53