sharp icon indicating copy to clipboard operation
sharp copied to clipboard

Support manual instantiation of wasm binary

Open gvkhna opened this issue 10 months ago • 2 comments

Problem

I'm choosing to import the wasm binary into the bundle that is produced by vite like so for sharp:

import SharpWasm from '@img/sharp-wasm32/lib/sharp-wasm32.node.wasm?arraybuffer'

It's requiring hacky code. Read more about the same issue here: https://github.com/ArtifexSoftware/mupdf.js/issues/156

Suggestion

While it's unclear the route to go through because the loaders are compiled by emscripten. I wanted to report the issue regardless, I think ideally some simple way to manually load the library in a controlled manner should be supported, opting out of environment introspection which is very hacky at this point.

For instance: In the case of CanvasKit, it does export it's emscripten loader but doesn't type the instantiateWasm function, only the locateFile function, and so it's easier and more straightforward to provide the binary. This is ideally the way to do it, to provide a means to manually instantiate the wasm and let developers choose how they want to handle it.


export default function CanvasKitInit(opts?: CanvasKitInitOptions): Promise<CanvasKit>;

export interface CanvasKitInitOptions {
    /**
     * This callback will be invoked when the CanvasKit loader needs to fetch a file (e.g.
     * the blob of WASM code). The correct url prefix should be applied.
     * @param file - the name of the file that is about to be loaded.
     */
    locateFile(file: string): string;
}

Related: I'm going to link all of these together because they're addressing the same thing for different packages and the hassles involved for folks using bun/deno, and other means of working with the wasm binary that require jumping through hoops.

https://github.com/ArtifexSoftware/mupdf.js/issues/147

https://github.com/lovell/sharp/issues/3912

https://issues.skia.org/u/1/issues/409942760

gvkhna avatar Apr 11 '25 20:04 gvkhna

Unfortunately couldn't get sharp working with wasm and deno at all. Due to this issue related to emnapi. Sharp loads with wasm but then actually using it, for instance .toBuffer() triggers the this.refHandle.ref is not a function error.

https://github.com/toyobayashi/emnapi/pull/142

gvkhna avatar Apr 12 '25 02:04 gvkhna