1use crate::compress::{self, Tools};
21use crate::seo::{self, SeoPage, SiteConfig};
22use crate::{compile, BuildContext};
23use std::io;
24use std::path::{Path, PathBuf};
25
26#[derive(Debug, Default, Clone)]
28pub struct SiteReport {
29 pub built: Vec<PathBuf>,
31 pub errors: Vec<(PathBuf, String)>,
33 pub warnings: Vec<String>,
36 pub pages: Vec<SeoPage>,
39 pub configured: bool,
41 pub artifacts: Vec<PathBuf>,
44 pub compressed: usize,
46 pub dictionary: bool,
49}
50
51impl SiteReport {
52 pub fn is_clean(&self) -> bool {
54 self.errors.is_empty()
55 }
56}
57
58pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
70 let config = SiteConfig::load(src);
71 let mut report = SiteReport {
72 configured: config.is_some(),
73 ..SiteReport::default()
74 };
75 let mut stack = vec![src.to_path_buf()];
76 while let Some(dir) = stack.pop() {
77 for entry in std::fs::read_dir(&dir)? {
78 let entry = entry?;
79 let path = entry.path();
80 let name = entry.file_name();
81 let name = name.to_string_lossy();
82 if path.is_dir() {
83 if !name.starts_with('.') {
84 stack.push(path);
85 }
86 } else if name.ends_with(".md") {
87 build_one_page(src, out, &path, config.as_ref(), &mut report);
88 }
89 }
90 }
91 if let Some(config) = &config {
92 let page_refs: &[SeoPage] = &report.pages;
93 for (name, content) in [
94 ("llms.txt", seo::llms_txt(config, page_refs)),
95 ("sitemap.xml", seo::sitemap_xml(config, page_refs)),
96 ("robots.txt", seo::robots_txt(config)),
97 ] {
98 let path = out.join(name);
99 std::fs::write(&path, content)?;
100 report.artifacts.push(path);
101 }
102 }
103 precompress(out, &mut report);
104 Ok(report)
105}
106
107fn precompress(out: &Path, report: &mut SiteReport) {
112 let tools = Tools::detect();
113 if !tools.any() {
114 report
115 .warnings
116 .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
117 return;
118 }
119 let mut compressed = 0usize;
120 let artifacts = report.artifacts.clone();
121 for artifact in &artifacts {
122 match compress::sidecars(&tools, artifact) {
123 Ok(encodings) => compressed += encodings.len(),
124 Err(e) => report
125 .warnings
126 .push(format!("{}: compression failed: {e}", artifact.display())),
127 }
128 }
129 let dict_path = out.join("site.dict");
130 match compress::train_dictionary(&tools, &artifacts, &dict_path) {
131 Ok(true) => {
132 report.dictionary = true;
133 compressed += 1; for artifact in &artifacts {
135 if matches!(
136 artifact.extension().and_then(|e| e.to_str()),
137 Some("html") | Some("txt") | Some("xml")
138 ) && compress::dcz_sidecar(&tools, &dict_path, artifact).unwrap_or(false)
139 {
140 compressed += 1;
141 }
142 }
143 }
144 Ok(false) => {
145 report.warnings.push(format!(
146 "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
147 artifacts.len()
148 ));
149 }
150 Err(e) => report
151 .warnings
152 .push(format!("dictionary training failed: {e}")),
153 }
154 report.compressed = compressed;
155}
156
157fn build_one_page(
159 src: &Path,
160 out: &Path,
161 path: &Path,
162 config: Option<&SiteConfig>,
163 report: &mut SiteReport,
164) {
165 let rel = match path.strip_prefix(src) {
166 Ok(r) => r.to_path_buf(),
167 Err(_) => path.to_path_buf(),
168 };
169 let source = match std::fs::read_to_string(path) {
170 Ok(s) => s,
171 Err(e) => {
172 report.errors.push((path.to_path_buf(), e.to_string()));
173 return;
174 }
175 };
176 let (meta, body_markdown) = seo::split_front_matter(&source);
177 let root = path
178 .parent()
179 .filter(|p| !p.as_os_str().is_empty())
180 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
181 let body = match compile(&body_markdown, &BuildContext::new(root)) {
182 Ok(html) => html,
183 Err(e) => {
184 report.errors.push((path.to_path_buf(), e.to_string()));
185 return;
186 }
187 };
188
189 let stem = meta.slug.clone().unwrap_or_else(|| {
190 rel.file_stem()
191 .unwrap_or_default()
192 .to_string_lossy()
193 .into_owned()
194 });
195 let dir = rel.parent().unwrap_or(Path::new(""));
196 let route = if dir.as_os_str().is_empty() {
197 format!("{stem}.html")
198 } else {
199 format!("{}/{}.html", dir.display(), stem)
200 };
201 let title = meta
202 .title
203 .clone()
204 .or_else(|| seo::first_h1(&body))
205 .unwrap_or_else(|| {
206 rel.file_stem()
207 .map(|s| s.to_string_lossy().into_owned())
208 .unwrap_or_else(|| "Untitled".to_string())
209 });
210 let description = meta
211 .description
212 .clone()
213 .or_else(|| seo::first_paragraph(&body))
214 .unwrap_or_default();
215
216 if title.chars().count() > 60 {
217 report.warnings.push(format!(
218 "{route}: title is {} chars (guidance: <= 60)",
219 title.chars().count()
220 ));
221 }
222 if description.is_empty() {
223 report.warnings.push(format!(
224 "{route}: no description (front-matter or first paragraph)"
225 ));
226 } else if description.chars().count() > 155 {
227 report.warnings.push(format!(
228 "{route}: description is {} chars (guidance: <= 155)",
229 description.chars().count()
230 ));
231 }
232
233 let document = seo::document(&body, &meta, &title, &description, &route, config);
234 let target = out.join(&route);
235 if let Some(parent) = target.parent() {
236 if let Err(e) = std::fs::create_dir_all(parent) {
237 report.errors.push((path.to_path_buf(), e.to_string()));
238 return;
239 }
240 }
241 if let Err(e) = std::fs::write(&target, document) {
242 report.errors.push((path.to_path_buf(), e.to_string()));
243 return;
244 }
245 report.built.push(path.to_path_buf());
246 report.artifacts.push(target);
247 report.pages.push(SeoPage {
248 route,
249 title,
250 description,
251 date: meta.date,
252 });
253}
254
255#[must_use]
260pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
261 let path = url_path.split(['?', '#']).next().unwrap_or("");
262 let decoded = percent_decode(path)?;
263 let cleaned: Vec<&str> = decoded
264 .split('/')
265 .filter(|seg| !seg.is_empty() && *seg != ".")
266 .collect();
267 if cleaned.contains(&"..") {
268 return None;
269 }
270 let mut file = out.to_path_buf();
271 for seg in &cleaned {
272 file.push(seg);
273 }
274 if cleaned.is_empty() {
275 file.push("index.html");
276 }
277 if file.is_dir() {
278 file.push("index.html");
279 }
280 if !file.exists() && file.extension().is_none() {
281 let with_html = file.with_extension("html");
282 if with_html.is_file() {
283 return Some(with_html);
284 }
285 return None;
286 }
287 if file.is_file() {
288 Some(file)
289 } else {
290 None
291 }
292}
293
294#[must_use]
297fn percent_decode(path: &str) -> Option<String> {
298 let mut out = Vec::with_capacity(path.len());
299 let mut bytes = path.bytes();
300 while let Some(b) = bytes.next() {
301 let value = if b == b'%' {
302 let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
303 let hi = decode(bytes.next()?)?;
304 let lo = decode(bytes.next()?)?;
305 hi.checked_mul(16)?.checked_add(lo)?
306 } else {
307 b
308 };
309 out.push(value);
310 }
311 String::from_utf8(out).ok()
312}
313
314#[must_use]
317pub fn mime_for(path: &Path) -> &'static str {
318 match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
319 "html" => "text/html; charset=utf-8",
320 "css" => "text/css; charset=utf-8",
321 "js" | "mjs" => "text/javascript; charset=utf-8",
322 "json" => "application/json",
323 "wasm" => "application/wasm",
324 "svg" => "image/svg+xml",
325 "png" => "image/png",
326 "jpg" | "jpeg" => "image/jpeg",
327 "gif" => "image/gif",
328 "ico" => "image/x-icon",
329 "md" => "text/markdown; charset=utf-8",
330 "xml" => "application/xml",
331 "txt" => "text/plain; charset=utf-8",
332 "woff2" => "font/woff2",
333 _ => "text/plain; charset=utf-8",
334 }
335}