diff --git a/apps/desktop/src/lib/mupdf/mupdf-worker.ts b/apps/desktop/src/lib/mupdf/mupdf-worker.ts index f912051..3334a12 100644 --- a/apps/desktop/src/lib/mupdf/mupdf-worker.ts +++ b/apps/desktop/src/lib/mupdf/mupdf-worker.ts @@ -1,13 +1,43 @@ -import * as mupdf from "mupdf"; +import type { PDFDocument } from "mupdf"; -const documentMap = new Map(); +type MupdfModule = typeof import("mupdf"); + +type MupdfWasmModuleConfig = { + locateFile?: (path: string) => string; +}; + +const wasmModuleConfig = (( + globalThis as typeof globalThis & { + $libmupdf_wasm_Module?: MupdfWasmModuleConfig; + } +).$libmupdf_wasm_Module ??= {}); + +// In Vite dev, requests for /node_modules/.../mupdf-wasm.wasm can fall back to +// index.html. Pointing MuPDF at Vite's @fs URL keeps worker startup on the +// actual binary during local development without changing packaged builds. +if (import.meta.env.DEV) { + const devWasmUrl = `/@fs/${__MUPDF_WASM_FS_PATH__}`; + wasmModuleConfig.locateFile = (path: string) => { + if (path.endsWith("mupdf-wasm.wasm")) { + return devWasmUrl; + } + return path; + }; +} + +const mupdf: MupdfModule = await import("mupdf"); + +const documentMap = new Map(); let nextDocId = 1; const methods: Record any> = {}; methods.openDocument = (buffer: ArrayBuffer, magic: string): number => { const docId = nextDocId++; - const doc = mupdf.Document.openDocument(buffer, magic) as mupdf.PDFDocument; + const doc = mupdf.Document.openDocument( + buffer, + magic, + ) as unknown as PDFDocument; documentMap.set(docId, doc); return docId; }; diff --git a/apps/desktop/src/vite-env.d.ts b/apps/desktop/src/vite-env.d.ts index 11f02fe..3e45f76 100644 --- a/apps/desktop/src/vite-env.d.ts +++ b/apps/desktop/src/vite-env.d.ts @@ -1 +1,3 @@ /// + +declare const __MUPDF_WASM_FS_PATH__: string; diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 57e85b3..740f71b 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -4,6 +4,15 @@ import topLevelAwait from "vite-plugin-top-level-await"; import path from "node:path"; const host = process.env.TAURI_DEV_HOST; +const mupdfWasmFile = path.resolve( + __dirname, + "..", + "..", + "node_modules", + "mupdf", + "dist", + "mupdf-wasm.wasm", +); export default defineConfig({ plugins: [react(), topLevelAwait()], @@ -12,6 +21,9 @@ export default defineConfig({ "@": path.resolve(__dirname, "src"), }, }, + define: { + __MUPDF_WASM_FS_PATH__: JSON.stringify(mupdfWasmFile.replace(/\\/g, "/")), + }, worker: { format: "es", },