parse-worker.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Parse Worker
  3. *
  4. * Runs tree-sitter parsing in a separate thread so the main thread
  5. * stays unblocked and the UI animation renders smoothly.
  6. */
  7. import { parentPort } from 'worker_threads';
  8. import { extractFromSource } from './tree-sitter';
  9. import { detectLanguage, loadGrammarsForLanguages, resetParser } from './grammars';
  10. import type { Language, ExtractionResult } from '../types';
  11. const PARSER_RESET_INTERVAL = 5000;
  12. const parseCounts = new Map<Language, number>();
  13. parentPort!.on('message', async (msg: { type: string; id?: number; filePath?: string; content?: string; languages?: Language[] }) => {
  14. if (msg.type === 'load-grammars') {
  15. await loadGrammarsForLanguages(msg.languages!);
  16. parentPort!.postMessage({ type: 'grammars-loaded' });
  17. } else if (msg.type === 'parse') {
  18. const { id, filePath, content } = msg;
  19. try {
  20. const language = detectLanguage(filePath!);
  21. const result: ExtractionResult = extractFromSource(filePath!, content!, language);
  22. // Periodic parser reset to reclaim WASM heap memory
  23. const count = (parseCounts.get(language) ?? 0) + 1;
  24. parseCounts.set(language, count);
  25. if (count % PARSER_RESET_INTERVAL === 0) {
  26. resetParser(language);
  27. }
  28. parentPort!.postMessage({ type: 'parse-result', id, result });
  29. } catch (err) {
  30. const message = err instanceof Error ? err.message : String(err);
  31. parentPort!.postMessage({
  32. type: 'parse-result',
  33. id,
  34. result: {
  35. nodes: [],
  36. edges: [],
  37. unresolvedReferences: [],
  38. errors: [{ message: `Parse worker error: ${message}`, filePath: filePath!, severity: 'error', code: 'parse_error' }],
  39. durationMs: 0,
  40. } satisfies ExtractionResult,
  41. });
  42. }
  43. } else if (msg.type === 'shutdown') {
  44. parentPort!.postMessage({ type: 'shutdown-ack' });
  45. }
  46. });