LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
release: v0.4.22
nash_suac455694446a
diff --git a/package.json b/package.jsonindex d66a81e0..9e7fca96 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "llm-wiki","private": true,- "version": "0.4.21",+ "version": "0.4.22","type": "module","scripts": {"dev": "vite",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 5ff388a7..fe420387 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4461,7 +4461,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"[[package]]name = "llm-wiki"-version = "0.4.21"+version = "0.4.22"dependencies = ["arrow-array","arrow-schema",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex af055f76..ed6e367f 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "llm-wiki"-version = "0.4.21"+version = "0.4.22"description = "LLM Wiki - A personal knowledge base for LLM concepts"authors = []edition = "2021"diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex ac20bc2d..aa797248 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -989,6 +989,32 @@ pub async fn write_file(path: String, contents: String) -> Result<(), String> {.map_err(|e| format!("write_file blocking task join error: {e}"))?}+#[tauri::command]+pub async fn write_file_base64(path: String, base64: String) -> Result<(), String> {+ use base64::{engine::general_purpose::STANDARD as B64, Engine as _};++ tauri::async_runtime::spawn_blocking(move || {+ run_guarded("write_file_base64", || {+ require_absolute_path("write_file_base64", &path)?;+ let bytes = B64+ .decode(base64.as_bytes())+ .map_err(|e| format!("Invalid base64 for '{}': {}", path, e))?;+ let p = Path::new(&path);+ if let Some(parent) = p.parent() {+ fs::create_dir_all(parent)+ .map_err(|e| format!("Failed to create parent dirs for '{}': {}", path, e))?;+ }+ file_sync::mark_app_write_path(p);+ fs::write(&path, bytes)+ .map_err(|e| format!("Failed to write binary file '{}': {}", path, e))?;+ file_sync::mark_app_write_path(p);+ Ok(())+ })+ })+ .await+ .map_err(|e| format!("write_file_base64 blocking task join error: {e}"))?+}+#[tauri::command]pub async fn write_file_atomic(path: String, contents: String) -> Result<(), String> {tauri::async_runtime::spawn_blocking(move || {@@ -1616,6 +1642,45 @@ mod tests {assert!(result.unwrap_err().contains("Failed to parse DOC"));}+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn write_file_base64_writes_decoded_binary_bytes() {+ let dir = std::env::temp_dir();+ let path = dir.join(format!(+ "llm-wiki-base64-{}.bin",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let path_str = path.to_string_lossy().to_string();++ write_file_base64(path_str.clone(), "AAECA/8=".to_string())+ .await+ .unwrap();++ let bytes = fs::read(&path).unwrap();+ let _ = fs::remove_file(&path);+ assert_eq!(bytes, vec![0, 1, 2, 3, 255]);+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn write_file_base64_rejects_invalid_base64_and_relative_paths() {+ let invalid = write_file_base64(+ std::env::temp_dir()+ .join("llm-wiki-invalid-base64.bin")+ .to_string_lossy()+ .to_string(),+ "not!!base64".to_string(),+ )+ .await;+ assert!(invalid.is_err());+ assert!(invalid.unwrap_err().contains("Invalid base64"));++ let relative = write_file_base64("relative.bin".to_string(), "AA==".to_string()).await;+ assert!(relative.is_err());+ assert!(relative.unwrap_err().contains("requires an absolute path"));+ }+/// Ad-hoc probe: run the production PDF extraction path against every/// .pdf under a user-provided directory and print a per-file report of/// Ok / Err (library returned an error) / Panic (library panicked anddiff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 78e38800..afaf4505 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -195,6 +195,7 @@ pub fn run() {.invoke_handler(tauri::generate_handler![commands::fs::read_file,commands::fs::write_file,+ commands::fs::write_file_base64,commands::fs::write_file_atomic,commands::fs::list_directory,commands::fs::copy_file,diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 3baeb978..0bf7240d 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "LLM Wiki",- "version": "0.4.21",+ "version": "0.4.22","identifier": "com.llmwiki.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/commands/fs.ts b/src/commands/fs.tsindex f42338fb..982709a6 100644--- a/src/commands/fs.ts+++ b/src/commands/fs.ts@@ -24,6 +24,11 @@ export async function writeFile(path: string, contents: string): Promise<void> {return invoke<void>("write_file", { path, contents })}+export async function writeFileBase64(path: string, base64: string): Promise<void> {+ assertAbsoluteFsPath("writeFileBase64", path)+ return invoke<void>("write_file_base64", { path, base64 })+}+export async function writeFileAtomic(path: string, contents: string): Promise<void> {assertAbsoluteFsPath("writeFileAtomic", path)return invoke<void>("write_file_atomic", { path, contents })diff --git a/src/lib/changelog.ts b/src/lib/changelog.tsindex b27d8093..c1a30b30 100644--- a/src/lib/changelog.ts+++ b/src/lib/changelog.ts@@ -25,6 +25,22 @@ export interface ChangelogEntry {}export const CHANGELOG: ChangelogEntry[] = [+ {+ version: "0.4.22",+ date: "2026-06-08",+ highlights: {+ en: [+ "Improved MinerU PDF previews by extracting images from MinerU result archives and rewriting them into Markdown image links.",+ "Converted MinerU HTML tables inside Markdown output into Markdown tables for cleaner preview and ingest.",+ "Hardened MinerU image handling for spaces, parentheses, path traversal, duplicate names, and partial image-save failures.",+ ],+ zh: [+ "改进 MinerU PDF 预览:从 MinerU 结果压缩包提取图片,并重写为 Markdown 图片引用。",+ "将 MinerU Markdown 输出中的 HTML 表格转换为 Markdown 表格,让预览和摄取更干净。",+ "强化 MinerU 图片处理,覆盖空格、括号、路径穿越、重名图片和图片保存部分失败等边界。",+ ],+ },+ },{version: "0.4.21",date: "2026-06-07",diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.tsindex b293d9ab..0c8529dd 100644--- a/src/lib/ingest-source-path-collision.test.ts+++ b/src/lib/ingest-source-path-collision.test.ts@@ -112,7 +112,7 @@ vi.mock("./mineru", () => ({parseWithMineru: vi.fn(),}))-import { autoIngest, executeIngestWrites } from "./ingest"+import { autoIngest, executeIngestWrites, hasMineruImageRefs } from "./ingest"import { streamChat } from "./llm-client"import { parseWithMineru } from "./mineru"@@ -185,6 +185,21 @@ describe("autoIngest source summary paths", () => {tmp = undefined})+ it("detects MinerU image refs with URL-encoded source summary slugs", () => {+ expect(hasMineruImageRefs(+ "",+ "污水 paper",+ )).toBe(true)+ expect(hasMineruImageRefs(+ "",+ "污水 paper",+ )).toBe(true)+ expect(hasMineruImageRefs(+ "",+ "污水 paper",+ )).toBe(false)+ })+it("keeps distinct source summaries for same-basename files in different source subdirectories", async () => {if (!tmp) throw new Error("missing temp project")sourceMarkers = ["project-a config", "project-b config"]diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 8393ce84..0b277c7c 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -139,6 +139,19 @@ function stripWikiMediaAbsPaths(projectPath: string, content: string): string {return content.split(`${projectPath}/wiki/media/`).join("media/")}+function encodeMarkdownPathSegment(segment: string): string {+ return encodeURIComponent(segment).replace(/[!'()*]/g, (char) =>+ `%${char.charCodeAt(0).toString(16).toUpperCase()}`,+ )+}++export function hasMineruImageRefs(content: string, sourceSummarySlug: string): boolean {+ return (+ content.includes(`media/${sourceSummarySlug}/mineru/`) ||+ content.includes(`media/${encodeMarkdownPathSegment(sourceSummarySlug)}/mineru/`)+ )+}+interface SourceChunk {id: stringindex: number@@ -482,8 +495,8 @@ async function autoIngestImpl(const lowerExt = fileName.includes(".") ? fileName.split(".").pop()?.toLowerCase() : ""const isPdf = lowerExt === "pdf"const mineruCfg = useWikiStore.getState().mineruConfig+ let mineruSucceeded = falseif (isPdf && mineruCfg.enabled && mineruCfg.token) {- let mineruSucceeded = falsetry {const cacheDir = sp.substring(0, sp.lastIndexOf("/"))const cachePath = `${cacheDir}/.cache/${fileName}.txt`@@ -491,7 +504,10 @@ async function autoIngestImpl(console.log(`[ingest:mineru] submitting "${fileName}" to MinerU API`)const markdown = await parseWithMineru(mineruCfg, sp, undefined, (msg) => {activity.updateItem(activityId, { detail: `MinerU: ${msg}` })- }, signal)+ }, signal, {+ projectPath: pp,+ sourceSummarySlug,+ })await createDirectory(`${cacheDir}/.cache`)await writeFile(cachePath, markdown)mineruSucceeded = true@@ -532,7 +548,10 @@ async function autoIngestImpl(if (cachedFiles !== null) {try {console.log(`[ingest:diag] cache-hit branch: starting image extraction for ${sp}`)- let savedImages = await extractAndSaveSourceImages(pp, sp, sourceSummarySlug)+ const skipNativePdfImageExtraction = isPdf && hasMineruImageRefs(sourceContent, sourceSummarySlug)+ let savedImages = skipNativePdfImageExtraction+ ? []+ : await extractAndSaveSourceImages(pp, sp, sourceSummarySlug)const markdownImages = await extractAndSaveMarkdownImages(pp, sp, sourceContent, sourceSummarySlug)savedImages = [...savedImages, ...markdownImages]console.log(`[ingest:diag] cache-hit branch: got ${savedImages.length} image(s)`)@@ -625,7 +644,12 @@ async function autoIngestImpl(// and returns [] on any error.activity.updateItem(activityId, { detail: "Extracting embedded images..." })console.log(`[ingest:diag] full-pipeline branch: starting image extraction for ${sp}`)- let savedImages = await extractAndSaveSourceImages(pp, sp, sourceSummarySlug)+ const skipNativePdfImageExtraction = isPdf && (+ hasMineruImageRefs(sourceContent, sourceSummarySlug)+ )+ let savedImages = skipNativePdfImageExtraction+ ? []+ : await extractAndSaveSourceImages(pp, sp, sourceSummarySlug)const markdownImages = await extractAndSaveMarkdownImages(pp, sp, sourceContent, sourceSummarySlug)savedImages = [...savedImages, ...markdownImages]console.log(`[ingest:diag] full-pipeline branch: got ${savedImages.length} image(s)`)diff --git a/src/lib/mineru.test.ts b/src/lib/mineru.test.tsindex e3f4a73f..e2f825e1 100644--- a/src/lib/mineru.test.ts+++ b/src/lib/mineru.test.ts@@ -8,13 +8,17 @@ vi.mock("@/lib/tauri-fetch", () => ({}))const fsMocks = vi.hoisted(() => ({+ createDirectory: vi.fn<() => Promise<void>>(),getFileSize: vi.fn<() => Promise<number>>(),readFileAsBase64: vi.fn<() => Promise<{ base64: string; mimeType: string }>>(),+ writeFileBase64: vi.fn<() => Promise<void>>(),}))vi.mock("@/commands/fs", () => ({+ createDirectory: fsMocks.createDirectory,getFileSize: fsMocks.getFileSize,readFileAsBase64: fsMocks.readFileAsBase64,+ writeFileBase64: fsMocks.writeFileBase64,}))import { __mineruTest, parseWithMineru, testMineruConnection } from "./mineru"@@ -42,13 +46,17 @@ async function zipResponse(files: Record<string, string>): Promise<Response> {beforeEach(() => {mockHttpFetch.mockReset()+ fsMocks.createDirectory.mockReset()fsMocks.getFileSize.mockReset()fsMocks.readFileAsBase64.mockReset()+ fsMocks.writeFileBase64.mockReset()+ fsMocks.createDirectory.mockResolvedValue(undefined)fsMocks.getFileSize.mockResolvedValue(1024)fsMocks.readFileAsBase64.mockResolvedValue({base64: btoa("pdf bytes"),mimeType: "application/pdf",})+ fsMocks.writeFileBase64.mockResolvedValue(undefined)})describe("MinerU API helpers", () => {@@ -88,6 +96,231 @@ describe("MinerU API helpers", () => {await expect(__mineruTest.downloadAndExtractMarkdown("https://cdn/result.zip")).rejects.toThrow("No Markdown file")})++ it("converts MinerU HTML tables inside full.md to Markdown tables", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": [+ "# Parsed",+ "<table>",+ "<tr><th>Name</th><th>Value</th></tr>",+ "<tr><td>A&B</td><td>1|2</td></tr>",+ "</table>",+ ].join("\n"),+ }))++ await expect(__mineruTest.downloadAndExtractMarkdown("https://cdn/result.zip"))+ .resolves.toContain("| Name | Value |\n| --- | --- |\n| A&B | 1\\|2 |")+ })++ it("keeps malformed numeric HTML entities from crashing table conversion", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": [+ "<table>",+ "<tr><td>A</td><td>�</td><td>A</td><td>�</td></tr>",+ "</table>",+ ].join("\n"),+ }))++ await expect(__mineruTest.downloadAndExtractMarkdown("https://cdn/result.zip"))+ .resolves.toContain("| A | � | A | � |")+ })++ it("does not convert HTML tables inside fenced code blocks", async () => {+ const code = [+ "```html",+ "<table><tr><td>Keep raw</td></tr></table>",+ "```",+ ].join("\n")+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": `${code}\n\n<table><tr><td>Convert me</td></tr></table>`,+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown("https://cdn/result.zip")++ expect(markdown).toContain(code)+ expect(markdown).toContain("| Convert me |")+ })++ it("preserves and rewrites images inside MinerU HTML table cells", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": [+ "<table>",+ "<tr><th>Figure</th><th>Note</th></tr>",+ "<tr><td><img src=\"images/chart.png\" alt=\"Chart\"></td><td>A</td></tr>",+ "</table>",+ ].join("\n"),+ "images/chart.png": "chart-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(markdown).toContain("|  | A |")+ })++ it("extracts MinerU zip images and rewrites Markdown image references", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": [+ "# Parsed",+ "",+ "<img src=\"figures/table 1.jpg\" alt=\"Table\">",+ "",+ ].join("\n"),+ "images/chart.png": "chart-bytes",+ "figures/table 1.jpg": "table-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(fsMocks.createDirectory).toHaveBeenCalledWith("/project/wiki/media/paper/mineru")+ expect(fsMocks.writeFileBase64).toHaveBeenCalledWith(+ "/project/wiki/media/paper/mineru/images/chart.png",+ btoa("chart-bytes"),+ )+ expect(fsMocks.writeFileBase64).toHaveBeenCalledWith(+ "/project/wiki/media/paper/mineru/figures/table 1.jpg",+ btoa("table-bytes"),+ )+ expect(markdown).toContain("")+ expect(markdown).toContain("")+ expect(markdown).toContain("")+ })++ it("rewrites Markdown image paths containing spaces", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": "",+ "images/wide chart.png": "chart-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(markdown).toBe("")+ })++ it("rewrites image filenames containing parentheses into balanced encoded links", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": ".png)",+ "images/chart(1).png": "chart-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(markdown).toBe("")+ })++ it("writes large extracted images with exact base64 content", async () => {+ const bytes = "x".repeat(40_000)+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": "",+ "images/large.png": bytes,+ }))++ await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(fsMocks.writeFileBase64).toHaveBeenCalledWith(+ "/project/wiki/media/paper/mineru/images/large.png",+ btoa(bytes),+ )+ })++ it("rewrites image links by basename when MinerU Markdown omits image directories", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "result/full.md": "",+ "result/images/chart.png": "chart-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(markdown).toBe("")+ })++ it("keeps extracted zip paths inside the MinerU media directory", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": "",+ "../../evil.png": "evil-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(fsMocks.writeFileBase64).toHaveBeenCalledWith(+ "/project/wiki/media/paper/mineru/evil.png",+ btoa("evil-bytes"),+ )+ expect(markdown).toBe("")+ })++ it("does not use basename fallback when zip image basenames collide", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": "\n",+ "a/chart.png": "a-bytes",+ "b/chart.png": "b-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(markdown).toContain("")+ expect(markdown).toContain("")+ })++ it("keeps parsed Markdown when extracted image saving fails", async () => {+ fsMocks.writeFileBase64.mockRejectedValueOnce(new Error("disk full"))+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": "\nBody",+ "images/chart.png": "chart-bytes",+ }))++ await expect(__mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )).resolves.toBe("\nBody")+ })++ it("leaves external HTML image tags untouched", async () => {+ mockHttpFetch.mockResolvedValueOnce(await zipResponse({+ "full.md": "<img src=\"https://example.test/x.png\" alt=\"Remote\">",+ "images/local.png": "local-bytes",+ }))++ const markdown = await __mineruTest.downloadAndExtractMarkdown(+ "https://cdn/result.zip",+ undefined,+ { projectPath: "/project", sourceSummarySlug: "paper" },+ )++ expect(markdown).toBe("<img src=\"https://example.test/x.png\" alt=\"Remote\">")+ })})describe("parseWithMineru", () => {@@ -175,6 +408,42 @@ describe("parseWithMineru", () => {expect(new TextDecoder().decode(uploadBody as ArrayBuffer)).toBe("custom pdf bytes")})+ it("passes asset options through local MinerU parsing so images can be saved", async () => {+ mockHttpFetch+ .mockResolvedValueOnce(jsonResponse({+ code: 0,+ msg: "ok",+ data: { batch_id: "batch-1", file_urls: ["https://upload"] },+ }))+ .mockResolvedValueOnce(new Response("", { status: 200 }))+ .mockResolvedValueOnce(jsonResponse({+ code: 0,+ msg: "ok",+ data: {+ batch_id: "batch-1",+ extract_result: [{ file_name: "doc.pdf", state: "done", full_zip_url: "https://zip" }],+ },+ }))+ .mockResolvedValueOnce(await zipResponse({+ "full.md": "",+ "images/chart.png": "chart-bytes",+ }))++ await expect(parseWithMineru({+ enabled: true,+ token: "token",+ modelVersion: "vlm",+ }, "/tmp/doc.pdf", undefined, undefined, undefined, {+ projectPath: "/project",+ sourceSummarySlug: "doc",+ })).resolves.toBe("")++ expect(fsMocks.writeFileBase64).toHaveBeenCalledWith(+ "/project/wiki/media/doc/mineru/images/chart.png",+ btoa("chart-bytes"),+ )+ })+it("submits URL tasks without reading or uploading a local file", async () => {mockHttpFetch.mockResolvedValueOnce(jsonResponse({diff --git a/src/lib/mineru.ts b/src/lib/mineru.tsindex f72f9002..758720cf 100644--- a/src/lib/mineru.ts+++ b/src/lib/mineru.ts@@ -1,12 +1,24 @@import JSZip from "jszip"import type { MineruConfig } from "@/stores/wiki-store"-import { getFileSize, readFileAsBase64 } from "@/commands/fs"+import { createDirectory, getFileSize, readFileAsBase64, writeFileBase64 } from "@/commands/fs"import { getHttpFetch } from "@/lib/tauri-fetch"+import { getFileName, normalizePath } from "@/lib/path-utils"const API_BASE = "https://mineru.net/api/v4"const POLL_INTERVAL_MS = 3_000const POLL_TIMEOUT_MS = 300_000 // 5 minutesconst MAX_ACCURATE_PARSE_BYTES = 200 * 1024 * 1024+const MINERU_IMAGE_EXTS = new Set([+ "png",+ "jpg",+ "jpeg",+ "gif",+ "webp",+ "bmp",+ "svg",+ "tif",+ "tiff",+])// ── Types ──@@ -53,6 +65,11 @@ interface UploadUrlResponse {msg: string}+interface MineruAssetOptions {+ projectPath: string+ sourceSummarySlug: string+}+// ── API calls ──async function mineruHeaders(token: string): Promise<HeadersInit> {@@ -110,6 +127,215 @@ function bytesToUploadBody(bytes: Uint8Array): ArrayBuffer {) as ArrayBuffer}+function bytesToBase64(bytes: Uint8Array): string {+ let binary = ""+ const chunkSize = 0x8000+ for (let i = 0; i < bytes.length; i += chunkSize) {+ const chunk = bytes.subarray(i, i + chunkSize)+ binary += String.fromCharCode(...chunk)+ }+ return btoa(binary)+}++function safeMineruAssetSegment(segment: string): string {+ const decoded = (() => {+ try {+ return decodeURIComponent(segment)+ } catch {+ return segment+ }+ })()+ const cleaned = decoded+ .replace(/[<>:"|?*\x00-\x1f]/g, "_")+ .replace(/[\\/]+/g, "_")+ .replace(/^\.+$/, "_")+ .replace(/[. ]+$/g, "_")+ if (!cleaned) return "asset"+ if (cleaned.length <= 80) return cleaned++ const dot = cleaned.lastIndexOf(".")+ if (dot > 0 && dot < cleaned.length - 1) {+ const ext = cleaned.slice(dot).slice(0, 16)+ return `${cleaned.slice(0, Math.max(1, 80 - ext.length))}${ext}`+ }+ return cleaned.slice(0, 80)+}++function normalizeMineruZipPath(path: string): string {+ return normalizePath(path)+ .replace(/^\.\/+/, "")+ .split("/")+ .filter((part) => part && part !== "." && part !== "..")+ .join("/")+}++function decodeMineruPath(path: string): string {+ try {+ return decodeURIComponent(path)+ } catch {+ return path+ }+}++function isMineruImagePath(path: string): boolean {+ const ext = getFileName(path).split(".").pop()?.toLowerCase() ?? ""+ return MINERU_IMAGE_EXTS.has(ext)+}++function mineruAssetRelPath(sourceSummarySlug: string, zipPath: string): string {+ const safeParts = normalizeMineruZipPath(zipPath)+ .split("/")+ .map(safeMineruAssetSegment)+ .filter(Boolean)+ const safePath = safeParts.length > 0 ? safeParts.join("/") : "image.png"+ return `media/${sourceSummarySlug}/mineru/${safePath}`+}++function isExternalOrDataUrl(url: string): boolean {+ return /^(https?:|data:|blob:|file:|tauri:|asset:)/i.test(url)+}++function decodeHtmlEntities(text: string): string {+ const safeCodePoint = (raw: string, radix: 10 | 16): string => {+ const n = Number.parseInt(raw, radix)+ if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return radix === 16 ? `&#x${raw};` : `&#${raw};`+ try {+ return String.fromCodePoint(n)+ } catch {+ return radix === 16 ? `&#x${raw};` : `&#${raw};`+ }+ }++ return text+ .replace(/ /gi, " ")+ .replace(/&/gi, "&")+ .replace(/</gi, "<")+ .replace(/>/gi, ">")+ .replace(/"/gi, '"')+ .replace(/'/g, "'")+ .replace(/&#(\d+);/g, (_m, code: string) => safeCodePoint(code, 10))+ .replace(/&#x([0-9a-f]+);/gi, (_m, code: string) => safeCodePoint(code, 16))+}++function htmlImgTagsToMarkdown(html: string): string {+ return html.replace(/<img\b[^>]*\bsrc=(["'])([^"']+)\1[^>]*>/gi, (full, _quote: string, src: string) => {+ const alt = full.match(/\balt=(["'])([^"']*)\1/i)?.[2] ?? ""+ return ``+ })+}++function htmlCellToMarkdown(cell: string): string {+ return decodeHtmlEntities(+ htmlImgTagsToMarkdown(cell)+ .replace(/<br\s*\/?>/gi, "<br>")+ .replace(/<\/p\s*>/gi, "<br>")+ .replace(/<[^>]+>/g, "")+ .replace(/\s*<br>\s*/gi, "<br>")+ .replace(/\s+/g, " ")+ .trim(),+ ).replace(/\|/g, "\\|")+}++function convertHtmlTablesInSegment(segment: string): string {+ return segment.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml) => {+ const rows: string[][] = []+ for (const rowMatch of tableHtml.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)) {+ const rowHtml = rowMatch[1] ?? ""+ const cells: string[] = []+ for (const cellMatch of rowHtml.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/gi)) {+ cells.push(htmlCellToMarkdown(cellMatch[1] ?? ""))+ }+ if (cells.length > 0) rows.push(cells)+ }+ if (rows.length === 0) return tableHtml++ const width = Math.max(...rows.map((row) => row.length))+ const padded = rows.map((row) => {+ const out = [...row]+ while (out.length < width) out.push("")+ return out+ })+ const header = padded[0]+ const separator = Array.from({ length: width }, () => "---")+ const body = padded.slice(1)+ return [+ "",+ `| ${header.join(" | ")} |`,+ `| ${separator.join(" | ")} |`,+ ...body.map((row) => `| ${row.join(" | ")} |`),+ "",+ ].join("\n")+ })+}++function convertHtmlTablesToMarkdown(markdown: string): string {+ return markdown+ .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g)+ .map((segment) => (+ segment.startsWith("```") || segment.startsWith("~~~")+ ? segment+ : convertHtmlTablesInSegment(segment)+ ))+ .join("")+}++function encodeMarkdownImageUrl(relPath: string): string {+ return relPath+ .split("/")+ .map((part) =>+ encodeURIComponent(part).replace(/[!'()*]/g, (char) =>+ `%${char.charCodeAt(0).toString(16).toUpperCase()}`,+ ),+ )+ .join("/")+}++function rewriteMineruMarkdownImages(markdown: string, pathMap: Map<string, string>): string {+ const lookup = (rawUrl: string): string | null => {+ if (!rawUrl || isExternalOrDataUrl(rawUrl)) return null+ const cleaned = normalizeMineruZipPath(rawUrl.split("#")[0])+ if (!cleaned) return null+ const decoded = decodeMineruPath(cleaned)+ return pathMap.get(cleaned) ?? pathMap.get(decoded) ?? pathMap.get(getFileName(decoded)) ?? null+ }++ const withMarkdownImages = markdown.replace(+ /!\[([^\]]*)]\(((?:[^()]|\([^()]*\))*)\)/g,+ (full, alt: string, target: string) => {+ const trimmed = target.trim()+ const candidates: Array<{ url: string; suffix: string }> = []+ if (trimmed.startsWith("<") && trimmed.includes(">")) {+ const end = trimmed.indexOf(">")+ candidates.push({ url: trimmed.slice(1, end), suffix: trimmed.slice(end + 1) })+ } else {+ const titleMatch = trimmed.match(/^([\s\S]+?)(\s+["'][^"']*["']\s*)$/)+ if (titleMatch) candidates.push({ url: titleMatch[1].trim(), suffix: titleMatch[2] })+ candidates.push({ url: trimmed, suffix: "" })+ const tokenMatch = trimmed.match(/^(\S+)([\s\S]*)$/)+ if (tokenMatch) candidates.push({ url: tokenMatch[1], suffix: tokenMatch[2] })+ }++ for (const candidate of candidates) {+ const rel = lookup(candidate.url)+ if (!rel) continue+ const rewrittenTarget = `${encodeMarkdownImageUrl(rel)}${candidate.suffix}`+ return ``+ }+ return full+ },+ )++ return withMarkdownImages.replace(+ /<img\b[^>]*\bsrc=(["'])([^"']+)\1[^>]*>/gi,+ (full, _quote: string, src: string) => {+ const rel = lookup(src)+ if (!rel) return full+ const alt = full.match(/\balt=(["'])([^"']*)\1/i)?.[2] ?? ""+ return `})`+ },+ )+}+async function submitUrlTask(token: string,url: string,@@ -254,7 +480,52 @@ async function pollBatchTask(throw new Error("MinerU parsing timed out after 5 minutes")}-async function downloadAndExtractMarkdown(zipUrl: string, signal?: AbortSignal): Promise<string> {+async function saveMineruZipImages(+ zip: JSZip,+ options: MineruAssetOptions,+ signal?: AbortSignal,+): Promise<Map<string, string>> {+ const pp = normalizePath(options.projectPath)+ const rootDir = `${pp}/wiki/media/${options.sourceSummarySlug}/mineru`+ const pathMap = new Map<string, string>()+ const imageEntries: Array<[string, JSZip.JSZipObject]> = []+ const basenameCounts = new Map<string, number>()++ zip.forEach((relativePath, file) => {+ const normalized = normalizeMineruZipPath(relativePath)+ if (!file.dir && normalized && isMineruImagePath(normalized)) {+ imageEntries.push([normalized, file])+ const basename = getFileName(normalized)+ basenameCounts.set(basename, (basenameCounts.get(basename) ?? 0) + 1)+ }+ })++ if (imageEntries.length === 0) return pathMap++ await createDirectory(rootDir)+ for (const [zipPath, file] of imageEntries) {+ throwIfAborted(signal)+ const relPath = mineruAssetRelPath(options.sourceSummarySlug, zipPath)+ const absPath = `${pp}/wiki/${relPath}`+ const bytes = await file.async("uint8array")+ await writeFileBase64(absPath, bytesToBase64(bytes))+ pathMap.set(zipPath, relPath)+ pathMap.set(decodeMineruPath(zipPath), relPath)+ const basename = getFileName(zipPath)+ if (basenameCounts.get(basename) === 1) {+ pathMap.set(basename, relPath)+ pathMap.set(decodeMineruPath(basename), relPath)+ }+ }++ return pathMap+}++async function downloadAndExtractMarkdown(+ zipUrl: string,+ signal?: AbortSignal,+ assetOptions?: MineruAssetOptions,+): Promise<string> {const httpFetch = await getHttpFetch()throwIfAborted(signal)const res = await httpFetch(zipUrl, { signal })@@ -280,7 +551,23 @@ async function downloadAndExtractMarkdown(zipUrl: string, signal?: AbortSignal):const fullMd = mdEntries.find(([relativePath]) =>relativePath.split("/").pop()?.toLowerCase() === "full.md")- return await (fullMd ?? mdEntries[0])[1].async("string")+ const markdown = await (fullMd ?? mdEntries[0])[1].async("string")+ const markdownWithTables = convertHtmlTablesToMarkdown(markdown)+ if (!assetOptions) return markdownWithTables++ try {+ const pathMap = await saveMineruZipImages(zip, assetOptions, signal)+ return pathMap.size > 0+ ? rewriteMineruMarkdownImages(markdownWithTables, pathMap)+ : markdownWithTables+ } catch (err) {+ if (signal?.aborted) throw err+ console.warn(+ "[MinerU] failed to save extracted images; keeping parsed Markdown text:",+ err instanceof Error ? err.message : err,+ )+ return markdownWithTables+ }}// ── Public API ──@@ -300,6 +587,7 @@ export async function parseWithMineru(sourceUrl?: string,onProgress?: (msg: string) => void,signal?: AbortSignal,+ assetOptions?: MineruAssetOptions,): Promise<string> {throwIfAborted(signal)if (!config.token) throw new Error("MinerU API token not configured")@@ -339,7 +627,7 @@ export async function parseWithMineru(}onProgress?.("Downloading parsed result...")- const markdown = await downloadAndExtractMarkdown(zipUrl, signal)+ const markdown = await downloadAndExtractMarkdown(zipUrl, signal, assetOptions)onProgress?.("Done")return markdown@@ -374,5 +662,7 @@ export const __mineruTest = {downloadAndExtractMarkdown,mineruApiErrorMessage,decodeBase64ToBytes,+ rewriteMineruMarkdownImages,+ convertHtmlTablesToMarkdown,MAX_ACCURATE_PARSE_BYTES,}