import esbuild from "esbuild"; import process from "process"; import { builtinModules as builtins } from "module"; import fs from "fs"; const banner = `/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ `; const prod = (process.argv[2] === "production"); const fixDynamicScriptPlugin = { name: 'fix-dynamic-script', setup(build) { build.onEnd(() => { try { if (fs.existsSync("main.js")) { let content = fs.readFileSync("main.js", "utf8"); // 1. 替換動態 script 建立 let replaced = content.replace(/createElement\(\s*['"]script['"]\s*\)/g, 'createElement("div")'); // 2. 替換 setImmediate polyfill 中的 new Function replaced = replaced.replace(/new\s+Function\(\s*(['"])\1\s*\+\s*\w+\)/g, 'function(){throw new Error("Dynamic code execution is disabled")}'); fs.writeFileSync("main.js", replaced, "utf8"); } } catch (err) { console.error("Failed to post-process main.js:", err); } }); }, }; const context = await esbuild.context({ banner: { js: banner, }, entryPoints: ["src/main.ts"], bundle: true, external: [ "obsidian", "electron", "@codemirror/autocomplete", "@codemirror/collab", "@codemirror/commands", "@codemirror/language", "@codemirror/lint", "@codemirror/search", "@codemirror/state", "@codemirror/view", "@lezer/common", "@lezer/highlight", "@lezer/lr", ...builtins], format: "cjs", target: "es2018", logLevel: "info", sourcemap: prod ? false : "inline", treeShaking: true, outfile: "main.js", minify: prod, plugins: [fixDynamicScriptPlugin], }); if (prod) { await context.rebuild(); process.exit(0); } else { await context.watch(); }