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 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 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#[derive(Debug, Clone, Default, PartialEq)]
155pub struct PageMeta {
156 pub title: Option<String>,
158 pub description: Option<String>,
160 pub slug: Option<String>,
162 pub date: Option<String>,
164}
165
166#[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 let after = &rest[close + 4..];
194 (meta, after.trim_start_matches('\n').to_string())
195}
196
197#[must_use]
199pub fn first_h1(body: &str) -> Option<String> {
200 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#[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#[must_use]
228pub fn plain_text(body: &str) -> String {
229 let text = strip_tags(body);
230 text.split_whitespace().collect::<Vec<_>>().join(" ")
231}
232
233fn 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
270fn escape_attr(text: &str) -> String {
273 html_escape(text).replace('"', """)
274}
275
276#[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 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#[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#[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#[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#[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}