use serde::Serialize;
use std::{collections::BTreeMap, fs, path::Path};
use tracing::info;
pub const SNIPPET_CHARS: usize = 160;
const SHARD_COUNT: usize = 16;
#[derive(Serialize, Debug)]
pub struct ChunkMeta {
pub heading_path: Vec<String>,
pub anchor: String,
pub snippet: String,
}
#[derive(Serialize, Debug)]
pub struct DocMeta {
pub id: usize,
pub lang: String,
pub title: String,
pub url: String,
pub snippet: String,
pub document_id: String,
pub revision: String,
pub chunks: Vec<ChunkMeta>,
}
#[derive(Serialize, Debug)]
struct Shard {
index: BTreeMap<String, Vec<[usize; 2]>>,
}
#[derive(Serialize)]
struct SearchMeta {
docs: Vec<DocMeta>,
shards: Vec<String>, }
#[derive(Debug)]
pub struct SearchDoc {
pub lang: String,
pub title: String,
pub page_path: String,
pub document_id: String,
pub revision: String,
pub chunks: Vec<SearchChunk>,
}
#[derive(Debug)]
pub struct SearchChunk {
pub heading_path: Vec<String>,
pub anchor: String,
pub source_text: String,
}
pub fn write_index(out: &Path, docs: &[SearchDoc], base: &str) -> anyhow::Result<()> {
let mut metas: Vec<DocMeta> = Vec::new();
let mut shards: Vec<Shard> = (0..SHARD_COUNT)
.map(|_| Shard {
index: BTreeMap::new(),
})
.collect();
let mut doc_id = 0usize;
for doc in docs {
let url = if base.is_empty() {
format!("/{}", doc.page_path)
} else {
format!("{base}/{}", doc.page_path)
};
let mut chunk_metas: Vec<ChunkMeta> = Vec::with_capacity(doc.chunks.len());
for (chunk_idx, chunk) in doc.chunks.iter().enumerate() {
let text = plain_text(&chunk.source_text);
let snippet = truncate_chars(&text, SNIPPET_CHARS);
chunk_metas.push(ChunkMeta {
heading_path: chunk.heading_path.clone(),
anchor: chunk.anchor.clone(),
snippet,
});
let mut indexable = chunk.heading_path.join(" ");
indexable.push(' ');
indexable.push_str(&text);
for token in tokenize(&indexable) {
let shard_idx = shard_for(&token);
let entry = shards[shard_idx].index.entry(token).or_default();
let posting = [doc_id, chunk_idx];
if entry.last() != Some(&posting) {
entry.push(posting);
}
}
}
let snippet = chunk_metas
.first()
.map(|c| c.snippet.clone())
.unwrap_or_default();
metas.push(DocMeta {
id: doc_id,
lang: doc.lang.clone(),
title: doc.title.clone(),
url,
snippet,
document_id: doc.document_id.clone(),
revision: doc.revision.clone(),
chunks: chunk_metas,
});
doc_id += 1;
}
let mut shard_names: Vec<String> = Vec::with_capacity(SHARD_COUNT);
for (i, shard) in shards.iter().enumerate() {
let name = format!("search_i_{:02}.json", i);
let json = serde_json::to_string(&shard.index)?;
fs::write(out.join(&name), &json)?;
shard_names.push(name);
}
let meta = SearchMeta {
docs: metas,
shards: shard_names,
};
let meta_json = serde_json::to_string(&meta)?;
fs::write(out.join("search_meta.json"), &meta_json)?;
let chunk_total: usize = docs.iter().map(|d| d.chunks.len()).sum();
info!(
"search index: {} docs / {} chunks in {} shards",
doc_id, chunk_total, SHARD_COUNT
);
Ok(())
}
pub(crate) fn tokenize(text: &str) -> Vec<String> {
let mut tokens = Vec::new();
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
while i < chars.len() {
let ch = chars[i];
if ch.is_ascii_alphanumeric() {
let mut word = String::new();
while i < chars.len() {
let c = chars[i];
if c.is_ascii_alphanumeric() {
word.push(c.to_ascii_lowercase());
i += 1;
} else {
break;
}
}
if word.len() >= 2 {
tokens.push(word);
}
} else if is_cjk(ch) {
if i + 1 < chars.len() && is_cjk(chars[i + 1]) {
let bigram: String = [ch, chars[i + 1]].iter().collect();
tokens.push(bigram);
}
i += 1;
} else {
i += 1;
}
}
tokens
}
fn is_cjk(ch: char) -> bool {
matches!(
ch,
'\u{4E00}'..='\u{9FFF}' | '\u{3400}'..='\u{4DBF}' | '\u{F900}'..='\u{FAFF}' | '\u{3040}'..='\u{30FF}' | '\u{AC00}'..='\u{D7AF}' )
}
fn shard_for(word: &str) -> usize {
let first = word.chars().next().unwrap_or('?');
(first as usize) % SHARD_COUNT
}
fn strip_one_container(line: &str) -> Option<&str> {
let trimmed = line.trim_start();
if let Some(after) = trimmed.strip_prefix('>') {
return Some(after.trim_start());
}
let after = strip_list_marker(trimmed);
if after.len() < trimmed.len() {
return Some(after);
}
None
}
fn strip_container_markers(line: &str, depth: usize) -> &str {
let mut rest = line;
for _ in 0..depth {
match strip_one_container(rest) {
Some(after) => rest = after,
None => break,
}
}
rest
}
fn strip_list_marker(line: &str) -> &str {
let s = line.trim_start();
for marker in ["-", "*", "+"] {
if let Some(rest) = s.strip_prefix(marker) {
if rest.starts_with(char::is_whitespace) {
return rest.trim_start();
}
}
}
let digits = s.chars().take_while(|c| c.is_ascii_digit()).count();
if digits > 0 {
if let Some(rest) = s[digits..].strip_prefix('.') {
if rest.starts_with(char::is_whitespace) {
return rest.trim_start();
}
}
}
s
}
fn fence_opener(rest: &str) -> Option<(char, usize, String)> {
let lead = rest.chars().next()?;
if lead != '`' && lead != '~' {
return None;
}
let run = rest.chars().take_while(|&c| c == lead).count();
if run < 3 {
return None;
}
let info = rest[run..].trim().to_string();
if lead == '`' && info.contains('`') {
return None;
}
Some((lead, run, info))
}
fn is_markdown_info(info: &str) -> bool {
if info.is_empty() {
return false;
}
let lang = info.split_whitespace().next().unwrap_or("");
matches!(
lang.to_ascii_lowercase().as_str(),
"markdown" | "md" | "mdx" | "gfm" | "commonmark"
)
}
fn is_reference_definition(line: &str) -> bool {
let s = line.trim_start();
let mut chars = s.chars().peekable();
if chars.next() != Some('[') {
return false;
}
let mut depth = 1usize;
let mut saw_close = false;
let mut label_len = 0usize;
let mut escaped = false;
for c in chars.by_ref() {
if escaped {
escaped = false;
label_len += 1;
continue;
}
match c {
'\\' => escaped = true,
'[' => depth += 1,
']' => {
depth -= 1;
if depth == 0 {
saw_close = true;
break;
}
}
_ => label_len += 1,
}
if depth > 8 {
return false; }
}
if !saw_close || depth != 0 || label_len == 0 {
return false;
}
let rest: String = chars.collect();
let Some(after_colon) = rest.strip_prefix(':') else {
return false;
};
let mut dest = after_colon.trim_start();
if let Some(stripped) = dest.strip_prefix('<') {
let Some(end) = stripped.find('>') else {
return false;
};
dest = &stripped[end + 1..];
} else {
let token_len = dest.find(char::is_whitespace).unwrap_or(dest.len());
if token_len == 0 {
return false;
}
dest = &dest[token_len..];
}
let tail = dest.trim();
tail.is_empty()
|| (tail.starts_with('"') && tail.ends_with('"') && tail.len() >= 2)
|| (tail.starts_with('\'') && tail.ends_with('\'') && tail.len() >= 2)
|| (tail.starts_with('(') && tail.ends_with(')') && tail.len() >= 2)
}
struct FenceState {
ch: char,
len: usize,
depth: usize,
markdown: bool,
}
fn strip_link_targets_into(text: &str, out: &mut String) {
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
while i < chars.len() {
let image = chars[i] == '!' && i + 1 < chars.len() && chars[i + 1] == '[';
let link = chars[i] == '[';
if image || link {
let open = if image { i + 1 } else { i };
if let Some(close) = find_close_bracket(&chars, open) {
if chars.get(close + 1) == Some(&'(') {
if let Some(paren) = find_close_paren(&chars, close + 1) {
let inner: String = chars[open + 1..close].iter().collect();
strip_link_targets_into(&inner, out);
i = paren + 1;
while chars.get(i) == Some(&'[') {
if let Some(label) = find_close_bracket(&chars, i) {
out.push(' ');
i = label + 1;
} else {
break;
}
}
continue;
}
} else if chars.get(close + 1) == Some(&'[') {
let inner: String = chars[open + 1..close].iter().collect();
strip_link_targets_into(&inner, out);
i = close + 1;
while chars.get(i) == Some(&'[') {
if let Some(label) = find_close_bracket(&chars, i) {
out.push(' ');
i = label + 1;
} else {
break;
}
}
continue;
}
}
}
out.push(chars[i]);
i += 1;
}
}
pub(crate) fn plain_text(raw: &str) -> String {
let mut out = String::with_capacity(raw.len() / 2);
let mut fence: Option<FenceState> = None;
for raw_line in raw.lines() {
let line = raw_line.trim();
let mut indent = 0usize;
for c in raw_line.chars() {
match c {
' ' => indent += 1,
'\t' => indent = (indent / 4 + 1) * 4,
_ => break,
}
}
let mut depth = 0usize;
let mut body = line;
while let Some(after) = strip_one_container(body) {
depth += 1;
body = after;
}
if fence.is_none() && indent < 4 && is_reference_definition(body) {
continue;
}
let opener = fence_opener(body);
if let Some(state) = &fence {
let candidate = strip_container_markers(line, state.depth);
if let Some((ch, run, info)) = fence_opener(candidate) {
if ch == state.ch && run >= state.len && info.is_empty() {
fence = None;
continue; }
}
if !out.is_empty() {
out.push(' ');
}
let literal = strip_container_markers(line, state.depth);
if state.markdown {
strip_link_targets_into(literal, &mut out);
} else {
out.push_str(literal);
}
continue;
}
if let Some((ch, run, info)) = opener {
fence = Some(FenceState {
ch,
len: run,
depth,
markdown: is_markdown_info(&info),
});
continue; }
let mut rest = body;
loop {
let trimmed = rest.trim_start();
let mut stripped = None;
for prefix in ["-", "+", "*"] {
if let Some(after) = trimmed.strip_prefix(prefix) {
if after.starts_with(char::is_whitespace) {
stripped = Some(after);
break;
}
}
}
if let Some(after) = stripped {
rest = after.trim_start();
continue;
}
if let Some(after) = trimmed.strip_prefix('>') {
rest = after.trim_start();
continue;
}
let hashes = trimmed.chars().take_while(|&c| c == '#').count();
if (1..=6).contains(&hashes)
&& matches!(
trimmed[hashes..].chars().next(),
None | Some(' ') | Some('\t')
)
{
rest = trimmed[hashes..].trim_start();
continue;
}
let digits = trimmed.chars().take_while(|c| c.is_ascii_digit()).count();
if digits > 0
&& matches!(trimmed[digits..].chars().next(), Some('.'))
&& matches!(trimmed[digits + 1..].chars().next(), Some(' '))
{
rest = trimmed[digits + 1..].trim_start();
continue;
}
rest = trimmed;
break;
}
if !out.is_empty() {
out.push(' ');
}
strip_inline_markers_into(rest, &mut out);
}
let mut collapsed = String::with_capacity(out.len());
let mut prev_ws = false;
for ch in out.chars() {
if ch.is_whitespace() {
if !prev_ws {
collapsed.push(' ');
}
prev_ws = true;
} else {
collapsed.push(ch);
prev_ws = false;
}
}
collapsed.trim().to_string()
}
pub(crate) fn truncate_chars(text: &str, limit: usize) -> String {
text.chars().take(limit).collect()
}
fn strip_inline_markers_into(text: &str, out: &mut String) {
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
while i < chars.len() {
let run_len =
|i: usize, c: char| -> usize { chars[i..].iter().take_while(|&&x| x == c).count() };
let c = chars[i];
match c {
'`' => {
let run = run_len(i, '`');
if let Some(close_rel) = chars[i + run..].iter().position(|&x| x == '`') {
let inner: String = chars[i + run..i + run + close_rel].iter().collect();
out.push_str(&inner);
i += run + close_rel + 1;
} else {
i += run;
}
}
'*' | '_' => {
let run = run_len(i, c);
if run == 1 && c == '_' {
out.push(c);
}
i += run;
}
'!' if i + 1 < chars.len() && chars[i + 1] == '[' => {
if let Some(close) = find_close_bracket(&chars, i + 1) {
let inner: String = chars[i + 2..close].iter().collect();
strip_inline_markers_into(&inner, out);
i = close + 1;
if i < chars.len() && chars[i] == '(' {
if let Some(parens) = find_close_paren(&chars, i) {
i = parens + 1;
}
}
while i < chars.len() && chars[i] == '[' {
if let Some(label) = find_close_bracket(&chars, i) {
out.push(' ');
i = label + 1;
} else {
break;
}
}
continue;
}
out.push(c);
i += 1;
}
'[' => {
if let Some(close) = find_close_bracket(&chars, i) {
let inner: String = chars[i + 1..close].iter().collect();
if inner.is_empty() {
out.push(c);
i += 1;
continue;
}
strip_inline_markers_into(&inner, out);
i = close + 1;
if i < chars.len() && chars[i] == '(' {
if let Some(parens) = find_close_paren(&chars, i) {
i = parens + 1;
}
}
while i < chars.len() && chars[i] == '[' {
if let Some(label) = find_close_bracket(&chars, i) {
out.push(' ');
i = label + 1;
} else {
break;
}
}
continue;
}
out.push(c);
i += 1;
}
'<' => {
if let Some(gt) = chars[i..].iter().position(|&x| x == '>') {
out.push(' ');
i += gt + 1;
} else {
out.push(c);
i += 1;
}
}
_ => {
out.push(c);
i += 1;
}
}
}
}
fn find_close_bracket(chars: &[char], open: usize) -> Option<usize> {
let mut depth = 0usize;
for (p, &c) in chars[open..].iter().enumerate() {
match c {
'[' => depth += 1,
']' => {
depth -= 1;
if depth == 0 {
return Some(open + p);
}
}
_ => {}
}
}
None
}
fn find_close_paren(chars: &[char], open: usize) -> Option<usize> {
let mut depth = 0usize;
for (p, &c) in chars[open..].iter().enumerate() {
match c {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(open + p);
}
}
_ => {}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokenize_latin_words() {
let t = tokenize("Hello World, build a site!");
assert!(t.iter().any(|s| s == "hello"));
assert!(t.iter().any(|s| s == "world"));
assert!(t.iter().any(|s| s == "build"));
assert!(t.iter().any(|s| s == "site"));
assert!(!t.iter().any(|s| s == "a")); }
#[test]
fn tokenize_cjk_bigrams() {
let t = tokenize("构建网站");
assert!(t.iter().any(|s| s == "构建"));
assert!(t.iter().any(|s| s == "建网"));
assert!(t.iter().any(|s| s == "网站"));
}
#[test]
fn shard_for_pins_the_concrete_mapping_the_frontend_uses() {
assert_eq!(shard_for("lagrange"), 12);
assert_eq!(shard_for("dir"), 4);
assert_eq!(shard_for("anchor"), 1);
let js = include_str!("site.rs");
assert!(
js.contains("charCodeAt(0)%16") || js.contains("charCodeAt(0) % 16"),
"the embedded JS must shard on the FIRST character modulo 16"
);
for probe in ["a", "z", "9", "_", "运"] {
assert!(shard_for(probe) < SHARD_COUNT);
}
}
#[test]
fn plain_text_strips_block_and_inline_markers() {
assert_eq!(plain_text("# Heading\ntext"), "Heading text");
assert_eq!(plain_text("> quote **bold**"), "quote bold");
assert_eq!(plain_text("- item one\n2. item two"), "item one item two");
assert_eq!(plain_text("see [docs](https://x.y) now"), "see docs now");
assert_eq!(plain_text("keep snake_case"), "keep snake_case");
assert_eq!(plain_text("```\ncode line\n```"), "code line");
assert_eq!(plain_text("<b>bold</b> and <i>it</i>"), "bold and it");
assert_eq!(
plain_text("a<br>b <span class=\"x\">c</span>"),
"a b c",
"a dropped tag leaves a word boundary, never glues the neighbours"
);
}
#[test]
fn code_spans_keep_angle_brackets_verbatim() {
assert_eq!(
plain_text("run `lagrange build --src docs --out <dir>` now"),
"run lagrange build --src docs --out <dir> now"
);
assert_eq!(
plain_text("```html\n<p align=\"center\">x</p>\n```"),
"<p align=\"center\">x</p>"
);
assert_eq!(plain_text("a <b>bold</b> b"), "a bold b");
assert_eq!(plain_text("deploy --out <dir>"), "deploy --out");
}
#[test]
fn fence_bodies_keep_text_but_drop_link_targets() {
let fenced = "```markdown\n\n```";
let text = plain_text(fenced);
assert_eq!(text, "Dashboard shot", "alt text stays, URL does not");
assert!(!text.contains("webp"), "image target leaked: {text}");
let link = "```markdown\nsee [the guide](https://x.y/guide) here\n```";
assert_eq!(plain_text(link), "see the guide here");
assert_eq!(
plain_text("```html\n<p align=\"center\">x</p>\n```"),
"<p align=\"center\">x</p>"
);
assert_eq!(
plain_text("```bash\nlagrange --out <dir>\n```"),
"lagrange --out <dir>"
);
let tokens = tokenize(&plain_text("```markdown\n--out <dir> \n```"));
assert!(tokens.iter().any(|t| t == "dir"));
assert!(!tokens.iter().any(|t| t == "svg"));
}
#[test]
fn markdown_fenced_reference_links_keep_their_text() {
let raw = "```markdown\nsee [t][r] end\n```";
assert_eq!(plain_text(raw), "see t end");
let raw = "```markdown\nshot ![a][b] done\n```";
assert_eq!(plain_text(raw), "shot a done");
}
#[test]
fn fence_state_machine_handles_nesting_and_mixing() {
let nested = "````\n```bash\nlagrange --out <dir>\n```\n````";
assert_eq!(plain_text(nested), "```bash lagrange --out <dir> ```");
let mixed = "```\n~~~\ncode <dir>\n~~~\n```";
assert!(
plain_text(mixed).contains("<dir>"),
"mixed delimiters: {}",
plain_text(mixed)
);
let quoted = "> ```bash\n> lagrange --out <dir>\n> ```";
let text = plain_text(quoted);
assert!(text.contains("--out <dir>"), "quoted fence: {text}");
assert!(
!text.contains("bash"),
"the fence language tag is not prose: {text}"
);
}
#[test]
fn fence_bodies_keep_their_own_quote_markers() {
let quoted = "> ```\n> cargo build --offline\n> ```";
assert_eq!(plain_text(quoted), "cargo build --offline");
let prompt = "```\n> cargo build --offline\n```";
assert_eq!(plain_text(prompt), "> cargo build --offline");
let callout = "> ```markdown\n> > quoted line\n> ```";
assert_eq!(plain_text(callout), "> quoted line");
}
#[test]
fn reference_link_definitions_are_not_prose() {
let raw = "[deploy]: https://example.invalid/secret-deploy-path";
assert_eq!(plain_text(raw), "", "the definition line is metadata");
let tokens = tokenize(&plain_text(raw));
assert!(!tokens.iter().any(|t| t == "invalid" || t == "secret"));
let mixed = "See the guide.\n\n[guide]: https://x.y/g\n\nMore text.";
assert_eq!(plain_text(mixed), "See the guide. More text.");
}
#[test]
fn only_markdown_fences_project_link_targets() {
let code = "```rust\nlet v = arr[0](1);\n```";
assert_eq!(plain_text(code), "let v = arr[0](1);");
let code = "```\nmap[key](value);\n```";
assert_eq!(plain_text(code), "map[key](value);");
let md = "```markdown\nsee [the guide](https://x.y/g)\n```";
assert_eq!(plain_text(md), "see the guide");
assert_eq!(plain_text("```rust\nfn main() {}\n```"), "fn main() {}");
}
#[test]
fn a_fence_closes_only_on_a_bare_marker() {
let raw = "```\nalpha\n```rust\nbeta\n```";
assert_eq!(plain_text(raw), "alpha ```rust beta");
}
#[test]
fn container_prefixed_reference_definitions_are_metadata_too() {
for raw in [
"[a]: https://x.y/secret-path",
"> [a]: https://x.y/secret-path",
"> > [a]: https://x.y/secret-path",
"- [a]: https://x.y/secret-path",
"* [a]: https://x.y/secret-path",
] {
let text = plain_text(raw);
assert!(
!text.contains("secret-path"),
"definition target leaked for {raw:?}: {text}"
);
}
assert!(plain_text(" [a]: https://x.y/keep").contains("keep"));
let prose = "[a]: https://x.y/p and more words";
assert!(
plain_text(prose).contains("more words"),
"prose was deleted"
);
assert_eq!(plain_text("[a [b]]: https://x.y/p"), "");
}
#[test]
fn a_deeper_quote_marker_does_not_close_a_quoted_fence() {
let raw = "> ```\n> > ```\n> > inner\n> > ```\n> ```";
let text = plain_text(raw);
assert!(text.contains("inner"), "{text}");
assert!(
text.contains("```"),
"the inner ``` lines are literal content: {text}"
);
}
#[test]
fn a_longer_closing_fence_still_closes() {
let raw = "```\nalpha\n````\nsee [x](https://leak.test)";
let text = plain_text(raw);
assert!(text.contains("alpha"), "{text}");
assert!(
!text.contains("leak.test"),
"the fence must have closed: {text}"
);
let raw = "````\nalpha\n```\nkeep [x](https://kept.test)";
let text = plain_text(raw);
assert!(
text.contains("kept.test"),
"a shorter marker must not close: {text}"
);
}
#[test]
fn reference_links_keep_a_word_boundary() {
assert_eq!(plain_text("see [text][ref] end"), "see text end");
let tokens = tokenize(&plain_text("see [text][ref] end"));
assert!(tokens.iter().any(|t| t == "text"));
assert!(!tokens.iter().any(|t| t == "textref"));
}
#[test]
fn reference_images_drop_the_label_with_a_boundary() {
assert_eq!(plain_text("[img]"), "badge");
assert_eq!(plain_text("[img] done"), "badge done");
assert_eq!(plain_text("shot ![alt][ref] done"), "shot alt done");
let tokens = tokenize(&plain_text("shot ![alt][ref] done"));
assert!(!tokens.iter().any(|t| t.contains("altref")));
}
#[test]
fn an_empty_label_is_not_a_definition() {
assert_eq!(
plain_text("[]: https://x.y/visible"),
"[]: https://x.y/visible"
);
}
#[test]
fn an_escaped_bracket_does_not_end_the_label() {
let raw = "[a\\]b]: https://x.y/leaky-escaped";
assert_eq!(
plain_text(raw),
"",
"escaped label is one definition: {raw}"
);
}
#[test]
fn definition_detection_peels_containers_in_any_order() {
for raw in [
"> - [a]: https://x.y/secret-path",
"- > [a]: https://x.y/secret-path",
"* > [a]: https://x.y/secret-path",
"1. [a]: https://x.y/secret-path",
] {
assert!(
!plain_text(raw).contains("secret-path"),
"target leaked for {raw:?}: {}",
plain_text(raw)
);
}
}
#[test]
fn a_tab_indented_definition_is_code_and_stays() {
assert!(
plain_text("\t[a]: https://x.y/kept").contains("kept"),
"tab indent is a code block: {}",
plain_text("\t[a]: https://x.y/kept")
);
}
#[test]
fn a_list_prefixed_fence_closes_behind_a_list_marker() {
let raw = "- ```rust\nlet v = arr[0](1);\n- ```\nsee [t](https://leak.test)";
let text = plain_text(raw);
assert!(text.contains("let v = arr[0](1);"), "{text}");
assert!(
!text.contains("leak.test"),
"the fence must have closed at `- ``` `: {text}"
);
}
#[test]
fn adjacent_reference_labels_are_dropped_in_prose_links() {
assert_eq!(plain_text("see [t](u)[r] end"), "see t end");
assert_eq!(plain_text("see [t](u)[r][r2] end"), "see t end");
let tokens = tokenize(&plain_text("see [target](u)[r] end"));
assert!(!tokens.iter().any(|token| token == "tr"));
assert!(tokens.iter().any(|token| token == "target"));
}
#[test]
fn adjacent_reference_labels_are_dropped_in_prose_images() {
assert_eq!(plain_text("[c][d] done"), "a done");
}
#[test]
fn fence_after_target_reference_labels_are_dropped_in_fences() {
let raw = "```markdown\nsee [t](u)[r] end\n```";
assert_eq!(plain_text(raw), "see t end");
let raw = "```markdown\nsee [t](u)[r][r2] end\n```";
assert_eq!(plain_text(raw), "see t end");
}
#[test]
fn abutting_reference_labels_keep_their_boundary() {
assert_eq!(plain_text("see [text][ref]end"), "see text end");
assert_eq!(plain_text("see [text](u)[ref]end"), "see text end");
assert_eq!(plain_text("![alt][ref]done"), "alt done");
let raw = "```markdown\nsee [text][ref]end\n```";
assert_eq!(plain_text(raw), "see text end");
let tokens = tokenize(&plain_text("see [text][ref]end"));
assert!(!tokens.iter().any(|t| t == "textend"));
assert!(tokens.iter().any(|t| t == "text"));
}
#[test]
fn negative_numbers_are_not_list_items() {
assert_eq!(plain_text("-5 degrees"), "-5 degrees");
assert_eq!(plain_text("+7 items here"), "+7 items here");
assert_eq!(plain_text("-42 is the answer"), "-42 is the answer");
assert_eq!(plain_text("- 5 degrees"), "5 degrees");
assert_eq!(plain_text("+ item"), "item");
assert_eq!(plain_text("* star item"), "star item");
}
#[test]
fn a_list_then_quote_prefixed_fence_closes_behind_its_own_shape() {
let raw = "- > ```rust\nlet v = arr[0](1);\n- > ```\nsee [t](https://leak.test)";
let text = plain_text(raw);
assert!(text.contains("let v = arr[0](1);"), "{text}");
assert!(
!text.contains("leak.test"),
"the fence must have closed at `- > ``` `: {text}"
);
}
#[test]
fn badge_link_leaves_no_url_in_snippet_or_tokens() {
let raw = "[](./LICENSE)";
let text = plain_text(raw);
assert!(!text.contains("badge.svg"), "img url leaked: {text}");
assert!(!text.contains("./LICENSE"), "link url leaked: {text}");
assert!(!text.contains("http"), "unexpected url in: {text}");
assert_eq!(text, "License");
for token in tokenize(&text) {
assert!(!token.contains("badge"), "token {token}");
assert!(!token.contains("svg"), "token {token}");
assert!(!token.contains("http"), "token {token}");
}
}
#[test]
fn snippet_truncation_is_char_safe_for_multibyte_text() {
let cjk = "运行说明".repeat(60);
let cut = truncate_chars(&cjk, SNIPPET_CHARS);
assert_eq!(cut.chars().count(), SNIPPET_CHARS);
assert!(cjk.is_char_boundary(cut.len()));
let mixed = "a🚀b".repeat(80);
let cut = truncate_chars(&mixed, SNIPPET_CHARS);
assert_eq!(cut.chars().count(), SNIPPET_CHARS);
assert_eq!(truncate_chars("short", SNIPPET_CHARS), "short");
}
#[test]
fn shard_count_is_literally_sixteen_because_the_frontend_hardcodes_it() {
assert_eq!(SHARD_COUNT, 16, "src/site.rs JS computes `% 16`");
let js = include_str!("site.rs");
assert!(
js.contains("%16") || js.contains("% 16"),
"the embedded search JS must agree with SHARD_COUNT"
);
}
#[test]
fn postings_are_doc_then_chunk() {
let dir = tempfile::tempdir().unwrap();
let docs = vec![
SearchDoc {
lang: "en".into(),
title: "T".into(),
page_path: "t.html".into(),
document_id: "t".into(),
revision: "abc".into(),
chunks: vec![
SearchChunk {
heading_path: vec!["T".into()],
anchor: "t".into(),
source_text: "# T\n\ntargetword here".into(),
},
SearchChunk {
heading_path: vec!["U".into()],
anchor: "u".into(),
source_text: "## U\n\nother".into(),
},
],
},
SearchDoc {
lang: "en".into(),
title: "Second".into(),
page_path: "s.html".into(),
document_id: "s".into(),
revision: "def".into(),
chunks: vec![SearchChunk {
heading_path: vec!["S".into()],
anchor: "s".into(),
source_text: "# S\n\ntargetword again".into(),
}],
},
];
write_index(dir.path(), &docs, "").unwrap();
let mut hits = Vec::new();
for i in 0..SHARD_COUNT {
let shard: serde_json::Value = serde_json::from_str(
&fs::read_to_string(dir.path().join(format!("search_i_{i:02}.json"))).unwrap(),
)
.unwrap();
for (word, posts) in shard.as_object().unwrap() {
if word != "targetword" && word != "tar" {
continue;
}
for p in posts.as_array().unwrap() {
let pair: Vec<u64> = p
.as_array()
.unwrap()
.iter()
.map(|v| v.as_u64().unwrap())
.collect();
hits.push((word.clone(), pair));
}
}
}
assert!(!hits.is_empty(), "the probe word must be indexed");
for (_word, pair) in &hits {
assert_eq!(pair.len(), 2, "a posting is a two-element pair");
let (doc, chunk) = (pair[0], pair[1]);
assert!(doc < 2, "first element is the doc id: {pair:?}");
assert!(chunk <= 1, "second element is the chunk index: {pair:?}");
}
let mut exact: Vec<[u64; 2]> = hits.iter().map(|(_, p)| [p[0], p[1]]).collect();
exact.sort();
exact.dedup();
assert_eq!(
exact,
vec![[0, 0], [1, 0]],
"postings must be exactly [doc, chunk] pairs for these hits"
);
}
#[test]
fn shard_files_keep_the_sixteen_slice_contract() {
let dir = tempfile::tempdir().unwrap();
let docs = vec![SearchDoc {
lang: "en".into(),
title: "T".into(),
page_path: "t.html".into(),
document_id: "t".into(),
revision: "abc".into(),
chunks: vec![SearchChunk {
heading_path: vec!["T".into()],
anchor: "t".into(),
source_text: "# T\n\nbody words here".into(),
}],
}];
write_index(dir.path(), &docs, "").unwrap();
for i in 0..SHARD_COUNT {
assert!(dir.path().join(format!("search_i_{i:02}.json")).exists());
}
let raw = fs::read_to_string(dir.path().join("search_meta.json")).unwrap();
let meta: serde_json::Value = serde_json::from_str(&raw).unwrap();
let top = meta.as_object().unwrap();
assert_eq!(top.keys().collect::<Vec<_>>(), vec!["docs", "shards"]);
assert_eq!(meta["shards"].as_array().unwrap().len(), SHARD_COUNT);
let doc0 = &meta["docs"][0];
let keys: Vec<&str> = doc0
.as_object()
.unwrap()
.keys()
.map(|k| k.as_str())
.collect();
assert_eq!(
keys,
vec![
"chunks",
"document_id",
"id",
"lang",
"revision",
"snippet",
"title",
"url"
]
);
let mut total_postings = 0usize;
let mut words_seen = Vec::new();
for i in 0..SHARD_COUNT {
let shard: serde_json::Value = serde_json::from_str(
&fs::read_to_string(dir.path().join(format!("search_i_{i:02}.json"))).unwrap(),
)
.unwrap();
for (word, postings) in shard.as_object().unwrap() {
words_seen.push(word.clone());
for posting in postings.as_array().unwrap() {
assert_eq!(posting.as_array().unwrap().len(), 2, "posting {posting}");
assert_eq!(posting[0], 0, "doc id");
assert_eq!(posting[1], 0, "chunk index");
total_postings += 1;
}
}
}
assert_eq!(total_postings, 3, "words_seen = {words_seen:?}");
assert_eq!(words_seen.len(), 3);
}
#[test]
fn chunk_hit_indexes_the_chunk_heading_and_body() {
let dir = tempfile::tempdir().unwrap();
let docs = vec![SearchDoc {
lang: "zh-Hans".into(),
title: "指南".into(),
page_path: "guide.html".into(),
document_id: "guide".into(),
revision: "abc".into(),
chunks: vec![
SearchChunk {
heading_path: vec!["指南".to_string(), "安装".to_string()],
anchor: "安装".into(),
source_text: "## 安装\n\n运行 安装 命令".into(),
},
SearchChunk {
heading_path: vec!["指南".to_string(), "部署".to_string()],
anchor: "部署".into(),
source_text: "## 部署\n\n部署到服务器".into(),
},
],
}];
write_index(dir.path(), &docs, "/docs").unwrap();
let raw = fs::read_to_string(dir.path().join("search_meta.json")).unwrap();
let meta: serde_json::Value = serde_json::from_str(&raw).unwrap();
assert_eq!(meta["docs"][0]["url"], "/docs/guide.html");
let mut hit_chunk: Option<i64> = None;
for i in 0..SHARD_COUNT {
let shard: serde_json::Value = serde_json::from_str(
&fs::read_to_string(dir.path().join(format!("search_i_{i:02}.json"))).unwrap(),
)
.unwrap();
if let Some(postings) = shard.get("安装") {
hit_chunk = Some(postings[0][1].as_i64().unwrap());
}
}
assert_eq!(hit_chunk, Some(0), "安装 must resolve to chunk 0");
assert_eq!(meta["docs"][0]["chunks"][0]["anchor"], "安装");
assert!(meta["docs"][0]["chunks"][0]["snippet"]
.as_str()
.unwrap()
.contains("运行"));
}
}