import { build } from "esbuild";
import { writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const project = dirname(fileURLToPath(new URL("../manifest.json", import.meta.url)));
const result = await build({
  entryPoints: [join(project, "src/entry.ts")],
  write: false,
  bundle: true,
  format: "esm",
  platform: "browser",
  target: "es2022",
  legalComments: "none",
  minify: true,
  treeShaking: true,
});
const source = result.outputFiles[0].text.replace(
  /export\{([A-Za-z_$][\w$]*) as default\};?\s*$/u,
  "export default $1;\n",
);
if (!/\bexport default [A-Za-z_$][\w$]*;\s*$/u.test(source)) {
  throw new Error("The live example bundle did not emit one default export.");
}
await writeFile(join(project, "plugin.js"), source);
