const fs = require("fs")
const config = require("./esbuild.config.js")
const svelteConfig = require("./svelte.config")

// Server build must NOT overwrite buildInfo written by the frontend build,
// otherwise the server timestamp is newer → checkBuildVersion triggers spurious reload.
// Only generate if buildInfo.js doesn't exist yet (standalone server build).
if (!fs.existsSync(__dirname + "/api/hooks/lib/buildInfo.js")) {
    config.writeBuildInfo()
}
config.writeBuildInfo = null

config.options.sourcemap = true
config.options.minify = false
config.options.platform = "node"
config.options.format = "cjs"
// Keep modern syntax that goja supports natively and downlevel only unsupported features.
config.options.target = "esnext"
config.options.supported = { "async-await": false, "async-generator": false, "dynamic-import": false }
config.options.entryPoints = ["./frontend/src/ssr.ts"]
config.options.outfile = __dirname + "/api/hooks/lib/app.server.js"
// Remove splitting-related options inherited from the frontend build.
delete config.options.outdir
delete config.options.splitting
delete config.options.entryNames
delete config.options.chunkNames
delete config.options.outExtension
config.options.plugins = [
    config.sveltePlugin({
        compilerOptions: {
            generate: "server",
            css: "external",
            dev: (process.argv?.length > 2 ? process.argv[2] : "build") !== "build",
        },
        preprocess: svelteConfig.preprocess,
        filterWarnings: (warning) => {
            // filter out a11y
            if (warning.code.match(/^a11y/)) return false
            return true
        },
    }),
    config.resolvePlugin,
]

module.exports = config
