const babel = require("@babel/core");
const parser = require("@babel/parser");

const babelPlugin = () => ({
  name: "babel-plugin",
  setup(build) {
    build.onLoad({ filter: /app\/javascript\/.*\.*\.jsx?$/ }, async args => {
      const fs = require("fs").promises;
      const contents = await fs.readFile(args.path, "utf8");

      const ast = parser.parse(contents, {
        sourceType: "module",
        plugins: ["jsx"],
      });

      const result = babel.transformFromAstSync(ast, contents);
      const transformedContents = result?.code;

      return { contents: transformedContents, loader: "jsx" };
    });
  },
});

module.exports = { babelPlugin };
