src / fileSearch / documents.ts

import { extname } from "node:path";
import { decodeDocument, type DocumentEncoding } from "./encoding";
import { parseJson } from "./json";
import { extractHtml } from "./web/html";

export const MAX_FILE_BYTES = 32 * 1024 * 1024;
export const MAX_COLLECTION_BYTES = 128 * 1024 * 1024;
export const MAX_DOCUMENTS = 200;
const extensions = new Set([".txt", ".text", ".md", ".markdown", ".json", ".jsonl", ".ndjson", ".html", ".htm", ".csv", ".tsv", ".log", ".xml", ".yaml", ".yml"]);

export function supports(name: string): boolean { return extensions.has(extname(name).toLowerCase()); }

export function extractDocument(name: string, bytes: Buffer, encoding: DocumentEncoding = "auto", sourceUrl?: string) {
  if (!supports(name)) throw new Error(`Unsupported file type: ${name}. PDF and Office are not supported yet.`);
  if (bytes.length > MAX_FILE_BYTES) throw new Error(`File exceeds 32 MiB: ${name}`);
  const decoded = decodeDocument(name, bytes, encoding);
  let text = decoded.text;
  if (text.includes("\0")) throw new Error(`Binary data is not supported: ${name}`);
  text = text.replace(/\r\n?/g, "\n");
  const sourceHtml = /\.html?$/i.test(name) ? text : undefined;
  const extractedHtml = sourceHtml !== undefined ? extractHtml(sourceHtml, sourceUrl) : undefined;
  if (extractedHtml) text = extractedHtml.text;
  const json = /\.json$/i.test(name) ? parseJson(text) : undefined;
  return { ...decoded, text, json, sourceHtml, html: extractedHtml?.html };
}

export function extractText(name: string, bytes: Buffer, encoding: DocumentEncoding = "auto"): string {
  return extractDocument(name, bytes, encoding).text;
}