1use std::collections::HashMap;
4use std::path::Path;
5
6use serde::Deserialize;
7
8#[derive(Debug, Deserialize)]
9pub struct ManifestEntry {
10 pub file: String,
11 #[serde(default)]
12 pub css: Vec<String>,
13}
14
15pub type Manifest = HashMap<String, ManifestEntry>;
16
17pub fn read_manifest(path: impl AsRef<Path>) -> Option<Manifest> {
18 let raw = std::fs::read_to_string(path).ok()?;
19 serde_json::from_str(&raw).ok()
20}
21
22pub fn render(entries: &[&str]) -> String {
23 let app_env = std::env::var("APP_ENV").unwrap_or_else(|_| "production".into());
24 if app_env == "local" || app_env == "development" {
25 render_dev(entries)
26 } else {
27 render_prod(entries)
28 }
29}
30
31fn render_dev(entries: &[&str]) -> String {
32 let host =
33 std::env::var("VITE_DEV_SERVER").unwrap_or_else(|_| "http://localhost:5173".to_string());
34 let mut html = format!(r#"<script type="module" src="{host}/@vite/client"></script>"#);
35 for entry in entries {
36 html.push_str(&format!(
37 "\n<script type=\"module\" src=\"{host}/{entry}\"></script>"
38 ));
39 }
40 html
41}
42
43fn render_prod(entries: &[&str]) -> String {
44 let manifest_path = std::env::var("VITE_MANIFEST_PATH")
45 .unwrap_or_else(|_| "public/build/manifest.json".to_string());
46 let Some(manifest) = read_manifest(&manifest_path) else {
47 tracing::warn!(path = %manifest_path, "vite manifest not found, emitting empty");
48 return String::new();
49 };
50 let mut html = String::new();
51 for entry in entries {
52 let Some(m) = manifest.get(*entry) else {
53 tracing::warn!(entry, "missing manifest entry");
54 continue;
55 };
56 if m.file.ends_with(".css") {
57 html.push_str(&format!(
58 "<link rel=\"stylesheet\" href=\"/build/{}\">\n",
59 m.file
60 ));
61 } else {
62 html.push_str(&format!(
63 "<script type=\"module\" src=\"/build/{}\"></script>\n",
64 m.file
65 ));
66 }
67 for css in &m.css {
68 html.push_str(&format!(
69 "<link rel=\"stylesheet\" href=\"/build/{}\">\n",
70 css
71 ));
72 }
73 }
74 html
75}