1use crate::chrome::{self, Chrome, NavGroup};
21use crate::compress::{self};
22use crate::seo::{self, SeoPage, SiteConfig};
23use crate::{compile, BuildContext};
24use std::io;
25use std::path::{Path, PathBuf};
26
27#[derive(Debug, Default, Clone)]
29pub struct SiteReport {
30 pub built: Vec<PathBuf>,
32 pub errors: Vec<(PathBuf, String)>,
34 pub warnings: Vec<String>,
37 pub pages: Vec<SeoPage>,
40 pub configured: bool,
42 pub artifacts: Vec<PathBuf>,
45 pub compressed: usize,
47 pub dictionary: bool,
50 pub assets_copied: usize,
52}
53
54impl SiteReport {
55 pub fn is_clean(&self) -> bool {
57 self.errors.is_empty()
58 }
59}
60
61struct PageBuild {
63 source: PathBuf,
64 route: String,
65 title: String,
66 description: String,
67 date: Option<String>,
68 meta: seo::PageMeta,
69 body: String,
70 text: String,
72}
73
74pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
88 let config = SiteConfig::load(src);
89 let tools = compress::Tools::detect();
90 let mut report = SiteReport {
91 configured: config.is_some(),
92 ..SiteReport::default()
93 };
94
95 let mut pages: Vec<PageBuild> = Vec::new();
97 let mut stack = vec![src.to_path_buf()];
98 while let Some(dir) = stack.pop() {
99 for entry in std::fs::read_dir(&dir)? {
100 let entry = entry?;
101 let path = entry.path();
102 let name = entry.file_name();
103 let name = name.to_string_lossy();
104 if path.is_dir() {
105 if !name.starts_with('.') {
106 stack.push(path);
107 }
108 } else if name.ends_with(".md") {
109 build_page(src, &path, &mut report, &mut pages);
110 }
111 }
112 }
113 pages.sort_by(|a, b| a.route.cmp(&b.route));
114
115 let chrome_css = out.join("_assets").join("layout.css");
119 std::fs::create_dir_all(
120 chrome_css
121 .parent()
122 .map_or_else(|| Path::new("."), Path::new),
123 )?;
124 std::fs::write(&chrome_css, chrome::LAYOUT_CSS)?;
125 report.artifacts.push(chrome_css);
126 let assets_src = src.join("assets");
127 if assets_src.is_dir() {
128 report.assets_copied = copy_tree(&assets_src, &out.join("_assets"))?;
129 }
130
131 let mut corpus = String::from("[\n");
135 let mut index = docs_search::IndexBuilder::new();
136 for page in &pages {
137 let chrome = Chrome {
138 nav: nav_groups(&pages, &page.route),
139 active_route: page.route.clone(),
140 toc: chrome::extract_toc(&page.body),
141 prev: prev_of(&pages, &page.route),
142 next: next_of(&pages, &page.route),
143 search_island: config.as_ref().and_then(|c| c.search_island.clone()),
144 search_index: config.as_ref().map(|_| "/search.json".into()),
145 };
146 let doc = seo::document(
147 &page.body,
148 &page.meta,
149 &page.title,
150 &page.description,
151 &page.route,
152 config.as_ref(),
153 );
154 let site_title = config
155 .as_ref()
156 .map_or_else(|| "Docs".to_string(), |c| c.site_title.clone());
157 let with_chrome = chrome::page(&doc, &site_title, &chrome);
158 let target = out.join(&page.route);
159 if let Some(parent) = target.parent() {
160 std::fs::create_dir_all(parent)?;
161 }
162 std::fs::write(&target, with_chrome)?;
163 report.built.push(page.source.clone());
164 report.artifacts.push(target);
165 report.pages.push(SeoPage {
166 route: page.route.clone(),
167 title: page.title.clone(),
168 description: page.description.clone(),
169 date: page.date.clone(),
170 });
171
172 corpus.push_str(&format!(
173 "{{\"title\":{},\"url\":{},\"description\":{},\"body\":{}}},\n",
174 serde_json::to_string(&page.title).unwrap_or_else(|_| "\"\"".into()),
175 serde_json::to_string(&format!("/{}", page.route)).unwrap_or_else(|_| "\"\"".into()),
176 serde_json::to_string(&page.description).unwrap_or_else(|_| "\"\"".into()),
177 serde_json::to_string(&page.text).unwrap_or_else(|_| "\"\"".into()),
178 ));
179 let _ = index.add_doc(&format!(
180 "{} {} {}",
181 page.title, page.description, page.text
182 ));
183 }
184
185 if let Some(config) = &config {
187 let page_refs: &[SeoPage] = &report.pages;
188 for (name, content) in [
189 ("llms.txt", seo::llms_txt(config, page_refs)),
190 ("sitemap.xml", seo::sitemap_xml(config, page_refs)),
191 ("robots.txt", seo::robots_txt(config)),
192 ] {
193 let path = out.join(name);
194 std::fs::write(&path, content)?;
195 report.artifacts.push(path);
196 }
197 }
198
199 if !report.pages.is_empty() {
202 corpus.push_str("]\n");
203 let corpus_path = out.join("search.json");
204 std::fs::write(&corpus_path, corpus)?;
205 report.artifacts.push(corpus_path);
206 let index_path = out.join("search.bin");
207 match index.build() {
208 Ok(bytes) => {
209 std::fs::write(&index_path, bytes)?;
210 report.artifacts.push(index_path);
211 }
212 Err(e) => report
213 .warnings
214 .push(format!("search index build failed: {e}")),
215 }
216 }
217
218 precompress(out, &tools, &mut report);
219 Ok(report)
220}
221
222fn build_page(src: &Path, path: &Path, report: &mut SiteReport, pages: &mut Vec<PageBuild>) {
225 let rel = match path.strip_prefix(src) {
226 Ok(r) => r.to_path_buf(),
227 Err(_) => path.to_path_buf(),
228 };
229 let source = match std::fs::read_to_string(path) {
230 Ok(s) => s,
231 Err(e) => {
232 report.errors.push((path.to_path_buf(), e.to_string()));
233 return;
234 }
235 };
236 let (meta, body_markdown) = seo::split_front_matter(&source);
237 let root = path
238 .parent()
239 .filter(|p| !p.as_os_str().is_empty())
240 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
241 let body = match compile(&body_markdown, &BuildContext::new(root)) {
242 Ok(html) => html,
243 Err(e) => {
244 report.errors.push((path.to_path_buf(), e.to_string()));
245 return;
246 }
247 };
248
249 let stem = meta.slug.clone().unwrap_or_else(|| {
250 rel.file_stem()
251 .unwrap_or_default()
252 .to_string_lossy()
253 .into_owned()
254 });
255 let dir = rel.parent().unwrap_or(Path::new(""));
256 let route = if dir.as_os_str().is_empty() {
257 format!("{stem}.html")
258 } else {
259 format!("{}/{}.html", dir.display(), stem)
260 };
261 let title = meta
262 .title
263 .clone()
264 .or_else(|| seo::first_h1(&body))
265 .unwrap_or_else(|| {
266 rel.file_stem()
267 .map(|s| s.to_string_lossy().into_owned())
268 .unwrap_or_else(|| "Untitled".to_string())
269 });
270 let description = meta
271 .description
272 .clone()
273 .or_else(|| seo::first_paragraph(&body))
274 .unwrap_or_default();
275
276 if title.chars().count() > 60 {
277 report.warnings.push(format!(
278 "{route}: title is {} chars (guidance: <= 60)",
279 title.chars().count()
280 ));
281 }
282 if description.is_empty() {
283 report.warnings.push(format!(
284 "{route}: no description (front-matter or first paragraph)"
285 ));
286 } else if description.chars().count() > 155 {
287 report.warnings.push(format!(
288 "{route}: description is {} chars (guidance: <= 155)",
289 description.chars().count()
290 ));
291 }
292
293 pages.push(PageBuild {
294 source: path.to_path_buf(),
295 route,
296 title,
297 description,
298 date: meta.date.clone(),
299 meta,
300 text: crate::seo::plain_text(&body),
301 body,
302 });
303}
304
305fn nav_groups(pages: &[PageBuild], active_route: &str) -> Vec<NavGroup> {
310 let mut order: Vec<String> = Vec::new();
311 let mut groups: std::collections::HashMap<String, Vec<(String, String)>> =
312 std::collections::HashMap::new();
313 for page in pages {
314 if page.route == "index.html" {
315 continue;
316 }
317 let segs: Vec<&str> = page.route.split('/').collect();
322 let key = match (segs.first(), segs.get(1)) {
323 (Some(top), Some(second)) if second.contains('.') => (*top).to_string(),
324 (Some(top), Some(second)) => format!("{top}/{stem}", stem = second.split('.').next().unwrap_or(second)),
325 _ => "pages".to_string(),
326 };
327 if !groups.contains_key(&key) {
328 order.push(key.clone());
329 }
330 groups
331 .entry(key)
332 .or_default()
333 .push((page.route.clone(), page.title.clone()));
334 }
335 let mut out = Vec::new();
336 for key in order {
337 let items = groups.remove(&key).unwrap_or_default();
338 let label = key.rsplit('/').next().unwrap_or(&key).to_string();
339 let active = active_route.starts_with(&format!("{key}/"));
340 out.push(NavGroup {
341 label: display_label(&key, &label),
342 active,
343 items,
344 });
345 }
346 out
347}
348
349fn display_label(key: &str, label: &str) -> String {
351 let mut chars = label.chars();
352 match chars.next() {
353 Some(first) => {
354 let mut out = String::from(key);
355 out.clear();
356 out.push(first.to_ascii_uppercase());
357 out.push_str(chars.as_str());
358 out
359 }
360 None => key.to_string(),
361 }
362}
363
364fn prev_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
365 let pos = pages.iter().position(|p| p.route == route)?;
366 let previous = pos.checked_sub(1)?;
367 pages
368 .get(previous)
369 .map(|p| (p.route.clone(), p.title.clone()))
370}
371
372fn next_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
373 let pos = pages.iter().position(|p| p.route == route)?;
374 pages
375 .get(pos + 1)
376 .map(|p| (p.route.clone(), p.title.clone()))
377}
378
379fn copy_tree(from: &Path, to: &Path) -> io::Result<usize> {
381 let mut count = 0usize;
382 let mut stack = vec![from.to_path_buf()];
383 while let Some(dir) = stack.pop() {
384 for entry in std::fs::read_dir(&dir)? {
385 let entry = entry?;
386 let path = entry.path();
387 if path.is_dir() {
388 stack.push(path);
389 } else {
390 let rel = path.strip_prefix(from).unwrap_or(&path).to_path_buf();
391 let dest = to.join(rel);
392 if let Some(parent) = dest.parent() {
393 std::fs::create_dir_all(parent)?;
394 }
395 std::fs::copy(&path, &dest)?;
396 count += 1;
397 }
398 }
399 }
400 Ok(count)
401}
402
403fn precompress(out: &Path, tools: &compress::Tools, report: &mut SiteReport) {
408 if !tools.any() {
409 report
410 .warnings
411 .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
412 return;
413 }
414 let mut compressed = 0usize;
415 let artifacts = report.artifacts.clone();
416 for artifact in &artifacts {
417 match compress::sidecars(tools, artifact) {
418 Ok(encodings) => compressed += encodings.len(),
419 Err(e) => report
420 .warnings
421 .push(format!("{}: compression failed: {e}", artifact.display())),
422 }
423 }
424 let dict_path = out.join("site.dict");
425 match compress::train_dictionary(tools, &artifacts, &dict_path) {
426 Ok(true) => {
427 report.dictionary = true;
428 compressed += 1;
429 for artifact in &artifacts {
430 if matches!(
431 artifact.extension().and_then(|e| e.to_str()),
432 Some("html") | Some("txt") | Some("xml") | Some("json")
433 ) && compress::dcz_sidecar(tools, &dict_path, artifact).unwrap_or(false)
434 {
435 compressed += 1;
436 }
437 }
438 }
439 Ok(false) => {
440 report.warnings.push(format!(
441 "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
442 artifacts.len()
443 ));
444 }
445 Err(e) => report
446 .warnings
447 .push(format!("dictionary training failed: {e}")),
448 }
449 report.compressed = compressed;
450}
451
452#[must_use]
457pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
458 let path = url_path.split(['?', '#']).next().unwrap_or("");
459 let decoded = percent_decode(path)?;
460 let cleaned: Vec<&str> = decoded
461 .split('/')
462 .filter(|seg| !seg.is_empty() && *seg != ".")
463 .collect();
464 if cleaned.contains(&"..") {
465 return None;
466 }
467 let mut file = out.to_path_buf();
468 for seg in &cleaned {
469 file.push(seg);
470 }
471 if cleaned.is_empty() {
472 file.push("index.html");
473 }
474 if file.is_dir() {
475 file.push("index.html");
476 }
477 if !file.exists() && file.extension().is_none() {
478 let with_html = file.with_extension("html");
479 if with_html.is_file() {
480 return Some(with_html);
481 }
482 return None;
483 }
484 if file.is_file() {
485 Some(file)
486 } else {
487 None
488 }
489}
490
491#[must_use]
494fn percent_decode(path: &str) -> Option<String> {
495 let mut out = Vec::with_capacity(path.len());
496 let mut bytes = path.bytes();
497 while let Some(b) = bytes.next() {
498 let value = if b == b'%' {
499 let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
500 let hi = decode(bytes.next()?)?;
501 let lo = decode(bytes.next()?)?;
502 hi.checked_mul(16)?.checked_add(lo)?
503 } else {
504 b
505 };
506 out.push(value);
507 }
508 String::from_utf8(out).ok()
509}
510
511#[must_use]
514pub fn mime_for(path: &Path) -> &'static str {
515 match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
516 "html" => "text/html; charset=utf-8",
517 "css" => "text/css; charset=utf-8",
518 "js" | "mjs" => "text/javascript; charset=utf-8",
519 "json" => "application/json",
520 "wasm" => "application/wasm",
521 "svg" => "image/svg+xml",
522 "png" => "image/png",
523 "jpg" | "jpeg" => "image/jpeg",
524 "gif" => "image/gif",
525 "ico" => "image/x-icon",
526 "md" => "text/markdown; charset=utf-8",
527 "xml" => "application/xml",
528 "txt" => "text/plain; charset=utf-8",
529 "bin" => "application/octet-stream",
530 "woff2" => "font/woff2",
531 _ => "text/plain; charset=utf-8",
532 }
533}