use wasm_bindgen::prelude::*;
use repoask_core::index::InvertedIndex;
use repoask_core::types::IndexDocument;
#[wasm_bindgen]
pub struct RepoIndex {
documents: Vec<IndexDocument>,
index: Option<InvertedIndex>,
}
#[wasm_bindgen]
impl RepoIndex {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self {
documents: Vec::new(),
index: None,
}
}
#[wasm_bindgen(js_name = "addFile")]
pub fn add_file(&mut self, filepath: &str, content: &str) {
let docs = repoask_parser::parse_file_lenient(filepath, content);
self.documents.extend(docs);
}
pub fn build(&mut self) {
let docs = std::mem::take(&mut self.documents);
self.index = Some(InvertedIndex::build(docs));
}
pub fn search(&self, query: &str, limit: usize) -> Result<String, JsError> {
let index = self
.index
.as_ref()
.ok_or_else(|| JsError::new("index not built: call build() first"))?;
let results = index.search(query, limit);
serde_json::to_string(&results).map_err(|e| JsError::new(&e.to_string()))
}
#[wasm_bindgen(js_name = "docCount")]
pub fn doc_count(&self) -> usize {
match &self.index {
Some(idx) => idx.doc_count(),
None => self.documents.len(),
}
}
}
impl Default for RepoIndex {
fn default() -> Self {
Self::new()
}
}