import { plugin, type BunPlugin } from "bun";

const imagePlugin: BunPlugin = {
    name: "Image loader",
    async setup(build) {
        build.onLoad({ filter: /\.(png|jpe?g)$/ }, async (args) => {
            const arrayBuffer = await Bun.file(args.path).arrayBuffer();
            const buffer = Buffer.from(arrayBuffer);
            const src = `data:;base64,${buffer.toString('base64')}`;
            return {
                contents: `
                    const img = new Image();
                    const promise = new Promise((resolve, reject) => {
                        img.onload = resolve;
                        img.onerror = reject;
                    });
                    img.src = (${JSON.stringify(src)});

                    await promise;
                    
                    export default img;
                `,
                loader: 'js',
            };
        });
    }
};

plugin(imagePlugin);

export default imagePlugin;