import * as esbuild from "esbuild";

export const OMEGA_ESBUILD_MAIN_FIELDS = ["module", "main"];

export async function bundleOmegaEntrypoints(options) {
  const buildOptions = {
    absWorkingDir: options.cwd,
    entryPoints: options.entryPoints,
    bundle: true,
    format: "esm",
    platform: options.platform,
    target: options.target,
    mainFields: OMEGA_ESBUILD_MAIN_FIELDS,
    sourcemap: true,
    ...(options.outfile ? { outfile: options.outfile } : {}),
    ...(options.outdir ? { outdir: options.outdir } : {}),
    ...(options.splitting ? { splitting: true } : {}),
  };

  if (options.watch) {
    const context = await esbuild.context(buildOptions);
    await context.watch();
    console.log("omega esbuild watch started");
    await new Promise(() => {});
    return;
  }

  await esbuild.build(buildOptions);
}
