scripts/build/esbuild-plugins/umd.mjs/esbuildPluginUmd
export default function esbuildPluginUmd({ name }) {
  return {
    name: "umd",
    setup(build) {
      const options = build.initialOptions;
      const { globalName, format, outfile } = options;

      if (globalName) {
        throw new Error("'globalName' in options cannot be set.");
      }

      if (format !== "umd") {
        throw new Error("'format' options must be 'umd'.");
      }

      if (!outfile) {
        throw new Error("'outfile' options is required.");
      }

      const {
        name: temporaryName,
        intro,
        outro,
        expectedOutput,
      } = getUmdWrapper(name, build);
      options.globalName = temporaryName;
      options.format = "iife";

      build.onEnd((result) => {
        if (result.errors.length > 0) {
          return;
        }

        if (!fs.existsSync(outfile)) {
          throw new Error(`${outfile} not exists`);
        }
        const text = fs.readFileSync(outfile, "utf8").trim();
        const actualOutput = {
          start: text.slice(0, expectedOutput.start.length),
          end: text.slice(-expectedOutput.end.length),
        };
        for (const property of ["start", "end"]) {
          if (actualOutput[property] !== expectedOutput[property]) {
            console.log();
            console.error(outdent`
              Expected output ${property}s with:
              ${expectedOutput[property]}

              Got:
              ${actualOutput[property]}
            `);
            throw new Error("Unexpected output");
          }
        }

        fs.writeFileSync(
          outfile,
          intro +
            text
              .slice(expectedOutput.start.length, -expectedOutput.end.length)
              .trimEnd() +
            outro
        );
      });
    },
  };
}