src / web / pageArchive.ts

import { randomBytes } from "node:crypto";
import { mkdir, open, readFile, rename, stat } from "node:fs/promises";
import { homedir } from "node:os";
import { isAbsolute, join } from "node:path";
import { escapeHtml, extractHtml, type HtmlText } from "./html";
export const PAGE_LIMIT = 32 * 1024 * 1024;
export interface SavedPage extends HtmlText {
  version: 1; pageId: string; url: string; retrievedAt: string; raw: string;
  format: "html" | "text"; encoding: string; source: "direct" | "jina";
}
export class PageArchive {
  readonly root: string;
  constructor(base = process.env.LMSTUDIO_WEB_ARCHIVE_DIR ?? join(homedir(), ".lmstudio", "plugin-data", "web-document-archive", "v1")) {
    if (!isAbsolute(base)) throw new Error("LMSTUDIO_WEB_ARCHIVE_DIR must be an absolute path.");
    this.root = join(base, "pages");
  }
  private path(id: string) {
    if (!/^[a-f0-9]{32}$/.test(id)) throw new Error("Invalid saved page ID.");
    return join(this.root, `${id}.json`);
  }
  async save(input: {raw: string; url: string; format?: "html" | "text"; encoding?: string; source?: "direct" | "jina"}, signal?: AbortSignal): Promise<SavedPage> {
    signal?.throwIfAborted();
    const url = new URL(input.url);
    if (!/^https?:$/.test(url.protocol)) throw new Error("Saved page URL must use HTTP(S).");
    if (url.href.length > 4096 || Buffer.byteLength(input.raw) > PAGE_LIMIT) throw new Error("Saved page exceeds URL or 32 MiB content limit.");
    const format = input.format ?? "html";
    const parsed = extractHtml(format === "html" ? input.raw : `<pre>${escapeHtml(input.raw)}</pre>`, url.href);
    const pageId = randomBytes(16).toString("hex");
    const page: SavedPage = {...parsed, version: 1, pageId, url: url.href, raw: input.raw, format,
      encoding: input.encoding ?? "utf-8", source: input.source ?? "direct", retrievedAt: new Date().toISOString()};
    const serialized = JSON.stringify(page);
    if (Buffer.byteLength(serialized) > PAGE_LIMIT * 7) throw new Error("Saved page index is too large.");
    signal?.throwIfAborted();
    await mkdir(this.root, {recursive: true});
    const target = this.path(pageId), temporary = `${target}.${process.pid}.tmp`;
    const file = await open(temporary, "wx", 0o600);
    try { await file.writeFile(serialized); } finally { await file.close(); }
    await rename(temporary, target);
    return page;
  }
  async read(pageId: string, signal?: AbortSignal): Promise<SavedPage> {
    signal?.throwIfAborted();
    const path = this.path(pageId);
    if ((await stat(path)).size > PAGE_LIMIT * 7) throw new Error("Saved page index is too large.");
    const page = JSON.parse(await readFile(path, {encoding: "utf8", signal})) as SavedPage;
    if (page.version !== 1 || page.pageId !== pageId || typeof page.raw !== "string" || typeof page.text !== "string"
      || !page.html || page.html.version !== 1 || !Array.isArray(page.html.blocks) || page.html.blocks.length > 20000
      || !["html", "text"].includes(page.format) || !/^https?:\/\//i.test(page.url)) throw new Error("Invalid saved page format.");
    return page;
  }
}