From 1c4eaf3e6da522e6e775e15216d09c2afdcfe54b Mon Sep 17 00:00:00 2001 From: Weilin Cai <1261249659@qq.com> Date: Tue, 7 Apr 2026 16:03:06 +0800 Subject: [PATCH] fix: resolve MuPDF wasm correctly in desktop dev --- apps/desktop/src/lib/mupdf/mupdf-worker.ts | 34 ++++++++++++++++++++-- apps/desktop/src/vite-env.d.ts | 2 ++ apps/desktop/vite.config.ts | 14 +++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/lib/mupdf/mupdf-worker.ts b/apps/desktop/src/lib/mupdf/mupdf-worker.ts index f912051..6e178e7 100644 --- a/apps/desktop/src/lib/mupdf/mupdf-worker.ts +++ b/apps/desktop/src/lib/mupdf/mupdf-worker.ts @@ -1,13 +1,41 @@ -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..62d7b54 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,11 @@ export default defineConfig({ "@": path.resolve(__dirname, "src"), }, }, + define: { + __MUPDF_WASM_FS_PATH__: JSON.stringify( + mupdfWasmFile.replace(/\\/g, "/"), + ), + }, worker: { format: "es", },