/** * Step 6 Phase 0 characterisation of the import flow on the home route, through the * import worker (R4.3: the real worker logic in-process on the shipped module, the * files real fixtures or minimal PDFs from `helpers/pdfBytes`): the picked file reaches * the worker unread by the page, with the page's sheet and module, and the core's * result hydrates the store on the loaded sheet; the migration alert (degraded * headline, then the count), the core's refusal kinds plus a worker trap mapped to the * FR messages, and the navigation to /editor on success; `lone_surrogate` (L1) has its * own message. */ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, } from 'vitest' import { cleanup, fireEvent, render, screen, waitFor, } from '@testing-library/react' import { MemoryRouter, Route, Routes } from 'react-router-dom' import type { ArchiveImport } from '@faunosteo/core-wasm/types' import HomeRoute from '@/app/routes/HomeRoute' import { MAX_PDF_BYTES, type EngineLoader } from '@/core/worker/handler' import type { ImportTaskMessage } from '@/core/worker/protocol' import { useReportStore } from '@/state/reportStore' import { useLocaleStore } from '@/state/localeStore' import { fr } from '@/i18n/fr' import type { SheetIndex } from '@/services/sheetIndex' import { FIXTURES_DIR } from '../helpers/goldens' import { throwingEngineLoader, useInProcessImportWorker, type FakeWorker, } from '../helpers/importWorker' import { archivePdf, foreignPdf, pdfFile } from '../helpers/pdfBytes' import { bundledSheet, loadTestSheet, minimalReport } from '../helpers/sheet' let sheet: SheetIndex let workers: FakeWorker[] let restoreSpawn: () => void beforeAll(async () => { sheet = await loadTestSheet() }) beforeEach(() => { useLocaleStore.setState({ locale: 'fr' }) // A fresh tab: the previous import's draft would be a held text. sessionStorage.clear() useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0, }) vi.stubGlobal('alert', vi.fn()) ;({ workers, restore: restoreSpawn } = useInProcessImportWorker()) }) afterEach(() => { restoreSpawn() cleanup() vi.unstubAllGlobals() vi.restoreAllMocks() }) const fixture = (name: string) => new Uint8Array(readFileSync(resolve(FIXTURES_DIR, name))) /** The demo report exported bare by the Step 6 code: same sheet, no archive. */ const barePdf = () => pdfFile(fixture('report-v3.bare.pdf')) /** A Report v2 holding one zone and one finding the migration map does not know. */ function lossyV2Pdf(): File { const v2 = JSON.parse( readFileSync(resolve(FIXTURES_DIR, 'report-v2.minimal.json'), 'utf8'), ) const observation = { id: 'obs-lost', zones: [{ boneId: 'point-gone' }], findings: [ { zoneId: 'zone-gone', path: ['zone-gone-dysfunctions', 'gone'], labelFrSnapshot: 'Constat disparu', labelEnSnapshot: 'Gone finding', }, ], freeTextFindings: [], comment: '', } const report = { ...v2, observations: [observation] } return pdfFile(archivePdf(JSON.stringify(report))) } /** The core's import outcome the worker answered (the result message, parsed). */ function resultOf(worker: FakeWorker): ArchiveImport { const result = worker.posted.find((m) => m.type === 'result') if (result?.type !== 'result') throw new Error('the worker gave no result') const envelope = JSON.parse(result.out) as { ok: boolean value: ArchiveImport } if (!envelope.ok) throw new Error(`the core refused: ${result.out}`) return envelope.value } async function mountAndPickPdf(file: File = barePdf()): Promise { render( } /> } /> , ) const button = screen.getByRole('button', { name: fr['home.import.cta'] }) await waitFor(() => expect(button).toBeEnabled()) const input = document.querySelector('input[type="file"]')! fireEvent.change(input, { target: { files: [file] } }) } const alertMock = () => vi.mocked(window.alert) const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' }) describe('HomeRoute import: success paths', () => { it('passes the file bytes to the scan and the attachment to the loaded sheet, hydrates, navigates to /editor', async () => { // Since R4.3 the scan runs in the worker: the page hands it the file unread. const file = barePdf() const read = vi.spyOn(file, 'arrayBuffer') const text = vi.spyOn(file, 'text') const real = useReportStore.getState().hydrateImport const hydrate = vi.fn(real) useReportStore.setState({ hydrateImport: hydrate }) try { await mountAndPickPdf(file) await screen.findByTestId('editor-route') } finally { useReportStore.setState({ hydrateImport: real }) } expect(workers).toHaveLength(1) const task = workers[0]!.received[0] as ImportTaskMessage expect(task).toMatchObject({ type: 'task', task: 'pdf', size: file.size }) expect(task.sheet).toBe(JSON.stringify(await bundledSheet())) expect(task.module).toBeInstanceOf(WebAssembly.Module) // The page streams the file chunk by chunk, never whole: no arrayBuffer, no text. expect(read).not.toHaveBeenCalled() expect(text).not.toHaveBeenCalled() const chunks = workers[0]!.received.filter( (m) => (m as { type: string }).type === 'chunk', ) expect(chunks.length).toBeGreaterThanOrEqual(1) expect(workers[0]!.received.at(-1)).toMatchObject({ type: 'end' }) const imported = resultOf(workers[0]!) expect(hydrate).toHaveBeenCalledTimes(1) const [session, index] = hydrate.mock.calls[0]! expect(session).toEqual({ report: imported.rebase.report, archive: null }) expect(index).toBe(sheet) expect(useReportStore.getState().report?.id).toBe('fixture-demo-v3') expect(alertMock()).not.toHaveBeenCalled() }) it('alerts "degraded" then the unresolved count (zones + findings) after a lossy migration', async () => { await mountAndPickPdf(lossyV2Pdf()) await screen.findByTestId('editor-route') expect(resultOf(workers[0]!).read).toMatchObject({ migrated: true, unresolvedZones: 1, unresolvedFindings: 1, }) expect(alertMock()).toHaveBeenCalledTimes(1) const message = alertMock().mock.calls[0]![0] as string const [headline, ...lines] = message.split('\n\n') expect(headline).toBe(fr['home.import.degraded']) expect(lines).toEqual([fr['home.import.migrated']!.replace('{count}', '2')]) }) it('stays silent on a migration that lost nothing', async () => { // The Step 5 v2 export: every zone and finding has its place on the draft. await mountAndPickPdf(pdfFile(fixture('report-v2.full.pdf'))) await screen.findByTestId('editor-route') expect(resultOf(workers[0]!).read).toMatchObject({ migrated: true, unresolvedZones: 0, unresolvedFindings: 0, }) expect(alertMock()).not.toHaveBeenCalled() }) }) describe('HomeRoute import: error paths', () => { const cases: Array<[string, () => File, string, EngineLoader?]> = [ [ 'incompatible_version → message with the found version', () => pdfFile( archivePdf(JSON.stringify({ ...minimalReport(sheet), version: 7 })), ), fr['home.import.error_incompatible_version']!.replace('{version}', '7'), ], [ 'invalid_pdf → unreadable PDF message', () => pdfFile(new TextEncoder().encode('not a PDF at all')), fr['home.import.error_invalid_pdf']!, ], [ 'no_attachment → not a Faunosteo PDF message', () => pdfFile(foreignPdf()), fr['home.import.error_no_attachment']!, ], [ 'lone_surrogate → malformed text message, file untouched', () => pdfFile( archivePdf( JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' })), ), ), fr['home.import.error_lone_surrogate']!, ], [ 'generic Error → generic message', // A trap of the worker's engine: never shown as a corrupt PDF (OD-5). barePdf, fr['home.import.error_generic']!, throwingEngineLoader(new WebAssembly.RuntimeError('unreachable')), ], ] it.each(cases)('%s', async (_label, file, expected, load) => { // Another engine replaces the seam; afterEach restores the default. if (load) { ;({ workers, restore: restoreSpawn } = useInProcessImportWorker(load)) } await mountAndPickPdf(file()) await waitFor(() => expect(errorText()).not.toBeNull()) expect(errorText()!.textContent).toBe(expected) expect(workers).toHaveLength(1) expect(screen.queryByTestId('editor-route')).toBeNull() expect(useReportStore.getState().report).toBeNull() expect(alertMock()).not.toHaveBeenCalled() }) }) describe('HomeRoute import: size gate', () => { it('refuses a file over MAX_PDF_BYTES before reading it: unreadable PDF message', async () => { const file = barePdf() Object.defineProperty(file, 'size', { value: MAX_PDF_BYTES + 1 }) const read = vi.spyOn(file, 'arrayBuffer') const stream = vi.spyOn(file, 'stream') await mountAndPickPdf(file) await waitFor(() => expect(errorText()).not.toBeNull()) expect(errorText()!.textContent).toBe(fr['home.import.error_invalid_pdf']) expect(read).not.toHaveBeenCalled() expect(stream).not.toHaveBeenCalled() expect(workers).toHaveLength(0) expect(screen.queryByTestId('editor-route')).toBeNull() expect(useReportStore.getState().report).toBeNull() }) }) describe('HomeRoute import: a core failure reading the tab draft', () => { it('shows the engine error line, not the held-session alert', async () => { const real = useReportStore.getState().hydrateImport useReportStore.setState({ hydrateImport: () => ({ ok: false }) }) try { await mountAndPickPdf() await screen.findByText(fr['home.import.error_core_unavailable']!) // The worker read the file: the failure is the store's, after the result. expect(workers[0]!.sequence()).toEqual(['ready', 'result']) expect(alertMock()).not.toHaveBeenCalled() expect(screen.queryByTestId('editor-route')).toBeNull() } finally { useReportStore.setState({ hydrateImport: real }) } }) it('still alerts and opens the editor for a held session text', async () => { const real = useReportStore.getState().hydrateImport useReportStore.setState({ hydrateImport: () => ({ ok: false, reason: 'held' }), }) try { await mountAndPickPdf() await screen.findByTestId('editor-route') expect(workers[0]!.sequence()).toEqual(['ready', 'result']) expect(alertMock()).toHaveBeenCalledWith(fr['session.held_blocked']) } finally { useReportStore.setState({ hydrateImport: real }) } }) })