import { PDFDocument } from 'pdf-lib' import { extractReportJson, IncompatibleReportVersionError } from './attachment' import type { Report } from '@/domain/schema/report' export type ImportErrorKind = | 'invalid_pdf' | 'incompatible_version' | 'no_attachment' /** * Localization-agnostic import error. Carries a kind discriminant + an * optional foundVersion so the caller (UI layer) can resolve the * user-facing message via the active i18n dict. */ export class ImportError extends Error { constructor( public readonly kind: ImportErrorKind, public readonly foundVersion?: number, ) { super(kind) this.name = 'ImportError' } } export async function importReportFromPdf(pdfBytes: Uint8Array): Promise { let pdfDoc: PDFDocument try { pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true }) } catch { throw new ImportError('invalid_pdf') } try { return await extractReportJson(pdfDoc) } catch (err) { if (err instanceof IncompatibleReportVersionError) { throw new ImportError('incompatible_version', err.foundVersion) } throw new ImportError('no_attachment') } }