1use std::path::Path;
16
17use crate::directives::html_escape;
18
19#[derive(Debug, Clone, PartialEq)]
21pub struct SeoPage {
22 pub route: String,
24 pub title: String,
26 pub description: String,
28 pub date: Option<String>,
30}
31
32#[derive(Debug, Clone, PartialEq)]
34pub struct SiteConfig {
35 pub base_url: String,
38 pub site_title: String,
40 pub author: String,
42 pub ai_crawlers: String,
45 pub stylesheet: Option<String>,
48 pub island_shim: Option<String>,
51 pub search_island: Option<String>,
54 pub search_wasm: Option<String>,
57 pub search_bin: Option<String>,
59 pub base_path: String,
62 pub og_image: Option<String>,
64 pub accent: Option<String>,
68}
69
70impl SiteConfig {
71 pub fn load(src: &Path) -> Option<SiteConfig> {
74 let text = std::fs::read_to_string(src.join("site.toml")).ok()?;
75 let mut base_url = None;
76 let mut site_title = String::from("Documentation");
77 let mut author = String::new();
78 let mut ai_crawlers = String::from("allow");
79 let mut stylesheet = None;
80 let mut island_shim = None;
81 let mut search_island = None;
82 let mut search_wasm = None;
83 let mut search_bin = None;
84 let mut base_path = String::new();
85 let mut og_image = None;
86 let mut accent = None;
87 for line in text.lines() {
88 let line = line.trim();
89 if line.is_empty() || line.starts_with('#') {
90 continue;
91 }
92 let Some((key, value)) = line.split_once('=') else {
93 continue;
94 };
95 let value = value.trim().trim_matches('"').to_string();
96 match key.trim() {
97 "base_url" => base_url = Some(value.trim_end_matches('/').to_string()),
98 "site_title" => site_title = value,
99 "author" => author = value,
100 "ai_crawlers" => ai_crawlers = value,
101 "stylesheet" => stylesheet = Some(value),
102 "island_shim" => island_shim = Some(value),
103 "search_island" => search_island = Some(value),
104 "search_wasm" => search_wasm = Some(value),
105 "search_bin" => search_bin = Some(value),
106 "base_path" => base_path = value.trim_end_matches('/').to_string(),
107 "og_image" => og_image = Some(value),
108 "accent" => accent = Some(value),
109 _ => {}
110 }
111 }
112 Some(SiteConfig {
113 base_url: base_url.map(|u| u.trim_end_matches('/').to_string())?,
114 site_title,
115 author,
116 ai_crawlers,
117 stylesheet,
118 island_shim,
119 search_island,
120 search_wasm,
121 search_bin,
122 base_path,
123 og_image,
124 accent,
125 })
126 }
127}
128
129#[derive(Debug, Clone, Default, PartialEq)]
133pub struct PageMeta {
134 pub title: Option<String>,
136 pub description: Option<String>,
138 pub slug: Option<String>,
140 pub date: Option<String>,
142}
143
144#[must_use]
147pub fn split_front_matter(markdown: &str) -> (PageMeta, String) {
148 let mut meta = PageMeta::default();
149 let Some(rest) = markdown.strip_prefix("---\n") else {
150 return (meta, markdown.to_string());
151 };
152 let Some(close) = rest.find("\n---") else {
153 return (meta, markdown.to_string());
154 };
155 let block = &rest[..close];
156 for line in block.lines() {
157 let Some((key, value)) = line.split_once(':') else {
158 continue;
159 };
160 let value = value.trim().to_string();
161 match key.trim() {
162 "title" => meta.title = Some(value),
163 "description" => meta.description = Some(value),
164 "slug" => meta.slug = Some(value),
165 "date" => meta.date = Some(value),
166 _ => {}
167 }
168 }
169 let after = &rest[close + 4..];
172 (meta, after.trim_start_matches('\n').to_string())
173}
174
175#[must_use]
177pub fn first_h1(body: &str) -> Option<String> {
178 let tag_pos = body.find("<h1")?;
180 let gt = body[tag_pos..].find('>')? + tag_pos + 1;
181 let end = body[gt..].find("</h1>")? + gt;
182 let text = strip_tags(&body[gt..end]);
183 if text.is_empty() {
184 None
185 } else {
186 Some(text)
187 }
188}
189
190#[must_use]
193pub fn first_paragraph(body: &str) -> Option<String> {
194 let start = body.find("<p>")? + 3;
195 let end = body[start..].find("</p>")? + start;
196 let text = strip_tags(&body[start..end]);
197 if text.is_empty() {
198 return None;
199 }
200 Some(truncate_words(&text, 155))
201}
202
203#[must_use]
206pub fn plain_text(body: &str) -> String {
207 let text = strip_tags(body);
208 text.split_whitespace().collect::<Vec<_>>().join(" ")
209}
210
211fn site_url(base_path: &str, value: &str) -> String {
215 if value.starts_with("https://") || value.starts_with("http://") || base_path.is_empty() {
216 value.to_string()
217 } else if value.starts_with('/') {
218 format!("{base_path}{value}")
219 } else {
220 format!("{base_path}/{value}")
221 }
222}
223
224fn strip_tags(html: &str) -> String {
225 let mut out = String::with_capacity(html.len());
226 let mut in_tag = false;
227 for c in html.chars() {
228 match c {
229 '<' => in_tag = true,
230 '>' => in_tag = false,
231 c if !in_tag => out.push(c),
232 _ => {}
233 }
234 }
235 out.trim().to_string()
236}
237
238fn truncate_words(text: &str, max: usize) -> String {
239 if text.len() <= max {
240 return text.to_string();
241 }
242 match text[..max].rfind(' ') {
243 Some(pos) => format!("{}...", &text[..pos]),
244 None => format!("{}...", &text[..max]),
245 }
246}
247
248fn escape_attr(text: &str) -> String {
251 html_escape(text).replace('"', """)
252}
253
254#[must_use]
260pub fn document(
261 body: &str,
262 meta: &PageMeta,
263 title: &str,
264 description: &str,
265 route: &str,
266 config: Option<&SiteConfig>,
267 breadcrumbs: &[(String, Option<String>)],
268) -> String {
269 let canonical = config
270 .map(|c| format!("{}/{}", c.base_url, route))
271 .unwrap_or_default();
272 let canonical_tags = if canonical.is_empty() {
273 String::new()
274 } else {
275 format!(
276 "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
277 u = escape_attr(&canonical)
278 )
279 };
280 let json_ld_tag = config
281 .map(|c| {
282 let mut article = serde_json::json!({
283 "@context": "https://schema.org",
284 "@type": "TechArticle",
285 "headline": title,
286 "description": description,
287 "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.base_url },
288 });
289 if let Some(obj) = article.as_object_mut() {
290 if !canonical.is_empty() {
291 obj.insert("url".into(), serde_json::json!(canonical));
292 }
293 if !c.author.is_empty() {
294 obj.insert(
295 "author".into(),
296 serde_json::json!({ "@type": "Person", "name": c.author }),
297 );
298 }
299 if let Some(date) = &meta.date {
300 obj.insert("datePublished".into(), serde_json::json!(date));
301 }
302 }
303 format!("<script type=\"application/ld+json\">{article}</script>")
304 })
305 .unwrap_or_default();
306 let site_name_tag = config
307 .map(|c| {
308 format!(
309 "<meta property=\"og:site_name\" content=\"{}\">",
310 escape_attr(&c.site_title)
311 )
312 })
313 .unwrap_or_default();
314 let og_image_tag = config
315 .and_then(|c| c.og_image.clone())
316 .map(|img| {
317 format!(
318 "<meta property=\"og:image\" content=\"{i}\"><meta name=\"twitter:image\" content=\"{i}\">",
319 i = escape_attr(&img)
320 )
321 })
322 .unwrap_or_default();
323 let _ = &og_image_tag;
324 let feed_link = config
325 .map(|c| {
326 format!(
327 "<link rel=\"alternate\" type=\"application/atom+xml\" href=\"{u}/atom.xml\">",
328 u = c.base_url
329 )
330 })
331 .unwrap_or_default();
332 let breadcrumb_markup = if breadcrumbs.is_empty() {
333 String::new()
334 } else {
335 let mut parts: Vec<String> = vec!["<a href=\"/\">Home</a>".into()];
336 for (label, href) in breadcrumbs {
337 parts.push(match href {
338 Some(h) => format!("<a href=\"{}\">{}</a>", escape_attr(h), html_escape(label)),
339 None => html_escape(label),
340 });
341 }
342 format!(
343 "<nav class=\"breadcrumbs\">{}</nav>",
344 parts.join(" <span class=\"crumb-sep\">/</span> ")
345 )
346 };
347 let head_extra = config
350 .map(|c| {
351 let mut extra = String::new();
352 if let Some(css) = &c.stylesheet {
353 extra.push_str(&format!(
354 "<link rel=\"stylesheet\" href=\"{}\">",
355 escape_attr(&site_url(&c.base_path, css))
356 ));
357 }
358 if let Some(shim) = &c.island_shim {
359 extra.push_str(&format!(
360 "<script type=\"module\" src=\"{}\"></script>",
361 escape_attr(&site_url(&c.base_path, shim))
362 ));
363 }
364 extra
365 })
366 .unwrap_or_default();
367 format!(
368 "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
369<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
370<title>{t}</title>\
371<meta name=\"description\" content=\"{d}\">{canonical_tags}\
372<meta property=\"og:type\" content=\"article\">\
373<meta property=\"og:title\" content=\"{t}\">\
374<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
375<meta name=\"twitter:card\" content=\"summary\">\
376<meta name=\"twitter:title\" content=\"{t}\">\
377<meta name=\"twitter:description\" content=\"{d}\">\
378{head_extra}{og_image_tag}{feed_link}{json_ld_tag}</head><body>{breadcrumb_markup}{body}</body></html>",
379 t = escape_attr(title),
380 d = escape_attr(description),
381 breadcrumb_markup = breadcrumb_markup
382 )
383}
384
385#[must_use]
388pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
389 let mut out = format!("# {}\n\n", config.site_title);
390 if !config.author.is_empty() {
391 out.push_str(&format!("By {}.\n\n", config.author));
392 }
393 for page in pages {
394 out.push_str(&format!(
395 "- [{t}]({u}/{r}): {d}\n",
396 t = page.title,
397 u = config.base_url,
398 r = page.route,
399 d = page.description
400 ));
401 }
402 out
403}
404
405#[must_use]
409pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
410 let mut out = String::from(
411 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
412 );
413 let mut sorted: Vec<&SeoPage> = pages.iter().collect();
414 sorted.sort_by(|a, b| a.route.cmp(&b.route));
415 for page in sorted {
416 let lastmod = page
417 .date
418 .as_ref()
419 .map(|d| format!("<lastmod>{d}</lastmod>"))
420 .unwrap_or_default();
421 out.push_str(&format!(
422 "<url><loc>{}/{}</loc>{lastmod}</url>\n",
423 config.base_url, page.route
424 ));
425 }
426 out.push_str("</urlset>\n");
427 out
428}
429
430#[must_use]
432pub fn robots_txt(config: &SiteConfig) -> String {
433 let policy = config.ai_crawlers.as_str();
434 let mut out =
435 format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
436 match policy {
437 "block-all" => {
438 out.push_str("User-agent: *\nDisallow: /\n");
439 }
440 "block-training" => {
441 for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
442 out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
443 }
444 out.push_str("User-agent: *\nAllow: /\n");
445 }
446 _ => {
447 out.push_str("User-agent: *\nAllow: /\n");
448 }
449 }
450 out.push_str(&format!("Sitemap: {}/sitemap.xml\n", config.base_url));
451 out
452}
453
454#[must_use]
458pub fn atom_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
459 let mut dated: Vec<&SeoPage> = pages.iter().filter(|p| p.date.is_some()).collect();
460 dated.sort_by(|a, b| b.date.as_deref().cmp(&a.date.as_deref()));
461 let mut out = String::from(
462 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n",
463 );
464 out.push_str(&format!(
465 "<title>{}</title>\n",
466 html_escape(&config.site_title)
467 ));
468 if !config.author.is_empty() {
469 out.push_str(&format!(
470 "<author><name>{}</name></author>\n",
471 html_escape(&config.author)
472 ));
473 }
474 let self_url = format!("{}/atom.xml", config.base_url);
475 out.push_str(&format!(
476 "<link rel=\"self\" href=\"{}\"/>\n<link rel=\"alternate\" href=\"{}\"/>\n<id>{}/</id>\n",
477 html_escape(&self_url),
478 config.base_url,
479 config.base_url,
480 ));
481 if let Some(newest) = dated.first() {
482 if let Some(date) = &newest.date {
483 out.push_str(&format!("<updated>{date}T00:00:00Z</updated>\n"));
484 }
485 }
486 for page in dated {
487 let url = format!("{}/{}", config.base_url, page.route);
488 out.push_str(&format!(
489 "<entry><title>{t}</title><link rel=\"alternate\" href=\"{u}\"/><id>{u}</id><published>{d}</published><summary>{s}</summary></entry>\n",
490 t = html_escape(&page.title),
491 u = html_escape(&url),
492 d = page.date.as_deref().unwrap_or(""),
493 s = html_escape(&page.description),
494 ));
495 }
496 out.push_str("</feed>\n");
497 out
498}