import { copyFile } from "fs/promises"; import { promises as fs } from "fs"; import md5 from "md5"; import path, { basename } from "node:path"; import _locreq from "locreq"; import { embeddable_file_extensions } from "../embeddable-file-extensions.js"; import { PluginBuild } from "esbuild"; const target_locreq = _locreq(process.cwd()); function addSuffix(filename: string, suffix: string) { return filename.replace(/(\.[a-zA-Z0-9]+)?$/, suffix + "$1"); } async function makeResourceURL(file_path: string) { const hash_base = file_path + (await fs.stat(file_path)).mtimeMs.toString(); const hash = md5(hash_base); const public_url = "dist/" + addSuffix(basename(file_path), "-" + hash.slice(0, 8)); const public_dir = "public"; await copyFile( file_path, target_locreq.resolve(path.resolve(public_dir, public_url)) ); return "/" + public_url; } export const load_assets_plugin = { name: "sealgen-load-assets", setup(build: PluginBuild) { build.onLoad( { filter: new RegExp( `\\.(${embeddable_file_extensions.join("|")})$` ), }, async (args) => { const contents = `export const url = "${await makeResourceURL( args.path )}"; const path = "${args.path}"; import fs from "fs"; let buffer_promise = null; export const getBuffer = function(){ if(buffer_promise) return buffer_promise; buffer_promise = fs.promises.readFile("${args.path}"); return buffer_promise; } export const getContent = async function(){ const buffer = await getBuffer(); return buffer.toString("utf-8"); } export const getBase64 = async function(){ const buffer = await getBuffer(); return buffer.toString("base64"); } export default { getContent, url, getBase64, getBuffer, path }; `; return { contents, }; } ); }, };