lovell / sharp

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
https://sharp.pixelplumbing.com
Apache License 2.0
29.17k stars 1.3k forks source link

WASM32 backend overrides global Worker #4198

Closed mdekstrand closed 1 month ago

mdekstrand commented 2 months ago

I realize I'm probably operating in very unsupported territory here, but I was doing some experimenting with Sharp on WASM and wanted to report what I found in case the developers want to look at it in the future.

I am experimenting with using the WASM32 backend for Sharp in Deno, mostly to see if it works but also to reduce my use of native modules. Since Deno doesn't support fine-grained control of Node dependencies, I did this test by creating a modified Sharp package to remove all optional dependencies except the WASM32 backend, but the specific problem arises just from loading @img/sharp-wasm32/sharp.node.

Sharp correctly loads the WASM32 backend on Deno but the Enscripten-generated loader code assigns to global.Worker, overriding the Worker class with an incompatible one. The result is that code that uses web workers and loads @img/sharp-wasm32 will no longer work, as new Worker(...) creates an object that is not compatible with the Web Workers API.

Steps to reproduce:

  1. Load @img/sharp-wasm32
  2. Try to use Web Workers with new Worker (specifically, addEventListener is missing)
lovell commented 2 months ago

The WebAssembly build of sharp is compiled using ENVIRONMENT_IS_NODE as emscripten currently requires this to generate a Node.js compatible binary (with a global Worker defined, as you've seen).

https://github.com/lovell/sharp/blob/fc32e0bd3f9111b80cf078df7b0cfc355695674e/src/binding.gyp#L194

There's been some discussion around improving Deno support in emscripten at https://github.com/emscripten-core/emscripten/issues/12203 and https://github.com/emscripten-core/emscripten/pull/19359 so this is probably an upstream thing.

lovell commented 1 month ago

Closing as I don't think there's anything we can do - I've linked to a couple of upstream issues that you should subscribe to. Happy to re-open if we need to do anything to take advantage of any changes they introduce.