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