import { execFile } from 'node:child_process'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; export async function extractPdfText(pdf: Buffer, bin = 'pdftotext', timeoutMs = 30_000): Promise { const dir = await mkdtemp(join(tmpdir(), 'srs-pdf-')); try { const file = join(dir, 'result.pdf'); await writeFile(file, pdf); return await new Promise((resolve, reject) => { execFile( bin, ['-raw', '-enc', 'UTF-8', file, '-'], { encoding: 'utf8', maxBuffer: 20 * 1024 * 1024, timeout: timeoutMs }, (err, stdout) => { if (!err) return resolve(stdout.replace(/\r\n/g, '\n')); const missing = (err as NodeJS.ErrnoException).code === 'ENOENT'; reject(new Error(missing ? 'pdftotext not found: install poppler-utils' : `pdftotext failed: ${err.message}`)); }, ); }); } finally { await rm(dir, { recursive: true, force: true }); } }