microduck-reachy-simulator / source /trainingCompilerPlugin.js
laureen
Publish static Space from 6953707
b968036
Raw History Blame Contribute Delete
1.37 kB
import { createReadStream, cpSync, mkdirSync, readdirSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
// Keep the compiler's relative WASM/sysroot URLs intact. These large assets
// are served locally and only fetched when the user first compiles a program.
export function trainingCompilerPlugin() {
const source = dirname(fileURLToPath(import.meta.resolve("@yowasp/clang")));
const files = new Set(readdirSync(source));
let outDir;
return {
name: "training-compiler",
configResolved(config) { outDir = resolve(config.root, config.build.outDir); },
configureServer(server) {
server.middlewares.use("/training-compiler", (req, res, next) => {
const name = req.url.split("?")[0].slice(1);
if (!files.has(name)) return next();
const path = join(source, name);
res.setHeader("Content-Type", name.endsWith(".js") ? "text/javascript" : name.endsWith(".wasm") ? "application/wasm" : "application/octet-stream");
res.setHeader("Content-Length", statSync(path).size);
createReadStream(path).on("error", next).pipe(res);
});
},
closeBundle() {
mkdirSync(join(outDir, "training-compiler"), { recursive: true });
cpSync(source, join(outDir, "training-compiler"), { recursive: true });
},
};
}