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 compile_site_with(src, out, None)
89}
90
91pub fn compile_site_with(
98 src: &Path,
99 out: &Path,
100 base_path_override: Option<&str>,
101) -> io::Result<SiteReport> {
102 let mut config = SiteConfig::load(src);
103 if let Some(bp) = base_path_override {
104 if let Some(c) = config.as_mut() {
105 c.base_path = bp.trim_end_matches('/').to_string();
106 }
107 }
108 let config = config;
109 let tools = compress::Tools::detect();
110 let mut report = SiteReport {
111 configured: config.is_some(),
112 ..SiteReport::default()
113 };
114
115 let mut pages: Vec<PageBuild> = Vec::new();
117 let mut stack = vec![src.to_path_buf()];
118 while let Some(dir) = stack.pop() {
119 for entry in std::fs::read_dir(&dir)? {
120 let entry = entry?;
121 let path = entry.path();
122 let name = entry.file_name();
123 let name = name.to_string_lossy();
124 if path.is_dir() {
125 if !name.starts_with('.') {
126 stack.push(path);
127 }
128 } else if name.ends_with(".md") {
129 build_page(src, &path, config.as_ref(), &mut report, &mut pages);
130 }
131 }
132 }
133 pages.sort_by(|a, b| a.route.cmp(&b.route));
134
135 let chrome_css = out.join("_assets").join("layout.css");
139 std::fs::create_dir_all(
140 chrome_css
141 .parent()
142 .map_or_else(|| Path::new("."), Path::new),
143 )?;
144 std::fs::write(&chrome_css, chrome::LAYOUT_CSS)?;
145 report.artifacts.push(chrome_css);
146 let assets_src = src.join("assets");
147 if assets_src.is_dir() {
148 report.assets_copied = copy_tree(&assets_src, &out.join("_assets"))?;
149 }
150
151 let base_path_str = config.as_ref().map(|c| c.base_path.clone());
155 let mut corpus_entries: Vec<String> = Vec::new();
156 let mut index = docs_search::IndexBuilder::new();
157 for page in &pages {
158 let segs: Vec<&str> = page.route.split('/').collect();
161 let mut breadcrumbs: Vec<(String, Option<String>)> = Vec::new();
164 if let Some(dir) = segs.get(1) {
165 let mut label = dir.split('.').next().unwrap_or(dir).to_string();
166 if let Some(first) = label.chars().next() {
167 label = first.to_uppercase().to_string() + &label[first.len_utf8()..];
168 }
169 breadcrumbs.push((label, None));
170 }
171 let chrome = Chrome {
172 nav: nav_groups(&pages, &page.route),
173 active_route: page.route.clone(),
174 toc: chrome::extract_toc(&page.body),
175 prev: prev_of(&pages, &page.route),
176 next: next_of(&pages, &page.route),
177 search_island: config.as_ref().and_then(|c| c.search_island.clone()),
178 search_index: Some(match base_path_str.as_deref() {
179 Some("") | None => "/search.json".to_string(),
180 Some(bp) => format!("{bp}/search.json"),
181 }),
182 search_wasm: config.as_ref().and_then(|c| c.search_wasm.clone()),
183 search_bin: config.as_ref().and_then(|c| c.search_bin.clone()),
184 accent: config.as_ref().and_then(|c| c.accent.clone()),
185 };
186 let doc = seo::document(
187 &page.body,
188 &page.meta,
189 &page.title,
190 &page.description,
191 &page.route,
192 config.as_ref(),
193 &breadcrumbs,
194 );
195 let site_title = config
196 .as_ref()
197 .map_or_else(|| "Docs".to_string(), |c| c.site_title.clone());
198 let with_chrome = chrome::page(
199 &doc,
200 &site_title,
201 &chrome,
202 base_path_str.as_deref().unwrap_or(""),
203 );
204 let target = out.join(&page.route);
205 if let Some(parent) = target.parent() {
206 std::fs::create_dir_all(parent)?;
207 }
208 std::fs::write(&target, with_chrome)?;
209 report.built.push(page.source.clone());
210 report.artifacts.push(target);
211 report.pages.push(SeoPage {
212 route: page.route.clone(),
213 title: page.title.clone(),
214 description: page.description.clone(),
215 date: page.date.clone(),
216 });
217
218 corpus_entries.push(format!(
219 "{{\"title\":{},\"url\":{},\"description\":{},\"body\":{}}}",
220 serde_json::to_string(&page.title).unwrap_or_else(|_| "\"\"".into()),
221 serde_json::to_string(&format!("/{}", page.route)).unwrap_or_else(|_| "\"\"".into()),
222 serde_json::to_string(&page.description).unwrap_or_else(|_| "\"\"".into()),
223 serde_json::to_string(&page.text).unwrap_or_else(|_| "\"\"".into()),
224 ));
225 let _ = index.add_doc(&format!(
226 "{} {} {}",
227 page.title, page.description, page.text
228 ));
229 }
230
231 if let Some(config) = &config {
233 let page_refs: &[SeoPage] = &report.pages;
234 for (name, content) in [
235 ("llms.txt", seo::llms_txt(config, page_refs)),
236 ("sitemap.xml", seo::sitemap_xml(config, page_refs)),
237 ("robots.txt", seo::robots_txt(config)),
238 ] {
239 let path = out.join(name);
240 std::fs::write(&path, content)?;
241 report.artifacts.push(path);
242 }
243 let feed_path = out.join("atom.xml");
244 std::fs::write(&feed_path, seo::atom_xml(config, page_refs))?;
245 report.artifacts.push(feed_path);
246 }
247
248 let not_found = seo::document(
250 "<h1>404</h1><p>This page does not exist. Use the navigation to find your way back.</p>",
251 &seo::PageMeta::default(),
252 "404 - not found",
253 "Page not found.",
254 "404.html",
255 config.as_ref(),
256 &[],
257 );
258 let not_found = chrome::page(
259 ¬_found,
260 &config
261 .as_ref()
262 .map_or_else(|| "Docs".to_string(), |c| c.site_title.clone()),
263 &chrome::Chrome {
264 nav: nav_groups(&pages, "404.html"),
265 active_route: "404.html".into(),
266 toc: Vec::new(),
267 prev: None,
268 next: None,
269 search_island: config.as_ref().and_then(|c| c.search_island.clone()),
270 search_index: Some(match base_path_str.as_deref() {
271 Some("") | None => "/search.json".to_string(),
272 Some(bp) => format!("{bp}/search.json"),
273 }),
274 search_wasm: config.as_ref().and_then(|c| c.search_wasm.clone()),
275 search_bin: config.as_ref().and_then(|c| c.search_bin.clone()),
276 accent: config.as_ref().and_then(|c| c.accent.clone()),
277 },
278 base_path_str.as_deref().unwrap_or(""),
279 );
280 let not_found_path = out.join("404.html");
281 std::fs::write(¬_found_path, not_found)?;
282 report.artifacts.push(not_found_path);
283
284 if !corpus_entries.is_empty() {
287 let corpus = format!("[\n{}\n]\n", corpus_entries.join(",\n"));
288 let corpus_path = out.join("search.json");
289 std::fs::write(&corpus_path, corpus)?;
290 report.artifacts.push(corpus_path);
291 let index_path = out.join("search.bin");
292 match index.build() {
293 Ok(bytes) => {
294 std::fs::write(&index_path, bytes)?;
295 report.artifacts.push(index_path);
296 }
297 Err(e) => report
298 .warnings
299 .push(format!("search index build failed: {e}")),
300 }
301 }
302
303 precompress(out, &tools, &mut report);
304 Ok(report)
305}
306
307fn build_page(
310 src: &Path,
311 path: &Path,
312 config: Option<&SiteConfig>,
313 report: &mut SiteReport,
314 pages: &mut Vec<PageBuild>,
315) {
316 let rel = match path.strip_prefix(src) {
317 Ok(r) => r.to_path_buf(),
318 Err(_) => path.to_path_buf(),
319 };
320 let source = match std::fs::read_to_string(path) {
321 Ok(s) => s,
322 Err(e) => {
323 report.errors.push((path.to_path_buf(), e.to_string()));
324 return;
325 }
326 };
327 let (meta, body_markdown) = seo::split_front_matter(&source);
328 let root = path
329 .parent()
330 .filter(|p| !p.as_os_str().is_empty())
331 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
332 let ctx = match config {
333 Some(c) if !c.base_path.is_empty() => {
334 BuildContext::with_asset_base(root, format!("{}/_assets", c.base_path))
335 }
336 _ => BuildContext::new(root),
337 };
338 let body = match compile(&body_markdown, &ctx) {
339 Ok(html) => html,
340 Err(e) => {
341 report.errors.push((path.to_path_buf(), e.to_string()));
342 return;
343 }
344 };
345
346 let stem = meta.slug.clone().unwrap_or_else(|| {
347 rel.file_stem()
348 .unwrap_or_default()
349 .to_string_lossy()
350 .into_owned()
351 });
352 let dir = rel.parent().unwrap_or(Path::new(""));
353 let route = if dir.as_os_str().is_empty() {
354 format!("{stem}.html")
355 } else {
356 format!("{}/{}.html", dir.display(), stem)
357 };
358 let title = meta
359 .title
360 .clone()
361 .or_else(|| seo::first_h1(&body))
362 .unwrap_or_else(|| {
363 rel.file_stem()
364 .map(|s| s.to_string_lossy().into_owned())
365 .unwrap_or_else(|| "Untitled".to_string())
366 });
367 let description = meta
368 .description
369 .clone()
370 .or_else(|| seo::first_paragraph(&body))
371 .unwrap_or_default();
372
373 if title.chars().count() > 60 {
374 report.warnings.push(format!(
375 "{route}: title is {} chars (guidance: <= 60)",
376 title.chars().count()
377 ));
378 }
379 if description.is_empty() {
380 report.warnings.push(format!(
381 "{route}: no description (front-matter or first paragraph)"
382 ));
383 } else if description.chars().count() > 155 {
384 report.warnings.push(format!(
385 "{route}: description is {} chars (guidance: <= 155)",
386 description.chars().count()
387 ));
388 }
389
390 pages.push(PageBuild {
391 source: path.to_path_buf(),
392 route,
393 title,
394 description,
395 date: meta.date.clone(),
396 meta,
397 text: crate::seo::plain_text(&body),
398 body,
399 });
400}
401
402fn nav_groups(pages: &[PageBuild], active_route: &str) -> Vec<NavGroup> {
407 let mut order: Vec<String> = Vec::new();
408 let mut groups: std::collections::HashMap<String, Vec<(String, String)>> =
409 std::collections::HashMap::new();
410 for page in pages {
411 if page.route == "index.html" {
412 continue;
413 }
414 let segs: Vec<&str> = page.route.split('/').collect();
419 let key = match (segs.first(), segs.get(1)) {
420 (Some(top), Some(second)) if second.contains('.') => (*top).to_string(),
421 (Some(top), Some(second)) => format!(
422 "{top}/{stem}",
423 stem = second.split('.').next().unwrap_or(second)
424 ),
425 _ => "pages".to_string(),
426 };
427 if !groups.contains_key(&key) {
428 order.push(key.clone());
429 }
430 groups
431 .entry(key)
432 .or_default()
433 .push((page.route.clone(), page.title.clone()));
434 }
435 let mut out = Vec::new();
436 for key in order {
437 let items = groups.remove(&key).unwrap_or_default();
438 let label = key.rsplit('/').next().unwrap_or(&key).to_string();
439 let active = active_route.starts_with(&format!("{key}/"));
440 out.push(NavGroup {
441 label: display_label(&key, &label),
442 active,
443 items,
444 });
445 }
446 out
447}
448
449fn display_label(key: &str, label: &str) -> String {
451 let mut chars = label.chars();
452 match chars.next() {
453 Some(first) => {
454 let mut out = String::from(key);
455 out.clear();
456 out.push(first.to_ascii_uppercase());
457 out.push_str(chars.as_str());
458 out
459 }
460 None => key.to_string(),
461 }
462}
463
464fn prev_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
465 let pos = pages.iter().position(|p| p.route == route)?;
466 let previous = pos.checked_sub(1)?;
467 pages
468 .get(previous)
469 .map(|p| (p.route.clone(), p.title.clone()))
470}
471
472fn next_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
473 let pos = pages.iter().position(|p| p.route == route)?;
474 pages
475 .get(pos + 1)
476 .map(|p| (p.route.clone(), p.title.clone()))
477}
478
479fn copy_tree(from: &Path, to: &Path) -> io::Result<usize> {
481 let mut count = 0usize;
482 let mut stack = vec![from.to_path_buf()];
483 while let Some(dir) = stack.pop() {
484 for entry in std::fs::read_dir(&dir)? {
485 let entry = entry?;
486 let path = entry.path();
487 if path.is_dir() {
488 stack.push(path);
489 } else {
490 let rel = path.strip_prefix(from).unwrap_or(&path).to_path_buf();
491 let dest = to.join(rel);
492 if let Some(parent) = dest.parent() {
493 std::fs::create_dir_all(parent)?;
494 }
495 std::fs::copy(&path, &dest)?;
496 count += 1;
497 }
498 }
499 }
500 Ok(count)
501}
502
503fn precompress(out: &Path, tools: &compress::Tools, report: &mut SiteReport) {
508 if !tools.any() {
509 report
510 .warnings
511 .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
512 return;
513 }
514 let mut compressed = 0usize;
515 let artifacts = report.artifacts.clone();
516 for artifact in &artifacts {
517 match compress::sidecars(tools, artifact) {
518 Ok(encodings) => compressed += encodings.len(),
519 Err(e) => report
520 .warnings
521 .push(format!("{}: compression failed: {e}", artifact.display())),
522 }
523 }
524 let dict_path = out.join("site.dict");
525 match compress::train_dictionary(tools, &artifacts, &dict_path) {
526 Ok(true) => {
527 report.dictionary = true;
528 compressed += 1;
529 for artifact in &artifacts {
530 if matches!(
531 artifact.extension().and_then(|e| e.to_str()),
532 Some("html") | Some("txt") | Some("xml") | Some("json")
533 ) && compress::dcz_sidecar(tools, &dict_path, artifact).unwrap_or(false)
534 {
535 compressed += 1;
536 }
537 }
538 }
539 Ok(false) => {
540 report.warnings.push(format!(
541 "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
542 artifacts.len()
543 ));
544 }
545 Err(e) => report
546 .warnings
547 .push(format!("dictionary training failed: {e}")),
548 }
549 report.compressed = compressed;
550}
551
552#[must_use]
557pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
558 let path = url_path.split(['?', '#']).next().unwrap_or("");
559 let decoded = percent_decode(path)?;
560 let cleaned: Vec<&str> = decoded
561 .split('/')
562 .filter(|seg| !seg.is_empty() && *seg != ".")
563 .collect();
564 if cleaned.contains(&"..") {
565 return None;
566 }
567 let mut file = out.to_path_buf();
568 for seg in &cleaned {
569 file.push(seg);
570 }
571 if cleaned.is_empty() {
572 file.push("index.html");
573 }
574 if file.is_dir() {
575 file.push("index.html");
576 }
577 if !file.exists() && file.extension().is_none() {
578 let with_html = file.with_extension("html");
579 if with_html.is_file() {
580 return Some(with_html);
581 }
582 return None;
583 }
584 if file.is_file() {
585 Some(file)
586 } else {
587 None
588 }
589}
590
591#[must_use]
594fn percent_decode(path: &str) -> Option<String> {
595 let mut out = Vec::with_capacity(path.len());
596 let mut bytes = path.bytes();
597 while let Some(b) = bytes.next() {
598 let value = if b == b'%' {
599 let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
600 let hi = decode(bytes.next()?)?;
601 let lo = decode(bytes.next()?)?;
602 hi.checked_mul(16)?.checked_add(lo)?
603 } else {
604 b
605 };
606 out.push(value);
607 }
608 String::from_utf8(out).ok()
609}
610
611#[must_use]
614pub fn mime_for(path: &Path) -> &'static str {
615 match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
616 "html" => "text/html; charset=utf-8",
617 "css" => "text/css; charset=utf-8",
618 "js" | "mjs" => "text/javascript; charset=utf-8",
619 "json" => "application/json",
620 "wasm" => "application/wasm",
621 "svg" => "image/svg+xml",
622 "png" => "image/png",
623 "jpg" | "jpeg" => "image/jpeg",
624 "gif" => "image/gif",
625 "ico" => "image/x-icon",
626 "md" => "text/markdown; charset=utf-8",
627 "xml" => "application/xml",
628 "txt" => "text/plain; charset=utf-8",
629 "bin" => "application/octet-stream",
630 "woff2" => "font/woff2",
631 _ => "text/plain; charset=utf-8",
632 }
633}