All files vault-indexer.ts

88.51% Statements 131/148
77.77% Branches 42/54
83.33% Functions 20/24
89.85% Lines 124/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372      3x                       1x       2x       1x 1x                   34x             18x                                                               71x       71x 71x       38x 3x     35x       35x 35x   3x 3x         3x 1x 1x 1x             34x 34x 34x 34x   34x 53x 38x     34x 2x 2x                 34x               34x 34x 34x 34x       34x           34x 34x 18x       18x 18x   63x 63x 62x 62x 62x 53x           53x 53x 53x       9x   1x       1x         18x 63x   18x               34x     34x       112x                                                     112x     469x       69x 69x 69x     69x 69x 2x 2x 2x 2x 3x 3x 3x 3x 1x 1x   2x 2x 2x                 69x 69x 12x     69x 69x 69x     69x           69x   69x               67x 67x   67x 73x 73x 73x   73x           73x         1x 1x     73x 1x 1x     73x 4x 4x     73x 58x 58x     73x 56x 56x     73x 63x 63x       67x               145x 145x 144x 144x 122x       72x 72x       3x     3x      
// src/vault-indexer.ts
 
import { VaultIndexEntry } from './types';
import { Logger } from './utils';
 
interface Cache {
  get(key: string): Promise<string | null>;
  put(key: string, value: string): Promise<void>;
  clear(): Promise<void>;
}
 
class InMemoryCache implements Cache {
  private store: Map<string, string>;
 
  constructor() {
    this.store = new Map();
  }
 
  get(key: string): Promise<string | null> {
    return Promise.resolve(this.store.get(key) || null);
  }
 
  put(key: string, value: string): Promise<void> {
    this.store.set(key, value);
    return Promise.resolve();
  }
 
  clear(): Promise<void> {
    this.store.clear();
    return Promise.resolve();
  }
}
 
class CancellationToken {
  private cancelled = false;
 
  cancel(): void {
    this.cancelled = true;
  }
 
  get isCancelled(): boolean {
    return this.cancelled;
  }
}
 
interface Frontmatter {
  title?: string;
  tags?: string;
}
 
interface VaultFile {
  basename: string;
  path: string;
}
 
interface VaultLike {
  getMarkdownFiles(): VaultFile[];
  read(file: VaultFile): Promise<string>;
}
 
interface TokenizedContent {
  tokens: string[];
  headings: string[];
  frontmatter: Frontmatter;
  firstParagraph?: string;
}
 
interface ScoreResult {
  score: number;
  matchedFields: string[];
}
 
class VaultIndexer {
  private vault: VaultLike | null = null;
  private cache?: Cache;
 
  constructor(vault: VaultLike, cache?: Cache) {
    this.vault = vault;
    this.cache = cache;
  }
 
  async searchVault(query: string, limit: number = 5): Promise<VaultIndexEntry[]> {
    if (!query || !query.trim()) {
      return [];
    }
 
    Iif (!this.vault) {
      throw new Error('Vault-like object not provided to VaultIndexer');
    }
 
    const cacheKey = `query:${query.trim()}:limit:${limit}`;
    if (this.cache) {
      let cachedResults;
      try {
        cachedResults = await this.cache.get(cacheKey);
      } catch {
        // Ignore cache retrieval errors and continue with normal processing
        cachedResults = null;
      }
      if (cachedResults) {
        try {
          const parsedResults = JSON.parse(cachedResults) as VaultIndexEntry[];
          return parsedResults.slice(0, limit);
        } catch {
          // Ignore cache parse errors and continue with normal processing
        }
      }
    }
 
    const queryTokens = this.tokenize(query.trim());
    const vault = this.vault;
    const allFiles = vault.getMarkdownFiles();
    const results = await this.processFilesInBatches(vault, allFiles, queryTokens);
 
    const filteredResults = results
      .filter((result): result is NonNullable<typeof result> => result !== null)
      .sort((a, b) => b.score - a.score)
      .slice(0, limit);
 
    if (this.cache) {
      try {
        await this.cache.put(cacheKey, JSON.stringify(filteredResults));
      } catch (error) {
        Logger.warn(
          `Failed to cache results for query "${query}": ${error instanceof Error ? error.message : String(error)}`,
          'vault-indexer'
        );
      }
    }
 
    return filteredResults;
  }
 
  private async processFilesInBatches(
    vault: VaultLike,
    files: VaultFile[],
    queryTokens: string[]
  ): Promise<Array<VaultIndexEntry | null>> {
    const batchSize = 10;
    const results: VaultIndexEntry[] = [];
    const seenPaths = new Set<string>();
    const cancellationToken = new CancellationToken();
    // Removed unused processedCount variable
 
    // Set up a check for cancellation every 100 files
    const checkInterval = setInterval(() => {
      Iif (cancellationToken.isCancelled) {
        clearInterval(checkInterval);
      }
    }, 100);
 
    try {
      for (let i = 0; i < files.length; i += batchSize) {
        Iif (cancellationToken.isCancelled) {
          break;
        }
 
        const batch = files.slice(i, i + batchSize);
        const batchResults = await Promise.all(
          batch.map(async (file) => {
            try {
              const content = await vault.read(file);
              const tokenized = this.tokenizeContent(content);
              const scoreResult = this.calculateWeightedScore(tokenized, queryTokens, file);
              if (scoreResult.score > 0) {
                const entry: VaultIndexEntry = {
                  path: file.path,
                  title: file.basename.replace(/\.md$/, ''),
                  content: content.substring(0, 500),
                  score: scoreResult.score,
                };
                if (!seenPaths.has(entry.path)) {
                  seenPaths.add(entry.path);
                  return entry;
                }
                return null;
              }
              return null;
            } catch (error) {
              Logger.warn(
                `Failed to process ${file.path}: ${error instanceof Error ? error.message : String(error)}`,
                'vault-indexer'
              );
              return null;
            }
          })
        );
 
        const validResults = batchResults.filter(
          (result): result is NonNullable<typeof result> => result !== null
        );
        results.push(...validResults);
 
        // Continue processing all files to ensure we don't miss higher-scoring results
        // even if we've already found some matches
 
        // Removed processedCount increment
      }
    } finally {
      clearInterval(checkInterval);
    }
 
    return results;
  }
 
  private tokenize(text: string): string[] {
    const stopWords = new Set([
      'the',
      'a',
      'an',
      'and',
      'or',
      'but',
      'is',
      'are',
      'was',
      'were',
      'in',
      'on',
      'at',
      'to',
      'of',
      'for',
      'with',
      'as',
      'by',
      'it',
      'its',
      'that',
      'this',
      'these',
      'those',
    ]);
    return text
      .toLowerCase()
      .split(/\W+/)
      .filter((token) => token.length > 1 && !stopWords.has(token));
  }
 
  private tokenizeContent(content: string): TokenizedContent {
    const tokens: string[] = [];
    const headings: string[] = [];
    const frontmatter: Frontmatter = {};
    let firstParagraph: string | undefined;
 
    const frontmatterMatch = content.match(/^---(.*?)---/s);
    if (frontmatterMatch) {
      try {
        const frontmatterContent = frontmatterMatch[1];
        const lines = frontmatterContent.trim().split('\n');
        for (const line of lines) {
          const [key, ...valueParts] = line.split(':');
          Iif (!key) continue;
          const value = valueParts.join(':').trim();
          if (key.trim() === 'title') {
            if (value) {
              frontmatter.title = value;
            }
          } else if (key.trim() === 'tags') {
            if (value) {
              frontmatter.tags = value;
            }
          }
        }
      } catch {
        Logger.warn('Failed to parse frontmatter', 'vault-indexer');
      }
    }
 
    const headingMatches = content.match(/^#{1,6} (.*?)$/gm);
    if (headingMatches) {
      headings.push(...headingMatches.map((h: string) => h.replace(/^#{1,6} /, '')));
    }
 
    const paragraphMatch = content.match(/^([^#]*?)(?=#|\n\n|$)/s);
    if (paragraphMatch) {
      firstParagraph = paragraphMatch[1].trim();
    }
 
    const allText = content
      .replace(/^---.*?---/s, '')
      .replace(/^#.*?$/gm, '')
      .replace(/```.*?```/gs, '')
      .replace(/`.*?`/g, '')
      .replace(/\[.*?\]\(.*?\)/g, '');
    tokens.push(...this.tokenize(allText));
 
    return { tokens, headings, frontmatter, firstParagraph };
  }
 
  private calculateWeightedScore(
    tokenized: TokenizedContent,
    queryTokens: string[],
    file?: VaultFile
  ): ScoreResult {
    let totalScore = 0;
    const matchedTokens: Set<string> = new Set<string>();
 
    for (const queryToken of queryTokens) {
      let tokenScore = 0;
      const stemmed = this.stemToken(queryToken);
      let matched = false;
 
      Iif (
        tokenized.frontmatter?.title &&
        this.exactMatch(tokenized.frontmatter.title, queryToken)
      ) {
        tokenScore += 3;
        matched = true;
      } else if (
        file &&
        file.basename &&
        this.exactMatch(file.basename.replace(/\.md$/, ''), queryToken)
      ) {
        tokenScore += 3;
        matched = true;
      }
 
      if (tokenized.frontmatter?.tags && this.exactMatch(tokenized.frontmatter.tags, queryToken)) {
        tokenScore += 2.5;
        matched = true;
      }
 
      if (tokenized.headings.some((heading: string) => heading.toLowerCase().includes(stemmed))) {
        tokenScore += 5;
        matched = true;
      }
 
      if (tokenized.firstParagraph && tokenized.firstParagraph.toLowerCase().includes(stemmed)) {
        tokenScore += 1.5;
        matched = true;
      }
 
      if (tokenized.tokens.includes(stemmed)) {
        tokenScore += 1;
        matched = true;
      }
 
      if (matched) {
        totalScore += tokenScore;
        matchedTokens.add(queryToken);
      }
    }
 
    return {
      score: totalScore,
      matchedFields: Array.from(matchedTokens),
    };
  }
 
  private stemToken(token: string): string {
    // Improved stemmer that handles edge cases
    Iif (token.length <= 3) return token; // Don't stem very short tokens
    if (token.endsWith('s')) return token.slice(0, -1);
    Iif (token.endsWith('ed') && token.length > 4) return token.slice(0, -2); // Don't stem 3-letter words ending in ed
    if (token.endsWith('ing') && token.length > 5) return token.slice(0, -3); // Don't stem 4-letter words ending in ing
    return token;
  }
 
  private exactMatch(content: string, token: string): boolean {
    const stemmedToken = this.stemToken(token);
    return content.toLowerCase().includes(stemmedToken);
  }
}
 
export { VaultIndexer, Cache, InMemoryCache, CancellationToken };
 
// Convenience method to create a VaultIndexer with an in-memory cache
export function createVaultIndexerWithCache(vault: VaultLike): VaultIndexer {
  return new VaultIndexer(vault, new InMemoryCache());
}