Page MenuHomeSealhub

load-assets.ts
No OneTemporary

load-assets.ts

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";
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;
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: any) {
build.onLoad(
{
filter: new RegExp(
`\\.(${embeddable_file_extensions.join("|")})$`
),
},
async (args: any) => {
let 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,
};
}
);
},
};

File Metadata

Mime Type
text/x-java
Expires
Wed, May 7, 19:46 (1 d, 3 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
630874
Default Alt Text
load-assets.ts (1 KB)

Event Timeline