Skip to main content

docs_compiler/
serve.rs

1//! The dev server's reusable half (Wave 2): compiling a directory of
2//! markdown into a directory of HTML, URL routing with a traversal
3//! guard, and MIME mapping. The socket loop and the file watcher are
4//! thin wrappers in the binary; everything with logic lives here and is
5//! unit-tested.
6//!
7//! Since Wave 2c every page compiles to a FULL HTML document carrying
8//! the estate-seo floor's head artifacts (title, description, canonical,
9//! Open Graph, JSON-LD); a `site.toml` with `base_url` additionally
10//! emits `llms.txt`, `sitemap.xml`, and `robots.txt` (with the
11//! AI-crawler policy as a recorded decision). Per-page inputs come from
12//! `---` front-matter (`title`, `description`, `slug`, `date`).
13//!
14//! Design note (plan ledger W2-3): the server lives in docs-compiler,
15//! not docs-core - docs-core is L2 with no web framework, and serving
16//! is a CLI concern. The server never dies on a bad page: compile
17//! errors are collected per page, printed, and the site keeps serving
18//! the last good HTML (fail-loud, not fail-dead).
19
20use crate::seo::{self, SeoPage, SiteConfig};
21use crate::{compile, BuildContext};
22use std::io;
23use std::path::{Path, PathBuf};
24
25/// What one site compilation pass produced.
26#[derive(Debug, Default, Clone)]
27pub struct SiteReport {
28    /// Pages written (source paths).
29    pub built: Vec<PathBuf>,
30    /// Pages that failed: (source path, error text).
31    pub errors: Vec<(PathBuf, String)>,
32    /// Content-quality warnings (title > 60 chars, description > 155,
33    /// missing description): the estate-seo floor's guidance, not errors.
34    pub warnings: Vec<String>,
35    /// The SEO view of every built page (route, title, description,
36    /// date) - also the source for llms.txt and sitemap.xml.
37    pub pages: Vec<SeoPage>,
38    /// Whether a `site.toml` provided site-wide settings.
39    pub configured: bool,
40}
41
42impl SiteReport {
43    /// Whether every page compiled.
44    pub fn is_clean(&self) -> bool {
45        self.errors.is_empty()
46    }
47}
48
49/// Compile every `.md` under `src` (recursive, hidden dirs skipped) into
50/// the mirrored `.html` layout under `out`, as full documents with the
51/// SEO head. Front-matter (`title`, `description`, `slug`, `date`)
52/// overrides the title/description/route/date fallbacks. Directive roots
53/// are each page's own directory, matching the single-file CLI's
54/// default. One bad page never blocks the others: its error lands in
55/// the report. A `site.toml` with `base_url` additionally emits
56/// `llms.txt`, `sitemap.xml`, and `robots.txt` into `out`.
57///
58/// # Errors
59/// I/O failures on the tree walk or output creation.
60pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
61    let config = SiteConfig::load(src);
62    let mut report = SiteReport {
63        configured: config.is_some(),
64        ..SiteReport::default()
65    };
66    let mut stack = vec![src.to_path_buf()];
67    while let Some(dir) = stack.pop() {
68        for entry in std::fs::read_dir(&dir)? {
69            let entry = entry?;
70            let path = entry.path();
71            let name = entry.file_name();
72            let name = name.to_string_lossy();
73            if path.is_dir() {
74                if !name.starts_with('.') {
75                    stack.push(path);
76                }
77            } else if name.ends_with(".md") {
78                build_one_page(src, out, &path, config.as_ref(), &mut report);
79            }
80        }
81    }
82    if let Some(config) = &config {
83        let page_refs: &[SeoPage] = &report.pages;
84        std::fs::write(out.join("llms.txt"), seo::llms_txt(config, page_refs))?;
85        std::fs::write(out.join("sitemap.xml"), seo::sitemap_xml(config, page_refs))?;
86        std::fs::write(out.join("robots.txt"), seo::robots_txt(config))?;
87    }
88    Ok(report)
89}
90
91/// Build one page: front-matter, compile, head, write, report.
92fn build_one_page(
93    src: &Path,
94    out: &Path,
95    path: &Path,
96    config: Option<&SiteConfig>,
97    report: &mut SiteReport,
98) {
99    let rel = match path.strip_prefix(src) {
100        Ok(r) => r.to_path_buf(),
101        Err(_) => path.to_path_buf(),
102    };
103    let source = match std::fs::read_to_string(path) {
104        Ok(s) => s,
105        Err(e) => {
106            report.errors.push((path.to_path_buf(), e.to_string()));
107            return;
108        }
109    };
110    let (meta, body_markdown) = seo::split_front_matter(&source);
111    let root = path
112        .parent()
113        .filter(|p| !p.as_os_str().is_empty())
114        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
115    let body = match compile(&body_markdown, &BuildContext::new(root)) {
116        Ok(html) => html,
117        Err(e) => {
118            report.errors.push((path.to_path_buf(), e.to_string()));
119            return;
120        }
121    };
122
123    let stem = meta.slug.clone().unwrap_or_else(|| {
124        rel.file_stem()
125            .unwrap_or_default()
126            .to_string_lossy()
127            .into_owned()
128    });
129    let dir = rel.parent().unwrap_or(Path::new(""));
130    let route = if dir.as_os_str().is_empty() {
131        format!("{stem}.html")
132    } else {
133        format!("{}/{}.html", dir.display(), stem)
134    };
135    let title = meta
136        .title
137        .clone()
138        .or_else(|| seo::first_h1(&body))
139        .unwrap_or_else(|| {
140            rel.file_stem()
141                .map(|s| s.to_string_lossy().into_owned())
142                .unwrap_or_else(|| "Untitled".to_string())
143        });
144    let description = meta
145        .description
146        .clone()
147        .or_else(|| seo::first_paragraph(&body))
148        .unwrap_or_default();
149
150    if title.chars().count() > 60 {
151        report.warnings.push(format!(
152            "{route}: title is {} chars (guidance: <= 60)",
153            title.chars().count()
154        ));
155    }
156    if description.is_empty() {
157        report.warnings.push(format!(
158            "{route}: no description (front-matter or first paragraph)"
159        ));
160    } else if description.chars().count() > 155 {
161        report.warnings.push(format!(
162            "{route}: description is {} chars (guidance: <= 155)",
163            description.chars().count()
164        ));
165    }
166
167    let document = seo::document(&body, &meta, &title, &description, &route, config);
168    let target = out.join(&route);
169    if let Some(parent) = target.parent() {
170        if let Err(e) = std::fs::create_dir_all(parent) {
171            report.errors.push((path.to_path_buf(), e.to_string()));
172            return;
173        }
174    }
175    if let Err(e) = std::fs::write(&target, document) {
176        report.errors.push((path.to_path_buf(), e.to_string()));
177        return;
178    }
179    report.built.push(path.to_path_buf());
180    report.pages.push(SeoPage {
181        route,
182        title,
183        description,
184        date: meta.date,
185    });
186}
187
188/// Map a request path to a file under `out`: empty → `index.html`;
189/// directories resolve to their `index.html`; an extensionless path
190/// falls back to `<path>.html`. Percent escapes are decoded; anything
191/// that escapes `out` (or games the encoding) resolves to nothing.
192#[must_use]
193pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
194    let path = url_path.split(['?', '#']).next().unwrap_or("");
195    let decoded = percent_decode(path)?;
196    let cleaned: Vec<&str> = decoded
197        .split('/')
198        .filter(|seg| !seg.is_empty() && *seg != ".")
199        .collect();
200    if cleaned.contains(&"..") {
201        return None;
202    }
203    let mut file = out.to_path_buf();
204    for seg in &cleaned {
205        file.push(seg);
206    }
207    if cleaned.is_empty() {
208        file.push("index.html");
209    }
210    if file.is_dir() {
211        file.push("index.html");
212    }
213    if !file.exists() && file.extension().is_none() {
214        let with_html = file.with_extension("html");
215        if with_html.is_file() {
216            return Some(with_html);
217        }
218        return None;
219    }
220    if file.is_file() {
221        Some(file)
222    } else {
223        None
224    }
225}
226
227/// Minimal percent-decoding for request paths; malformed escapes
228/// (`%` not followed by two hex digits) resolve to nothing.
229#[must_use]
230fn percent_decode(path: &str) -> Option<String> {
231    let mut out = Vec::with_capacity(path.len());
232    let mut bytes = path.bytes();
233    while let Some(b) = bytes.next() {
234        let value = if b == b'%' {
235            let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
236            let hi = decode(bytes.next()?)?;
237            let lo = decode(bytes.next()?)?;
238            hi.checked_mul(16)?.checked_add(lo)?
239        } else {
240            b
241        };
242        out.push(value);
243    }
244    String::from_utf8(out).ok()
245}
246
247/// MIME type by extension; unknown extensions are plain text (the
248/// browser shows them instead of downloading).
249#[must_use]
250pub fn mime_for(path: &Path) -> &'static str {
251    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
252        "html" => "text/html; charset=utf-8",
253        "css" => "text/css; charset=utf-8",
254        "js" | "mjs" => "text/javascript; charset=utf-8",
255        "json" => "application/json",
256        "wasm" => "application/wasm",
257        "svg" => "image/svg+xml",
258        "png" => "image/png",
259        "jpg" | "jpeg" => "image/jpeg",
260        "gif" => "image/gif",
261        "ico" => "image/x-icon",
262        "md" => "text/markdown; charset=utf-8",
263        "xml" => "application/xml",
264        "txt" => "text/plain; charset=utf-8",
265        "woff2" => "font/woff2",
266        _ => "text/plain; charset=utf-8",
267    }
268}