kosei28/ezog

Cloudflare Workers: The `initWasm()` function can be used only once.

Opened this issue ยท 1 comments

Hello ๐Ÿ‘‹

Thanks for this amazing module. Unfortunately I receive the following error when using it inside of a Cloudflare Worker (only tested locally using the wrangler CLI).

โœ˜ [ERROR] Uncaught (in promise) Error: Already initialized. The `initWasm()` function can be used only once.

  throw new Error("Already initialized. The `initWasm()` function can be used only once.");
        ^
      at initWasm
  (/home/user/og-test/node_modules/@resvg/resvg-wasm/index.mjs:414:10)
      at generate
  (/home/user/og-test/node_modules/ezog/src/cloudflare/generate.ts:9:10)

On a cold start, this error doesn't appear (the png is generated just fine). However, when reloading the page (not the worker), this error appears. I'm not sure if this is behavior just in the local dev environment, or if this happens on Cloudflare as well.

The call to resvg-js's initWasm() in the generate() function seems to be the culprit (Ref). Patching the line fixes the issue. However, if there are any actual errors thrown by the resvg-js lib (ex. getImports() fails), then it could lead to catastrophic failures down the line.

--- index.js	2023-01-17 14:26:00.850899319 -0500
+++ index2.js	2023-01-17 14:29:45.079281456 -0500
@@ -295,7 +295,9 @@
 
 async function generate(elements, options) {
   const svg = await generateSvg(elements, options);
-  await initWasm(resvgWasm)
+  try {
+    await initWasm(resvgWasm)
+  } catch (_) {} // This "fixes" the issue but is bad in practice
   const resvg = new Resvg(svg, { fitTo: { mode: "original" } });
   const png = resvg.render().asPng();
   return png;

I tried looking more into resvg-js's documentation to see if there was some way to check if the wasm is initialized already, but I'm completely unfamiliar with the library.

Thanks in advance!

Please try upgrading to resvg-wasm 2.3.1.