Skip to content

Using resvg-wasm on the Edge #382

@jdgamble555

Description

@jdgamble555

I'm trying to run @resvg/resvg-wasm on Vercel Edge.

import satori from 'satori';
import { html as toReactElement } from 'satori-html';
import type { SatoriOptions } from 'satori/wasm';
import type { Component } from 'svelte';
import { render } from 'svelte/server';
import { getRequestEvent } from '$app/server';

import { Resvg, initWasm } from '@resvg/resvg-wasm';
import resvg_wasm from "$lib/index_bg.wasm?inline";


let wasmInitialized = false;

export const generateImage = async <T extends Record<string, unknown>>(
    element: Component<T>,
    options: ImageResponseOptions,
) => {

    const { fetch } = getRequestEvent();


    if (!wasmInitialized) {
        try {
            await initWasm(resvg_wasm);

            wasmInitialized = true;
        } catch (e) {
            console.error(e);
        }
    }


    const { text, spanText } = options;

    const renderedSvelte = render(element as Component, { props: { text, spanText } });

    const fontFile = await fetch(
        'https://og-playground.vercel.app/inter-latin-ext-700-normal.woff',
    );
    const fontData: ArrayBuffer = await fontFile.arrayBuffer();

    options.fonts = [
        {
            name: 'Inter Latin',
            data: fontData,
            style: 'normal',
        },
    ];

    const elementHtml = toReactElement(renderedSvelte.body);

    const svg = await satori(elementHtml, {
        width: options.width || 1200,
        height: options.height || 630,
        fonts: options.fonts?.length ? options.fonts : [],
        tailwindConfig: options.tailwindConfig,
    });

    const svgBuffer = Buffer.from(svg);

    const png = new Resvg(svgBuffer, {
        fitTo: {
            mode: 'width',
            value: options.width || 1200
        }
    });

    const pngBuffer = png.render().asPng();

    return pngBuffer;
};
...

This works fine in testing, but not on deployment. I get:

CompileError: WebAssembly.instantiate(): Wasm code generation disallowed by embedder

Clearly @vercel/og works on the edge, but the source (before being compiled) is not open, so I'm not sure how they import it.

I am not fetching anything, as the code is embedded directly.

How should I import this module to work correctly?

J

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions