feat(pdf): attach + extract report JSON via pdf-lib (with fallback traversal)
This commit is contained in:
1 parent
1c0b507458
commit
fb9a8fc3bd
2 files changed
+120
-19
No files matched your search
+80
-19
@@ -1,23 +1,84 @@
|
|||||||
import type { PDFDocument } from 'pdf-lib'
|
import { AFRelationship, type PDFDocument } from 'pdf-lib'
|
||||||
import type { Report } from '@/domain/schema/report'
|
import { ReportSchema, type Report } from '@/domain/schema/report'
|
||||||
|
|
||||||
/**
|
const FILENAME = 'osteo-report.json'
|
||||||
* Attaches the serialized Report JSON to the PDF document as a native
|
|
||||||
* embedded file with afRelationship 'Data'.
|
export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise<void> {
|
||||||
* Filename: 'osteo-report.json', mimeType: 'application/json'.
|
const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2))
|
||||||
*/
|
await pdfDoc.attach(bytes, FILENAME, {
|
||||||
export async function attachReportJson(
|
mimeType: 'application/json',
|
||||||
_pdfDoc: PDFDocument,
|
description: 'Osteo Report state v1',
|
||||||
_report: Report,
|
creationDate: new Date(),
|
||||||
): Promise<void> {
|
modificationDate: new Date(),
|
||||||
throw new Error('not implemented')
|
afRelationship: AFRelationship.Data,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export async function extractReportJson(pdfDoc: PDFDocument): Promise<Report> {
|
||||||
* Extracts and parses the first embedded file named 'osteo-report*'
|
const maybeApi = pdfDoc as unknown as { getAttachments?: () => Array<{ name: string; data: Uint8Array }> }
|
||||||
* with mime 'application/json' from the PDF document.
|
if (typeof maybeApi.getAttachments === 'function') {
|
||||||
* Throws ImportError if not found or invalid.
|
const list = maybeApi.getAttachments()
|
||||||
*/
|
if (list && list.length) {
|
||||||
export async function extractReportJson(_pdfDoc: PDFDocument): Promise<Report> {
|
const hit = list.find((a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json')) ?? list[0]
|
||||||
throw new Error('not implemented')
|
return parseAttachment(hit.data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const fallback = await traverseForJsonAttachment(pdfDoc)
|
||||||
|
if (!fallback) throw new Error('No osteo-report attachment found')
|
||||||
|
return parseAttachment(fallback)
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseAttachment(bytes: Uint8Array): Report {
|
||||||
|
const text = new TextDecoder().decode(bytes)
|
||||||
|
const data = JSON.parse(text)
|
||||||
|
return ReportSchema.parse(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RawObj {
|
||||||
|
contents?: Uint8Array
|
||||||
|
dict?: { entries?: () => Array<[unknown, unknown]> }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function inflateFlate(bytes: Uint8Array): Promise<Uint8Array | null> {
|
||||||
|
if (typeof DecompressionStream === 'undefined') return null
|
||||||
|
try {
|
||||||
|
const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate'))
|
||||||
|
return new Uint8Array(await new Response(stream).arrayBuffer())
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean {
|
||||||
|
for (const [k, v] of entries) {
|
||||||
|
if (String(k).includes('Filter') && String(v).includes('FlateDecode')) return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
async function traverseForJsonAttachment(pdfDoc: PDFDocument): Promise<Uint8Array | null> {
|
||||||
|
const ctx = (pdfDoc as unknown as { context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> } }).context
|
||||||
|
for (const [, obj] of ctx.enumerateIndirectObjects()) {
|
||||||
|
if (!obj || typeof obj !== 'object') continue
|
||||||
|
if (!(obj.contents instanceof Uint8Array)) continue
|
||||||
|
const entries = obj.dict?.entries?.() ?? []
|
||||||
|
let isEmbeddedFile = false
|
||||||
|
let isJsonSubtype = false
|
||||||
|
for (const [k, v] of entries) {
|
||||||
|
const ks = String(k)
|
||||||
|
const vs = String(v)
|
||||||
|
if (ks.includes('Type') && vs.includes('EmbeddedFile')) isEmbeddedFile = true
|
||||||
|
// PDF name syntax escapes '/' as '#2F': /application#2Fjson
|
||||||
|
if (ks.includes('Subtype') && (vs.includes('application/json') || vs.includes('application#2Fjson'))) {
|
||||||
|
isJsonSubtype = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isEmbeddedFile && !isJsonSubtype) continue
|
||||||
|
if (dictHasFlateFilter(entries)) {
|
||||||
|
const inflated = await inflateFlate(obj.contents)
|
||||||
|
if (inflated) return inflated
|
||||||
|
}
|
||||||
|
return obj.contents
|
||||||
|
}
|
||||||
|
return null
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { PDFDocument } from 'pdf-lib'
|
||||||
|
import { attachReportJson, extractReportJson } from '@/pdf/attachment'
|
||||||
|
import type { Report } from '@/domain/schema/report'
|
||||||
|
|
||||||
|
const report: Report = {
|
||||||
|
version: 1,
|
||||||
|
id: 'r1',
|
||||||
|
createdAt: '2026-05-18T10:00:00Z',
|
||||||
|
date: '2026-05-18',
|
||||||
|
practitioner: { name: 'Dr. Dupont' },
|
||||||
|
animal: { speciesId: 'equine', name: 'Mistral' },
|
||||||
|
owner: { name: 'Jean Martin' },
|
||||||
|
observations: [],
|
||||||
|
conclusion: 'tout va bien',
|
||||||
|
recommendations: 'continuer',
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('PDF attachment roundtrip', () => {
|
||||||
|
it('attaches and extracts the report JSON', async () => {
|
||||||
|
const doc = await PDFDocument.create()
|
||||||
|
doc.addPage()
|
||||||
|
await attachReportJson(doc, report)
|
||||||
|
const bytes = await doc.save()
|
||||||
|
|
||||||
|
const reopened = await PDFDocument.load(bytes)
|
||||||
|
const out = await extractReportJson(reopened)
|
||||||
|
expect(out.conclusion).toBe('tout va bien')
|
||||||
|
expect(out.animal.name).toBe('Mistral')
|
||||||
|
expect(out.version).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws on PDFs without the attachment', async () => {
|
||||||
|
const doc = await PDFDocument.create()
|
||||||
|
doc.addPage()
|
||||||
|
const bytes = await doc.save()
|
||||||
|
const reopened = await PDFDocument.load(bytes)
|
||||||
|
await expect(extractReportJson(reopened)).rejects.toThrow()
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in new issue
Block a user