const esbuild = require("esbuild")
const fs = require("fs")
const { parse, compileTemplate } = require("@vue/compiler-sfc")

esbuild.build({
    entryPoints: ["app.js"],
    bundle: true,
    outfile: "dist.js",
    format: "iife",
    platform: "browser",

    define: {
        "process.env.NODE_ENV": '"production"'
    },

    plugins: [
        {
            name: "vue2-sfc",
            setup(build) {

                build.onLoad({ filter: /\.vue$/ }, async (args) => {

                    const source = fs.readFileSync(args.path, "utf8")

                    const parsed = parse(source)

                    if (!parsed.descriptor) {
                        return { contents: "" }
                    }

                    const descriptor = parsed.descriptor

                    let scriptCode = ""

                    if (descriptor.script && descriptor.script.content) {
                        scriptCode = descriptor.script.content
                    }

                    let templateCode = ""

                    if (descriptor.template && descriptor.template.content) {

                        const compiled = compileTemplate({
                            source: descriptor.template.content,
                            filename: args.path,
                            id: args.path
                        })

                        templateCode = compiled.code
                    }

                    return {
                        contents: `
${scriptCode}

${templateCode}
`
                    }
                })
            }
        }
    ]
}).catch(() => process.exit(1))