1
0
silverbullet/plugbox/bin/plugbox-bundle.mjs

77 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-03-04 11:09:25 +00:00
#!/usr/bin/env node
2022-03-04 09:26:41 +00:00
import esbuild from "esbuild";
import { readFile, unlink, writeFile } from "fs/promises";
import path from "path";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
2022-03-07 09:21:02 +00:00
async function compile(filePath, functionName, debug) {
let outFile = "out.js";
let inFile = filePath;
if (functionName) {
// Generate a new file importing just this one function and exporting it
inFile = "in.js";
await writeFile(
inFile,
`import {${functionName}} from "./${filePath}";
export default ${functionName};`
);
}
// TODO: Figure out how to make source maps work correctly with eval() code
2022-03-04 09:26:41 +00:00
let js = await esbuild.build({
2022-03-07 09:21:02 +00:00
entryPoints: [inFile],
2022-03-04 09:26:41 +00:00
bundle: true,
format: "iife",
globalName: "mod",
platform: "neutral",
2022-03-07 09:21:02 +00:00
sourcemap: false, //sourceMap ? "inline" : false,
minify: !debug,
outfile: outFile,
2022-03-04 09:26:41 +00:00
});
2022-03-07 09:21:02 +00:00
let jsCode = (await readFile(outFile)).toString();
2022-03-04 09:26:41 +00:00
jsCode = jsCode.replace(/^var mod ?= ?/, "");
2022-03-07 09:21:02 +00:00
await unlink(outFile);
if (inFile !== filePath) {
await unlink(inFile);
}
2022-03-04 09:26:41 +00:00
return jsCode;
}
2022-03-04 11:09:25 +00:00
async function bundle(manifestPath, sourceMaps) {
2022-03-04 09:26:41 +00:00
const rootPath = path.dirname(manifestPath);
2022-03-04 11:09:25 +00:00
const manifest = JSON.parse((await readFile(manifestPath)).toString());
2022-03-04 09:26:41 +00:00
for (let [name, def] of Object.entries(manifest.functions)) {
let jsFunctionName = def.functionName,
filePath = path.join(rootPath, def.path);
if (filePath.indexOf(":") !== -1) {
[filePath, jsFunctionName] = filePath.split(":");
}
2022-03-07 09:21:02 +00:00
def.code = await compile(filePath, jsFunctionName, sourceMaps);
delete def.path;
2022-03-04 09:26:41 +00:00
}
return manifest;
}
async function run() {
let args = await yargs(hideBin(process.argv))
.option("debug", {
type: "boolean",
})
.parse();
2022-03-04 11:09:25 +00:00
let generatedManifest = await bundle(args._[0], !!args.debug);
writeFile(args._[1], JSON.stringify(generatedManifest, null, 2));
2022-03-04 09:26:41 +00:00
}
run().catch((e) => {
console.error(e);
process.exit(1);
});