jamsinclair / jSquash

Browser & Web Worker focussed wasm bundles derived from the Squoosh App.
Apache License 2.0
222 stars 14 forks source link

Passing a custom fetch function #57

Closed szymondlugolecki closed 3 months ago

szymondlugolecki commented 3 months ago

Is your feature request related to a problem? Please describe. When trying initialize a codec (WebAssembly Module) in SvelteKit it throws an error:

Error: Cannot use relative URL (/codecs/mozjpeg_dec_codec.wasm) with global fetch — use event.fetch instead: https://kit.svelte.dev/docs/web-standards#fetch-apis

Describe the solution you'd like Make it possible to add a custom fetch function to the module options:

import decodeJpeg, { init } from '@jsquash/jpeg/decode';

export const load = async ({ fetch }) => {
    await init(undefined, {
        fetch,
        locateFile: () => '/codecs/mozjpeg_dec_codec.wasm'
    });
}

Describe alternatives you've considered None

Additional context I think this works as a workaround:

import JPEG_DEC_WASM from '@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm?module';

export const load = async ({ fetch }) => {
    const response = await fetch(JPEG_DEC_WASM);
    const wasmArrayBuffer = await response.arrayBuffer();
    const wasmModule = new WebAssembly.Module(wasmArrayBuffer);

    await init(wasmModule);

    const image = await fetch('/dog.jpg')
    .then((res) => res.arrayBuffer())
    .then(decodeJpeg);
}