Skip to main content

docs_compiler/
seo.rs

1//! SEO emission (Wave 2c): full HTML documents with the estate-seo
2//! floor's technical artifacts - title, meta description, canonical,
3//! Open Graph, JSON-LD per page; `llms.txt`, `sitemap.xml`, and
4//! `robots.txt` per site (with `base_url` in `site.toml`).
5//!
6//! Policy decisions, recorded (estate-seo: never block AI crawlers
7//! silently): `site.toml` carries `ai_crawlers = "allow"` (default) /
8//! `"block-training"` / `"block-all"`, and the emitted robots.txt states
9//! the decision in a comment next to the rules.
10//!
11//! Inputs are deliberately tiny: front-matter is `key: value` scalars
12//! under a leading `---` fence; `site.toml` is `key = "value"` lines.
13//! No YAML/TOML dependency; anything richer belongs to a real pipeline.
14
15use std::path::Path;
16
17use crate::directives::html_escape;
18
19/// One indexable page, as the SEO emitters see it.
20#[derive(Debug, Clone, PartialEq)]
21pub struct SeoPage {
22    /// Site-relative HTML route (`index.html`, `guides/x.html`).
23    pub route: String,
24    /// Page title (front-matter, first h1, or file stem).
25    pub title: String,
26    /// Meta description (front-matter or first paragraph).
27    pub description: String,
28    /// Declared publication date (ISO), for sitemap lastmod + JSON-LD.
29    pub date: Option<String>,
30}
31
32/// Site-wide settings, from `site.toml` in the source root.
33#[derive(Debug, Clone, PartialEq)]
34pub struct SiteConfig {
35    /// Absolute origin for canonical URLs, sitemap, and llms.txt
36    /// (`https://docs.example.com`, no trailing slash).
37    pub base_url: String,
38    /// Site title (llms.txt heading, JSON-LD `isPartOf`).
39    pub site_title: String,
40    /// Named author (E-E-A-T: real names beat anonymous).
41    pub author: String,
42    /// AI-crawler policy, recorded in robots.txt: `"allow"` (default),
43    /// `"block-training"`, `"block-all"`.
44    pub ai_crawlers: String,
45    /// Stylesheet URL emitted as a `<link rel="stylesheet">` in every
46    /// page head (e.g. the islands' Tailwind build).
47    pub stylesheet: Option<String>,
48    /// The island shim module URL, emitted as a deferred module script
49    /// in every page head (registers `<docs-island>`).
50    pub island_shim: Option<String>,
51    /// The search island chunk URL, emitted as a search trigger in the
52    /// header (props point at `/search.json`).
53    pub search_island: Option<String>,
54    /// The docs_search.wasm reader module URL (site-relative; wasm-first
55    /// search). Empty/absent = the island falls back to JSON scoring.
56    pub search_wasm: Option<String>,
57    /// The FST binary index URL (site-relative; reader input).
58    pub search_bin: Option<String>,
59    /// URL path prefix for all site-relative links (subpath hosting,
60    /// e.g. `/solid-fx/preview`). Empty string = served at root.
61    pub base_path: String,
62    /// Open Graph image URL, emitted as `og:image` + `twitter:image`.
63    pub og_image: Option<String>,
64    /// Accent color as `#rgb`/`#rrggbb` hex, overriding `--accent` in
65    /// the chrome palette (both themes; light gets a darkened variant).
66    /// Absent/invalid = the default palette.
67    pub accent: Option<String>,
68}
69
70impl SiteConfig {
71    /// Absolute URL for a site route: `base_url` (origin) joined with
72    /// the optional `base_path` (subpath hosting) and the route. The
73    /// empty route gives the site root. Slash-join is normalized (no
74    /// double slashes when `base_path` is empty).
75    pub fn full_url(&self, route: &str) -> String {
76        let bp = self.base_path.trim_matches('/');
77        let base = if bp.is_empty() {
78            self.base_url.clone()
79        } else {
80            format!("{}/{}", self.base_url, bp)
81        };
82        if route.is_empty() {
83            base
84        } else if route.starts_with('/') {
85            format!("{base}{route}")
86        } else {
87            format!("{base}/{route}")
88        }
89    }
90}
91
92impl SiteConfig {
93    /// Parse `site.toml` if present: `key = "value"` scalar lines only.
94    /// `base_url` is the one required key; the rest have defaults.
95    pub fn load(src: &Path) -> Option<SiteConfig> {
96        let text = std::fs::read_to_string(src.join("site.toml")).ok()?;
97        let mut base_url = None;
98        let mut site_title = String::from("Documentation");
99        let mut author = String::new();
100        let mut ai_crawlers = String::from("allow");
101        let mut stylesheet = None;
102        let mut island_shim = None;
103        let mut search_island = None;
104        let mut search_wasm = None;
105        let mut search_bin = None;
106        let mut base_path = String::new();
107        let mut og_image = None;
108        let mut accent = None;
109        for line in text.lines() {
110            let line = line.trim();
111            if line.is_empty() || line.starts_with('#') {
112                continue;
113            }
114            let Some((key, value)) = line.split_once('=') else {
115                continue;
116            };
117            let value = value.trim().trim_matches('"').to_string();
118            match key.trim() {
119                "base_url" => base_url = Some(value.trim_end_matches('/').to_string()),
120                "site_title" => site_title = value,
121                "author" => author = value,
122                "ai_crawlers" => ai_crawlers = value,
123                "stylesheet" => stylesheet = Some(value),
124                "island_shim" => island_shim = Some(value),
125                "search_island" => search_island = Some(value),
126                "search_wasm" => search_wasm = Some(value),
127                "search_bin" => search_bin = Some(value),
128                "base_path" => base_path = value.trim_end_matches('/').to_string(),
129                "og_image" => og_image = Some(value),
130                "accent" => accent = Some(value),
131                _ => {}
132            }
133        }
134        Some(SiteConfig {
135            base_url: base_url.map(|u| u.trim_end_matches('/').to_string())?,
136            site_title,
137            author,
138            ai_crawlers,
139            stylesheet,
140            island_shim,
141            search_island,
142            search_wasm,
143            search_bin,
144            base_path,
145            og_image,
146            accent,
147        })
148    }
149}
150
151/// Per-page metadata, from the page's front-matter (`---` fenced
152/// `key: value` scalars). `title` falls back to the first `<h1>`, then
153/// the file stem; `description` falls back to the first paragraph.
154#[derive(Debug, Clone, Default, PartialEq)]
155pub struct PageMeta {
156    /// Page title.
157    pub title: Option<String>,
158    /// Meta description.
159    pub description: Option<String>,
160    /// Output file stem override (route becomes `<slug>.html`).
161    pub slug: Option<String>,
162    /// Publication date (ISO `YYYY-MM-DD`; sitemap lastmod + JSON-LD).
163    pub date: Option<String>,
164}
165
166/// Split a leading `---` front-matter block off a document: returns the
167/// parsed metadata and the remainder to compile.
168#[must_use]
169pub fn split_front_matter(markdown: &str) -> (PageMeta, String) {
170    let mut meta = PageMeta::default();
171    let Some(rest) = markdown.strip_prefix("---\n") else {
172        return (meta, markdown.to_string());
173    };
174    let Some(close) = rest.find("\n---") else {
175        return (meta, markdown.to_string());
176    };
177    let block = &rest[..close];
178    for line in block.lines() {
179        let Some((key, value)) = line.split_once(':') else {
180            continue;
181        };
182        let value = value.trim().to_string();
183        match key.trim() {
184            "title" => meta.title = Some(value),
185            "description" => meta.description = Some(value),
186            "slug" => meta.slug = Some(value),
187            "date" => meta.date = Some(value),
188            _ => {}
189        }
190    }
191    // Skip the closing fence line and any following blank lines
192    // (markdown leading whitespace is insignificant).
193    let after = &rest[close + 4..];
194    (meta, after.trim_start_matches('\n').to_string())
195}
196
197/// Derive a page title from the rendered body: the first `<h1>` text.
198#[must_use]
199pub fn first_h1(body: &str) -> Option<String> {
200    // Matches both `<h1>` and `<h1 id="...">` (anchored headings, 0.3.0+).
201    let tag_pos = body.find("<h1")?;
202    let gt = body[tag_pos..].find('>')? + tag_pos + 1;
203    let end = body[gt..].find("</h1>")? + gt;
204    let text = strip_tags(&body[gt..end]);
205    if text.is_empty() {
206        None
207    } else {
208        Some(text)
209    }
210}
211
212/// Derive a description from the rendered body: the first paragraph's
213/// text, tags stripped, truncated at a word boundary to 155 chars.
214#[must_use]
215pub fn first_paragraph(body: &str) -> Option<String> {
216    let start = body.find("<p>")? + 3;
217    let end = body[start..].find("</p>")? + start;
218    let text = strip_tags(&body[start..end]);
219    if text.is_empty() {
220        return None;
221    }
222    Some(truncate_words(&text, 155))
223}
224
225/// Strip all tags from rendered HTML and collapse whitespace: the
226/// plain-text view used for search corpora.
227#[must_use]
228pub fn plain_text(body: &str) -> String {
229    let text = strip_tags(body);
230    text.split_whitespace().collect::<Vec<_>>().join(" ")
231}
232
233/// Prefix a site-relative URL with the configured base path. Values
234/// starting with a scheme (https://, http://) pass through verbatim
235/// (external URLs, CDN assets).
236fn site_url(base_path: &str, value: &str) -> String {
237    if value.starts_with("https://") || value.starts_with("http://") || base_path.is_empty() {
238        value.to_string()
239    } else if value.starts_with('/') {
240        format!("{base_path}{value}")
241    } else {
242        format!("{base_path}/{value}")
243    }
244}
245
246fn strip_tags(html: &str) -> String {
247    let mut out = String::with_capacity(html.len());
248    let mut in_tag = false;
249    for c in html.chars() {
250        match c {
251            '<' => in_tag = true,
252            '>' => in_tag = false,
253            c if !in_tag => out.push(c),
254            _ => {}
255        }
256    }
257    out.trim().to_string()
258}
259
260fn truncate_words(text: &str, max: usize) -> String {
261    if text.len() <= max {
262        return text.to_string();
263    }
264    match text[..max].rfind(' ') {
265        Some(pos) => format!("{}...", &text[..pos]),
266        None => format!("{}...", &text[..max]),
267    }
268}
269
270/// Attribute-safe escaping: text escaping plus double quotes (SEO head
271/// values live inside `content="..."` attributes).
272fn escape_attr(text: &str) -> String {
273    html_escape(text).replace('"', "&quot;")
274}
275
276/// The full-document wrapper: doctype, head (charset, viewport, title,
277/// description, canonical, Open Graph, Twitter card, JSON-LD), body.
278/// `route` is the page's site-relative HTML path (`index.html`,
279/// `guides/x.html`). Length guidance (title <=60, description <=155)
280/// surfaces as warnings in the report, not build failures.
281#[must_use]
282pub fn document(
283    body: &str,
284    meta: &PageMeta,
285    title: &str,
286    description: &str,
287    route: &str,
288    config: Option<&SiteConfig>,
289    breadcrumbs: &[(String, Option<String>)],
290) -> String {
291    let canonical = config.map(|c| c.full_url(route)).unwrap_or_default();
292    let canonical_tags = if canonical.is_empty() {
293        String::new()
294    } else {
295        format!(
296            "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
297            u = escape_attr(&canonical)
298        )
299    };
300    let json_ld_tag = config
301        .map(|c| {
302            let mut article = serde_json::json!({
303                "@context": "https://schema.org",
304                "@type": "TechArticle",
305                "headline": title,
306                "description": description,
307                "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.full_url("") },
308            });
309            if let Some(obj) = article.as_object_mut() {
310                if !canonical.is_empty() {
311                    obj.insert("url".into(), serde_json::json!(canonical));
312                }
313                if !c.author.is_empty() {
314                    obj.insert(
315                        "author".into(),
316                        serde_json::json!({ "@type": "Person", "name": c.author }),
317                    );
318                }
319                if let Some(date) = &meta.date {
320                    obj.insert("datePublished".into(), serde_json::json!(date));
321                }
322            }
323            format!("<script type=\"application/ld+json\">{article}</script>")
324        })
325        .unwrap_or_default();
326    let site_name_tag = config
327        .map(|c| {
328            format!(
329                "<meta property=\"og:site_name\" content=\"{}\">",
330                escape_attr(&c.site_title)
331            )
332        })
333        .unwrap_or_default();
334    let og_image_tag = config
335        .and_then(|c| c.og_image.clone())
336        .map(|img| {
337            format!(
338                "<meta property=\"og:image\" content=\"{i}\"><meta name=\"twitter:image\" content=\"{i}\">",
339                i = escape_attr(&img)
340            )
341        })
342        .unwrap_or_default();
343    let _ = &og_image_tag;
344    let feed_link = config
345        .map(|c| {
346            format!(
347                "<link rel=\"alternate\" type=\"application/atom+xml\" href=\"{u}\">",
348                u = escape_attr(&c.full_url("atom.xml"))
349            )
350        })
351        .unwrap_or_default();
352    let breadcrumb_markup = if breadcrumbs.is_empty() {
353        String::new()
354    } else {
355        let mut parts: Vec<String> = vec!["<a href=\"/\">Home</a>".into()];
356        for (label, href) in breadcrumbs {
357            parts.push(match href {
358                Some(h) => format!("<a href=\"{}\">{}</a>", escape_attr(h), html_escape(label)),
359                None => html_escape(label),
360            });
361        }
362        format!(
363            "<nav class=\"breadcrumbs\">{}</nav>",
364            parts.join(" <span class=\"crumb-sep\">/</span> ")
365        )
366    };
367    // Site-level head wiring (Wave 2c.5): the islands' stylesheet and
368    // the shim module that registers <docs-island>.
369    let head_extra = config
370        .map(|c| {
371            let mut extra = String::new();
372            if let Some(css) = &c.stylesheet {
373                extra.push_str(&format!(
374                    "<link rel=\"stylesheet\" href=\"{}\">",
375                    escape_attr(&site_url(&c.base_path, css))
376                ));
377            }
378            if let Some(shim) = &c.island_shim {
379                extra.push_str(&format!(
380                    "<script type=\"module\" src=\"{}\"></script>",
381                    escape_attr(&site_url(&c.base_path, shim))
382                ));
383            }
384            extra
385        })
386        .unwrap_or_default();
387    format!(
388        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
389<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
390<title>{t}</title>\
391<meta name=\"description\" content=\"{d}\">{canonical_tags}\
392<meta property=\"og:type\" content=\"article\">\
393<meta property=\"og:title\" content=\"{t}\">\
394<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
395<meta name=\"twitter:card\" content=\"summary\">\
396<meta name=\"twitter:title\" content=\"{t}\">\
397<meta name=\"twitter:description\" content=\"{d}\">\
398{head_extra}{og_image_tag}{feed_link}{json_ld_tag}</head><body>{breadcrumb_markup}{body}</body></html>",
399        t = escape_attr(title),
400        d = escape_attr(description),
401        breadcrumb_markup = breadcrumb_markup
402    )
403}
404
405/// `llms.txt` (GEO floor): the site heading plus one curated link per
406/// page with its description.
407#[must_use]
408pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
409    let mut out = format!("# {}\n\n", config.site_title);
410    if !config.author.is_empty() {
411        out.push_str(&format!("By {}.\n\n", config.author));
412    }
413    for page in pages {
414        out.push_str(&format!(
415            "- [{t}]({u}): {d}\n",
416            t = page.title,
417            u = config.full_url(&page.route),
418            d = page.description
419        ));
420    }
421    out
422}
423
424/// `sitemap.xml`: one `<url>` per page, sorted by route; `lastmod` only
425/// when the page declares a date (deterministic builds do not lie about
426/// modification times).
427#[must_use]
428pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
429    let mut out = String::from(
430        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
431    );
432    let mut sorted: Vec<&SeoPage> = pages.iter().collect();
433    sorted.sort_by(|a, b| a.route.cmp(&b.route));
434    for page in sorted {
435        let lastmod = page
436            .date
437            .as_ref()
438            .map(|d| format!("<lastmod>{d}</lastmod>"))
439            .unwrap_or_default();
440        out.push_str(&format!(
441            "<url><loc>{}</loc>{lastmod}</url>\n",
442            config.full_url(&page.route)
443        ));
444    }
445    out.push_str("</urlset>\n");
446    out
447}
448
449/// `robots.txt` with the AI-crawler policy as a recorded decision.
450#[must_use]
451pub fn robots_txt(config: &SiteConfig) -> String {
452    let policy = config.ai_crawlers.as_str();
453    let mut out =
454        format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
455    match policy {
456        "block-all" => {
457            out.push_str("User-agent: *\nDisallow: /\n");
458        }
459        "block-training" => {
460            for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
461                out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
462            }
463            out.push_str("User-agent: *\nAllow: /\n");
464        }
465        _ => {
466            out.push_str("User-agent: *\nAllow: /\n");
467        }
468    }
469    out.push_str(&format!("Sitemap: {}\n", config.full_url("sitemap.xml")));
470    out
471}
472
473/// `atom.xml`: one entry per dated page, newest first. Pages without a
474/// front-matter date stay out of the feed (deterministic builds do not
475/// invent timestamps).
476#[must_use]
477pub fn atom_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
478    let mut dated: Vec<&SeoPage> = pages.iter().filter(|p| p.date.is_some()).collect();
479    dated.sort_by(|a, b| b.date.as_deref().cmp(&a.date.as_deref()));
480    let mut out = String::from(
481        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n",
482    );
483    out.push_str(&format!(
484        "<title>{}</title>\n",
485        html_escape(&config.site_title)
486    ));
487    if !config.author.is_empty() {
488        out.push_str(&format!(
489            "<author><name>{}</name></author>\n",
490            html_escape(&config.author)
491        ));
492    }
493    let self_url = config.full_url("atom.xml");
494    let site_url = config.full_url("");
495    out.push_str(&format!(
496        "<link rel=\"self\" href=\"{}\"/>\n<link rel=\"alternate\" href=\"{}\"/>\n<id>{}/</id>\n",
497        html_escape(&self_url),
498        html_escape(&site_url),
499        html_escape(&site_url),
500    ));
501    if let Some(newest) = dated.first() {
502        if let Some(date) = &newest.date {
503            out.push_str(&format!("<updated>{date}T00:00:00Z</updated>\n"));
504        }
505    }
506    for page in dated {
507        let url = config.full_url(&page.route);
508        out.push_str(&format!(
509            "<entry><title>{t}</title><link rel=\"alternate\" href=\"{u}\"/><id>{u}</id><published>{d}</published><summary>{s}</summary></entry>\n",
510            t = html_escape(&page.title),
511            u = html_escape(&url),
512            d = page.date.as_deref().unwrap_or(""),
513            s = html_escape(&page.description),
514        ));
515    }
516    out.push_str("</feed>\n");
517    out
518}