Skip to content

armgit / VERT

Public Imported from GitHub
0

The next-generation file converter. Open source, fully local* and free forever.

refactor: use offical pandoc-wasm package (#218)

JovannMCaa1e23af5406
diff --git a/bun.lock b/bun.lock
index c0529b8..4b446f2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,7 +5,6 @@
"": {
"name": "vert",
"dependencies": {
- "@bjorn3/browser_wasi_shim": "^0.4.2",
"@ffmpeg/core": "0.12.10",
"@ffmpeg/core-mt": "0.12.10",
"@ffmpeg/ffmpeg": "^0.12.15",
@@ -35,6 +34,7 @@
"overlayscrollbars": "^2.16.0",
"overlayscrollbars-svelte": "^0.5.5",
"p-queue": "^10.0.0",
+ "pandoc-wasm": "^1.1.0",
"qoa-format": "^1.0.1",
"riff-file": "^1.0.3",
"sanitize-html": "^2.18.1",
@@ -766,6 +766,8 @@
"pako": ["[email protected]", "", {}, "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w=="],
+ "pandoc-wasm": ["[email protected]", "", { "dependencies": { "@bjorn3/browser_wasi_shim": "^0.4.2" } }, "sha512-IoWBsC/cbSZe71rcRtxXUxG+Auf8aGDHKYOQZA6OdwmUL2xdpQaqrSGhPa+6zfLdSar7cnyAmTWt6KU9n5kBjQ=="],
+
"parse-srcset": ["[email protected]", "", {}, "sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q=="],
"path-exists": ["[email protected]", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
diff --git a/package.json b/package.json
index 0b0fbb0..63b1b5c 100644
--- a/package.json
+++ b/package.json
@@ -46,7 +46,6 @@
"vite-plugin-wasm": "^3.6.0"
},
"dependencies": {
- "@bjorn3/browser_wasi_shim": "^0.4.2",
"@ffmpeg/core": "0.12.10",
"@ffmpeg/core-mt": "0.12.10",
"@ffmpeg/ffmpeg": "^0.12.15",
@@ -76,6 +75,7 @@
"overlayscrollbars": "^2.16.0",
"overlayscrollbars-svelte": "^0.5.5",
"p-queue": "^10.0.0",
+ "pandoc-wasm": "^1.1.0",
"qoa-format": "^1.0.1",
"riff-file": "^1.0.3",
"sanitize-html": "^2.18.1",
diff --git a/src/lib/converters/pandoc/pandoc.svelte.ts b/src/lib/converters/pandoc/pandoc.svelte.ts
index 33fa5a0..3236603 100644
--- a/src/lib/converters/pandoc/pandoc.svelte.ts
+++ b/src/lib/converters/pandoc/pandoc.svelte.ts
@@ -3,6 +3,7 @@ import { VertFile, type WorkerMessage } from "#lib/types";
import { ToastManager } from "#lib/util/toast.svelte";
import PandocWorker from "#lib/workers/pandoc?worker&url";
import { browser } from "$app/env";
+import pandocWasm from "pandoc-wasm/wasm?url";
import { SvelteMap } from "svelte/reactivity";
import { Converter, FormatInfo, formatDuration } from "../converter.svelte";
@@ -22,9 +23,7 @@ export class PandocConverter extends Converter {
protected async download(): Promise<void> {
if (!browser) return;
try {
- this.wasm = await fetch("/pandoc.wasm").then((r) =>
- r.arrayBuffer(),
- );
+ this.wasm = await fetch(pandocWasm).then((r) => r.arrayBuffer());
this.status = "ready";
return Promise.resolve();
@@ -111,7 +110,7 @@ export class PandocConverter extends Converter {
);
return new VertFile(
new File([result.output], file.name),
- result.isZip ? ".zip" : to,
+ result.zip ? ".zip" : to,
);
} finally {
this.clearTrackedConversion(file);
diff --git a/src/lib/converters/spessasynth/spessasynth.svelte.ts b/src/lib/converters/spessasynth/spessasynth.svelte.ts
index fa19242..88d134b 100644
--- a/src/lib/converters/spessasynth/spessasynth.svelte.ts
+++ b/src/lib/converters/spessasynth/spessasynth.svelte.ts
@@ -131,8 +131,12 @@ export class SpessaSynthConverter extends Converter {
this.activeConversions.delete(input.id);
}
+ private waitForMessage(
+ worker: Worker,
+ type?: string,
+ timeout = 0,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- private waitForMessage(worker: Worker, type?: string, timeout = 0): Promise<any> {
+ ): Promise<any> {
return new Promise((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const onMessage = (e: MessageEvent) => {
diff --git a/src/lib/types/pandoc-wasm.d.ts b/src/lib/types/pandoc-wasm.d.ts
new file mode 100644
index 0000000..6addefe
--- /dev/null
+++ b/src/lib/types/pandoc-wasm.d.ts
@@ -0,0 +1,38 @@
+declare module "pandoc-wasm/core" {
+ export interface PandocConvertOptions {
+ from?: string;
+ to?: string;
+ "input-files"?: string[];
+ "output-file"?: string;
+ "extract-media"?: string;
+ [key: string]: unknown;
+ }
+
+ export interface PandocConvertResult {
+ stdout: string;
+ stderr: string;
+ warnings: unknown[];
+ files: Record<string, Blob>;
+ mediaFiles: Record<string, Blob>;
+ }
+
+ export type PandocConvert = (
+ options: PandocConvertOptions,
+ stdin: string | null,
+ files: Record<string, string | Blob>,
+ ) => Promise<PandocConvertResult>;
+
+ export type PandocQuery = (options: {
+ query: string;
+ format?: string;
+ }) => Promise<unknown>;
+
+ export interface PandocInstance {
+ convert: PandocConvert;
+ query: PandocQuery;
+ }
+
+ export function createPandocInstance(
+ wasmBinary: BufferSource,
+ ): Promise<PandocInstance>;
+}
diff --git a/src/lib/workers/pandoc.ts b/src/lib/workers/pandoc.ts
index 8662024..74413df 100644
--- a/src/lib/workers/pandoc.ts
+++ b/src/lib/workers/pandoc.ts
@@ -1,26 +1,10 @@
import type { WorkerMessage } from "#lib/types";
-import * as wasiShim from "@bjorn3/browser_wasi_shim";
-import * as zip from "client-zip";
+import { makeZip } from "client-zip";
+import type { PandocInstance } from "pandoc-wasm/core";
+import { createPandocInstance } from "pandoc-wasm/core";
-self.onmessage = async (e) => {
- const message = e.data;
- try {
- const res = await handleMessage(message);
- if (!res) return;
- self.postMessage({
- ...res,
- id: message.id,
- });
- } catch (e) {
- self.postMessage({
- type: "error",
- error: e,
- id: message.id,
- });
- }
-};
-
-let wasm: ArrayBuffer = null!;
+const formatError = (err: unknown): string =>
+ err instanceof Error ? err.message : String(err);
type Format =
| ".md"
@@ -46,53 +30,114 @@ type Format =
| ".jats"
| ".adoc";
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-const handleMessage = async (message: WorkerMessage): Promise<any> => {
+let wasm: ArrayBuffer = null!;
+let pandocPromise: Promise<PandocInstance> | null = null;
+
+const ensurePandoc = (): Promise<PandocInstance> =>
+ (pandocPromise ??= createPandocInstance(wasm).catch((err) => {
+ pandocPromise = null;
+ throw err;
+ }));
+
+const handleMessage = async (
+ message: WorkerMessage,
+): Promise<Partial<WorkerMessage>> => {
switch (message.type) {
case "load": {
wasm = message.wasm;
- postMessage({ type: "loaded", id: "0" });
- break;
+ await ensurePandoc();
+ return { type: "loaded" };
}
case "convert": {
- try {
- const { to: ext, input } = message;
- const file = input.file as File;
- const to = ext as Format;
- const buf = new Uint8Array(await file.arrayBuffer());
- const args = `-f ${formatToReader(`.${file.name.split(".").pop() || ""}` as Format)} -t ${formatToReader(to)} --extract-media=.`;
- const [result, stderr, zip] = await pandoc(
- args,
- buf,
- file.name,
- to,
- );
- if (result.length === 0) {
- return {
- type: "error",
- error: stderr
- .replaceAll("\\n", "\n")
- .replaceAll('\\"', '"')
- .split('"')
- .slice(1, -1)
- .join('"'),
- errorKind: stderr.split(" ")[0],
- };
- }
+ const instance = await ensurePandoc();
+ const { to: ext, input } = message;
+ const file = input.file as File;
+ const to = ext as Format;
+ const from = `.${file.name.split(".").pop() || ""}` as Format;
+ const out = ext.startsWith(".") ? ext : `.${ext}`;
+ const baseName = input.name.replace(/\.[^.]+$/, "");
+ const outName = `${baseName}${out}`;
+
+ const options = {
+ from: formatToReader(from),
+ to: formatToReader(to),
+ "input-files": [file.name],
+ "output-file": outName,
+ "extract-media": ".",
+ };
+ const result = await instance.convert(options, null, {
+ [file.name]: file,
+ });
+ const outputFile = result.files[options["output-file"]];
+
+ if (result.stderr.trim()) return errorFromStderr(result.stderr);
+ if (!outputFile)
+ return {
+ type: "error",
+ error: `No output produced for ${from} to ${to}`,
+ };
+
+ const mediaEntries = Object.entries(result.mediaFiles);
+ if (mediaEntries.length > 0) {
+ const files: File[] = [new File([outputFile], outName)];
+ for (const [name, blob] of mediaEntries)
+ files.push(new File([blob], name));
+
+ const zip = makeZip(files);
return {
type: "finished",
- output: result,
- isZip: zip,
+ output: await readToEnd(zip.getReader()),
+ zip: true,
};
- } catch (e) {
- console.error(e);
- return { type: "error", error: e };
}
+
+ return {
+ type: "finished",
+ output: new Uint8Array(await outputFile.arrayBuffer()),
+ };
}
+
+ default:
+ return { type: "error", error: "Unknown message type" };
}
};
+const errorFromStderr = (
+ stderr: string,
+): Partial<WorkerMessage> & { errorKind?: string } => {
+ const error = stderr.trim();
+ const unknownOutput = error.match(/Unknown output format '(.+)'/);
+ const unknownInput = error.match(/Unknown input format '(.+)'/);
+ if (unknownOutput)
+ return { type: "error", errorKind: "PandocUnknownWriterError", error };
+ if (unknownInput)
+ return { type: "error", errorKind: "PandocUnknownReaderError", error };
+ if (error.includes("JSON missing pandoc-api-version"))
+ return { type: "error", errorKind: "PandocParseError", error };
+ return { type: "error", error };
+};
+
+const readToEnd = async (
+ reader: ReadableStreamDefaultReader<Uint8Array>,
+): Promise<Uint8Array> => {
+ const chunks: Uint8Array[] = [];
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value) chunks.push(value);
+ }
+
+ const total = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
+ const result = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ result.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return result;
+};
+
const formatToReader = (format: Format): string => {
switch (format) {
case ".md":
@@ -141,231 +186,17 @@ const formatToReader = (format: Format): string => {
throw new Error(`Unsupported format: ${format}`);
};
-async function pandoc(
- args_str: string,
- in_data: Uint8Array,
- in_name: string,
- out_ext: string,
-): Promise<[Uint8Array, string, boolean]> {
- if (!wasm) throw new Error("WASM not loaded");
- let stderr = "";
- const args = ["pandoc.wasm", "+RTS", "-H64m", "-RTS"];
- const env: string[] = [];
- const in_file = new wasiShim.File(in_data, {
- readonly: true,
- });
- const out_file = new wasiShim.File(new Uint8Array(), {
- readonly: false,
- });
- const map = new Map<string, wasiShim.File>([
- ["in", in_file],
- ["out", out_file],
- ]);
- const root = new wasiShim.PreopenDirectory("/", map);
- const fds = [
- new wasiShim.OpenFile(
- new wasiShim.File(new Uint8Array(), { readonly: true }),
- ),
- wasiShim.ConsoleStdout.lineBuffered((msg) => {
- console.log(`[WASI stdout] ${msg}`);
- }),
- wasiShim.ConsoleStdout.lineBuffered((msg) => {
- console.warn(`[WASI stderr] ${msg}`);
- stderr += msg + "\n";
- }),
- root,
- new wasiShim.PreopenDirectory("/tmp", new Map()),
- ];
-
- const wasi = new wasiShim.WASI(args, env, fds, { debug: false });
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const { instance }: { instance: any } = await WebAssembly.instantiate(
- wasm,
- {
- wasi_snapshot_preview1: wasi.wasiImport,
- },
- );
-
- wasi.initialize(instance);
-
- instance.exports.__wasm_call_ctors();
-
- function memory_data_view() {
- return new DataView(instance.exports.memory.buffer);
- }
-
- const argc_ptr = instance.exports.malloc(4);
- memory_data_view().setUint32(argc_ptr, args.length, true);
- const argv = instance.exports.malloc(4 * (args.length + 1));
- for (let i = 0; i < args.length; ++i) {
- const arg = instance.exports.malloc(args[i].length + 1);
- new TextEncoder().encodeInto(
- args[i],
- new Uint8Array(instance.exports.memory.buffer, arg, args[i].length),
- );
- memory_data_view().setUint8(arg + args[i].length, 0);
- memory_data_view().setUint32(argv + 4 * i, arg, true);
- }
- memory_data_view().setUint32(argv + 4 * args.length, 0, true);
- const argv_ptr = instance.exports.malloc(4);
- memory_data_view().setUint32(argv_ptr, argv, true);
-
- instance.exports.hs_init_with_rtsopts(argc_ptr, argv_ptr);
-
- const args_ptr = instance.exports.malloc(args_str.length);
- new TextEncoder().encodeInto(
- args_str,
- new Uint8Array(
- instance.exports.memory.buffer,
- args_ptr,
- args_str.length,
- ),
- );
-
- instance.exports.wasm_main(args_ptr, args_str.length);
- // list all files in /
- const openedPath = root.dir.path_open(0, BigInt(0), 0).fd_obj;
- const dirRet = openedPath.path_lookup(".", 0);
- const dir = dirRet.inode_obj;
- if (dir) {
- const opened = dir.path_open(0, BigInt(0), 0).fd_obj;
- if (!opened) {
- return [out_file.data, stderr, false];
- }
-
- const fs = readRecursive(opened);
- // const media = fs.get("media");
- // if (media && media.type === "folder") {
- // const file = new File(
- // [out_file.data],
- // `${in_name.split(".").slice(0, -1).join(".")}${out_ext}`,
- // );
- // const zipped = await zipFiles(file, media.entries);
- // return [zipped, stderr, true];
- // }
- // filter to folders
- const folders = [...fs.entries()].filter(
- (f) => f[0] !== "in" && f[0] !== "out",
- );
- if (folders.length > 0) {
- const file = new File(
- [new Uint8Array(Array.from(out_file.data))],
- `${in_name.split(".").slice(0, -1).join(".")}${out_ext}`,
- );
- const filteredMap = new Map<string, PandocFsEntry>();
- for (const [name, entry] of folders) {
- filteredMap.set(name, entry);
- }
- const zipped = await zipFiles(file, filteredMap);
- return [zipped, stderr, true];
- }
- }
- return [out_file.data, stderr, false];
-}
-
-const zipFiles = async (
- output: File,
- entries: PandocEntries,
-): Promise<Uint8Array> => {
- const zipFormatted = pandocToFiles(entries);
- const zipped = zip.makeZip([...zipFormatted, output]);
- // read the ReadableStream to the end
- const reader = zipped.getReader();
- const chunks: Uint8Array[] = [];
- let done = false;
- while (!done) {
- const { done: d, value } = await reader.read();
- done = d;
- if (value) {
- chunks.push(value);
- }
- }
- const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
- const result = new Uint8Array(totalLength);
- let offset = 0;
- for (const chunk of chunks) {
- result.set(chunk, offset);
- offset += chunk.length;
- }
- return result;
-};
-
-const pandocToFiles = (entries: PandocEntries, parent = ""): File[] => {
- const flattened: File[] = [];
-
- for (const [name, entry] of entries) {
- const fullPath = parent ? `${parent}/${name}` : name;
-
- if (entry.type === "folder") {
- const nestedFiles = pandocToFiles(entry.entries, fullPath);
- flattened.push(...nestedFiles);
- } else {
- const file = new File(
- [new Uint8Array(Array.from(entry.data))],
- fullPath,
- );
- flattened.push(file);
- }
- }
-
- return flattened;
-};
-
-const readRecursive = (fd: wasiShim.Fd): PandocEntries => {
- const entries = new Map<string, PandocFsEntry>();
- const stat = fd.fd_filestat_get().filestat;
- if (!stat) return entries;
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const dir: any = fd.path_lookup(".", 0).inode_obj;
- if (!dir) return entries;
- const dirEntries: Map<string, wasiShim.File | wasiShim.Directory> =
- dir.contents;
- const results = readRecursiveInternal(dirEntries);
- for (const [name, entry] of results) {
- entries.set(name, entry);
- }
-
- return entries;
-};
-
-const readRecursiveInternal = (
- contents: Map<string, wasiShim.File | wasiShim.Directory>,
-): PandocEntries => {
- const entries = new Map<string, PandocFsEntry>();
- for (const [name, entry] of contents) {
- if (entry instanceof wasiShim.File) {
- const file: PandocFile = {
- data: entry.data,
- type: "file",
- };
- entries.set(name, file);
- } else {
- const folder: PandocFolder = {
- entries: readRecursiveInternal(
- entry.contents as unknown as Map<
- string,
- wasiShim.File | wasiShim.Directory
- >,
- ),
- type: "folder",
- };
- entries.set(name, folder);
- }
+onmessage = async (e: MessageEvent<WorkerMessage>) => {
+ const message = e.data;
+ try {
+ const res = await handleMessage(message);
+ if (!res) return;
+ postMessage({ ...res, id: message.id });
+ } catch (err) {
+ postMessage({
+ type: "error",
+ error: formatError(err),
+ id: message.id,
+ });
}
- return entries;
};
-
-type PandocEntries = Map<string, PandocFsEntry>;
-
-interface PandocFile {
- data: Uint8Array;
- type: "file";
-}
-
-interface PandocFolder {
- entries: PandocEntries;
- type: "folder";
-}
-
-type PandocFsEntry = PandocFile | PandocFolder;
diff --git a/src/lib/workers/spessasynth.ts b/src/lib/workers/spessasynth.ts
index 592d402..8dbf508 100644
--- a/src/lib/workers/spessasynth.ts
+++ b/src/lib/workers/spessasynth.ts
@@ -99,7 +99,7 @@ const handleMessage = async (
convertMIDI(buffer, to, message.input.name),
);
} else {
- throw new Error(`Unsupported conversion: ${from} -> ${to}`);
+ throw new Error(`Unsupported conversion: ${from} to ${to}`);
}
if (!output.length)
diff --git a/src/lib/workers/vectorizer.ts b/src/lib/workers/vectorizer.ts
index 3aee8ca..e88e9f6 100644
--- a/src/lib/workers/vectorizer.ts
+++ b/src/lib/workers/vectorizer.ts
@@ -63,7 +63,7 @@ const handleMessage = async (
const optimizeStartedAt = performance.now();
svg = optimizeSync(raw, { multipass: true });
log(
- `optimized svg in ${Math.round(performance.now() - optimizeStartedAt)}ms (${raw.length} -> ${svg.length} chars)`,
+ `optimized svg in ${Math.round(performance.now() - optimizeStartedAt)}ms (${raw.length} to ${svg.length} chars)`,
);
}
diff --git a/static/pandoc.wasm b/static/pandoc.wasm
deleted file mode 100644
index 36321b5..0000000
Binary files a/static/pandoc.wasm and /dev/null differ
diff --git a/static/sw.js b/static/sw.js
index 3ff763d..b90a1b4 100644
--- a/static/sw.js
+++ b/static/sw.js
@@ -1,9 +1,9 @@
-const CACHE_NAME = "vert-wasm-cache-v6"; // updated when workers update
+const CACHE_NAME = "vert-wasm-cache-v7"; // updated when workers update
let coepCredentialless = false;
const WASM_FILES = [
- "/pandoc.wasm", // from https://github.com/haskell-wasm/pandoc-wasm
+ // any static wasm files that should be cached
];
const WASM_URL_PATTERNS = [
@@ -11,6 +11,7 @@ const WASM_URL_PATTERNS = [
/\/assets\/.*worker.*\.js$/, // prod worker files
/magick.*\.wasm$/, // magick-wasm (unneeded?)
/vips.*\.wasm$/, // wasm-vips (main + dynamic libs)
+ /pandoc.*\.wasm$/, // pandoc-wasm
/\/ffmpeg-core[^/]*\.(js|wasm)$/, // ffmpeg wasm core
];
diff --git a/vite.config.ts b/vite.config.ts
index 034df0f..6dd8e2c 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -4,10 +4,13 @@ import adapter from "@sveltejs/adapter-static";
import { sveltekit } from "@sveltejs/kit/vite";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
import { execSync } from "child_process";
+import { resolve } from "node:path";
import { defineConfig, type PluginOption } from "vite";
import wasm from "vite-plugin-wasm";
-// coollify removes the .git folder but exposes commit via SOURCE_COMMIT env variable
+const pandocPath = (path: string) => resolve("node_modules/pandoc-wasm", path);
+
+// coolify removes the .git folder but exposes commit via SOURCE_COMMIT env variable
let commitHash = process.env.SOURCE_COMMIT
? process.env.SOURCE_COMMIT.substring(0, 7) // shorten it lol
: "unknown";
@@ -55,6 +58,19 @@ export default defineConfig(({ command }) => {
return {
plugins,
+ resolve: {
+ alias: [
+ {
+ find: "pandoc-wasm/core",
+ replacement: pandocPath("src/core.js"),
+ },
+ {
+ // regex so it also matches the "?url" query suffix (a plain string wouldn't)
+ find: /^pandoc-wasm\/wasm/,
+ replacement: pandocPath("src/pandoc.wasm"),
+ },
+ ],
+ },
worker: {
plugins: () => [wasm()],
format: "es",