#!/usr/bin/env node
import { emptyDir } from "fs-extra";
import { analyzeMetafile, build, context } from "esbuild";
import minimist from "minimist";
import { writeFile } from "fs/promises";

const argv = minimist(process.argv.slice(2));

process.env.NODE_ENV = argv.env ?? "development";

const minify = process.env.NODE_ENV !== "development";
const analyze = argv.analyze ?? false;

await emptyDir("out");

/** @type {import('esbuild').Plugin} */
const externalModulePlugin = {
  name: "external-module",
  setup(build) {
    build.onResolve({ filter: /.*/, namespace: "file" }, (resolveArgs) => {
      if (
        ["mime-types", "whatwg-url", "form-data", "cpu-features"].find((name) =>
          resolveArgs.path.includes(name)
        )
      ) {
        return {
          path: resolveArgs.path,
          namespace: "external-module",
        };
      }

      return undefined;
    });
    build.onLoad({ filter: /.*/, namespace: "external-module" }, async () => {
      return {
        contents: "",
        loader: "js",
      };
    });
  },
};

/** @type {import('esbuild').BuildOptions} */
const options = {
  logLevel: "info",
  entryPoints: ["src/extension.ts"],
  bundle: true,
  format: "cjs",
  platform: "node",
  target: "node16",
  metafile: analyze,
  external: ["vscode"],
  loader: { ".node": "file" },
  outdir: "out",
  plugins: [externalModulePlugin],
};

if (minify) {
  options.minify = true;

  const result = await build(options);

  if (analyze) {
    await writeFile("./meta.json", JSON.stringify(result.metafile));

    if (argv.output) {
      console.log(await analyzeMetafile(result.metafile, { verbose: true }));
    }
  }
} else {
  options.sourcemap = true;

  const ctx = await context(options);
  await ctx.watch();
}
