use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::Path;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug)]
pub struct EmbeddedDir {
files: &'static [(&'static str, &'static [u8])],
}
impl EmbeddedDir {
#[doc(hidden)]
#[must_use]
pub const fn __new(files: &'static [(&'static str, &'static [u8])]) -> Self {
Self { files }
}
#[must_use]
pub fn files(&self) -> &'static [(&'static str, &'static [u8])] {
self.files
}
#[must_use]
pub fn get(&self, path: &str) -> Option<&'static [u8]> {
self.files.iter().find(|(p, _)| *p == path).map(|(_, b)| *b)
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Asset {
pub hashed: String,
pub integrity: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetManifest {
#[serde(default)]
prefix: String,
assets: BTreeMap<String, Asset>,
}
impl AssetManifest {
pub fn from_dir(root: impl AsRef<Path>) -> std::io::Result<Self> {
let mut files = Vec::new();
collect(root.as_ref(), "", &mut files)?;
Ok(Self::from_files(
files.iter().map(|(p, b)| (p.as_str(), b.as_slice())),
))
}
#[must_use]
pub fn from_embedded(dir: &EmbeddedDir) -> Self {
Self::from_files(dir.files().iter().copied())
}
#[must_use]
pub fn from_files<'a>(files: impl IntoIterator<Item = (&'a str, &'a [u8])>) -> Self {
let assets = files
.into_iter()
.map(|(path, bytes)| (path.to_owned(), Asset::of(path, bytes)))
.collect();
Self {
prefix: String::new(),
assets,
}
}
#[must_use]
pub fn prefix(mut self, prefix: &str) -> Self {
self.prefix = prefix.trim_end_matches('/').to_owned();
self
}
#[must_use]
pub fn get(&self, path: &str) -> Option<&Asset> {
self.assets.get(path.trim_start_matches('/'))
}
#[must_use]
pub fn url(&self, path: &str) -> Option<String> {
self.get(path)
.map(|a| format!("{}/{}", self.prefix, a.hashed))
}
#[must_use]
pub fn integrity(&self, path: &str) -> Option<&str> {
self.get(path).map(|a| a.integrity.as_str())
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &Asset)> {
self.assets.iter().map(|(k, v)| (k.as_str(), v))
}
pub(super) fn by_hashed(&self) -> HashMap<String, String> {
self.assets
.iter()
.map(|(k, a)| (a.hashed.clone(), k.clone()))
.collect()
}
#[must_use]
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_default()
}
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
#[cfg(feature = "_tera")]
pub fn register_tera(&self, tera: &mut tera::Tera) {
let urls = std::sync::Arc::new(self.clone());
let sri = std::sync::Arc::clone(&urls);
tera.register_function("asset_url", move |args: &HashMap<String, tera::Value>| {
let name = asset_arg(args)?;
urls.url(name)
.map(tera::Value::String)
.ok_or_else(|| unknown_asset(name))
});
tera.register_function(
"asset_integrity",
move |args: &HashMap<String, tera::Value>| {
let name = asset_arg(args)?;
sri.integrity(name)
.map(|s| tera::Value::String(s.to_owned()))
.ok_or_else(|| unknown_asset(name))
},
);
}
}
impl Asset {
fn of(path: &str, bytes: &[u8]) -> Self {
use base64::Engine as _;
use sha2::Digest as _;
let digest = sha2::Sha384::digest(bytes);
let tag: String = digest[..6].iter().map(|b| format!("{b:02x}")).collect();
Self {
hashed: hashed_name(path, &tag),
integrity: format!(
"sha384-{}",
base64::engine::general_purpose::STANDARD.encode(digest)
),
}
}
}
fn hashed_name(path: &str, tag: &str) -> String {
let (dir, file) = path.rsplit_once('/').map_or(("", path), |(d, f)| (d, f));
let file = match file.split_once('.') {
Some((stem, ext)) if !stem.is_empty() => format!("{stem}.{tag}.{ext}"),
_ => format!("{file}.{tag}"),
};
if dir.is_empty() {
file
} else {
format!("{dir}/{file}")
}
}
fn collect(dir: &Path, rel: &str, out: &mut Vec<(String, Vec<u8>)>) -> std::io::Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if name.starts_with('.') {
continue;
}
let path = if rel.is_empty() {
name.to_owned()
} else {
format!("{rel}/{name}")
};
let kind = entry.file_type()?;
if kind.is_dir() {
collect(&entry.path(), &path, out)?;
} else if kind.is_file() {
out.push((path, std::fs::read(entry.path())?));
}
}
Ok(())
}
#[cfg(feature = "_tera")]
fn asset_arg(args: &HashMap<String, tera::Value>) -> tera::Result<&str> {
args.get("name")
.and_then(tera::Value::as_str)
.ok_or_else(|| tera::Error::msg("asset_url/asset_integrity need `name=\"…\"`"))
}
#[cfg(feature = "_tera")]
fn unknown_asset(name: &str) -> tera::Error {
tera::Error::msg(format!("no static asset named `{name}` in the manifest"))
}