Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

31.1 KB
Raw Blame
import tailwindcss from '@tailwindcss/postcss'
import autoprefixer from 'autoprefixer'
import chokidar from 'chokidar'
import cors from 'cors'
import cssnano from 'cssnano'
import { analyzeMetafile, context } from 'esbuild'
import { lessLoader } from 'esbuild-plugin-less'
import { polyfillNode } from 'esbuild-plugin-polyfill-node'
import { sassPlugin } from 'esbuild-sass-plugin'
import express from 'express'
import fse from 'fs-extra'
import fs from 'node:fs/promises'
import * as path from 'node:path'
import { fileURLToPath } from 'node:url'
import postcss from 'postcss'
import postcssPresetEnv from 'postcss-preset-env'
import ts from 'typescript'

import { chunkLoaderScript, chunkMapFileContents, chunkMapFileName } from './chunkLoader.mjs'
import { cssLoaderScript, stableCssLoaderScript } from './cssLoader.mjs'

// Re-exported for one-shot builds outside buildInParallel (e.g. the toolbar loader, which is
// built after the toolbar app build so it can embed the hashed entry filename). Consumers
// depend on @posthog/esbuilder, not on esbuild directly, so pnpm's strict node_modules
// wouldn't let them import 'esbuild' themselves.
export { build as esbuildBuild } from 'esbuild'

const defaultHost = process.argv.includes('--host') && process.argv.includes('0.0.0.0') ? '0.0.0.0' : 'localhost'
const defaultPort = 8234

export const isDev = process.argv.includes('--dev')

export function copyPublicFolder(srcDir, destDir) {
    fse.copySync(srcDir, destDir, { overwrite: true }, function (err) {
        if (err) {
            console.error(err)
        }
    })
}

export function copySnappyWASMFile(absWorkingDir, destDir = path.resolve(absWorkingDir, 'dist')) {
    try {
        fse.ensureDirSync(destDir)
        fse.copyFileSync(
            path.resolve(absWorkingDir, 'node_modules/snappy-wasm/es/snappy_bg.wasm'),
            path.resolve(destDir, 'snappy_bg.wasm')
        )
    } catch (error) {
        console.warn('Could not copy snappy wasm file:', error.message)
    }
}

export function copyRRWebWorkerFiles(absWorkingDir, distSubdir = 'dist') {
    // Mirror rrweb's image-bitmap worker sourcemap (shipped from posthog-js) into the output
    // dir so the sourceMappingURL baked into our bundled rrweb resolves under collectstatic.
    // ManifestStaticFilesStorage resolves the reference relative to the referencing file's
    // directory, so every outdir that bundles rrweb needs its own copy.
    try {
        const rrwebSourceDir = path.resolve(absWorkingDir, 'node_modules/posthog-js/dist')
        const distDir = path.resolve(absWorkingDir, distSubdir)
        const files = fse.readdirSync(rrwebSourceDir)
        const mapFiles = files.filter((f) => f.startsWith('image-bitmap-data-url-worker-') && f.endsWith('.js.map'))
        mapFiles.forEach((file) => {
            fse.copyFileSync(path.join(rrwebSourceDir, file), path.join(distDir, file))
        })
    } catch (error) {
        console.warn('Could not copy rrweb map files:', error.message)
    }
}

export function copyIndexHtml(
    absWorkingDir = '.',
    from = 'src/index.html',
    to = 'dist/index.html',
    entry = 'index',
    chunks = {},
    entrypoints = [],
    stable = null
) {
    // Takes a html file, `from`, and some artifacts from esbuild, and injects
    // some javascript that will load these artifacts dynamically, based on an
    // expected `window.JS_URL` javascript variable.
    //
    // `JS_URL` is expected to be injected into the html as part of Django html
    // template rendering. We do not know what JS_URL should be at runtime, as,
    // for instance, on PostHog Cloud, we want to use the official PostHog
    // Docker image, but serve the js and it's dependencies from e.g. CloudFront
    const buildId = new Date().valueOf()

    const bootScript = (chunks, entrypoints, { isStable = false, eagerCss = [] } = {}) => {
        const relativeFiles = entrypoints.map((e) => path.relative(path.resolve(absWorkingDir, 'dist'), e))
        const jsFile =
            relativeFiles.length > 0 ? relativeFiles.find((e) => e.endsWith('.js')) : `${entry}.js?t=${buildId}`
        const cssFile =
            relativeFiles.length > 0 ? relativeFiles.find((e) => e.endsWith('.css')) : `${entry}.css?t=${buildId}`

        const jsFileFallback = `${entry}.js?t=${buildId}`
        // The stable entry may already have run some stable chunks when it fails, and the default
        // entry would then run a second copy of those modules. So the stable variant reloads the page
        // on the default build instead. The server always serves the default build for
        // ?stable_chunks=fallback, so the reload cannot loop, and it stores no choice, so the next
        // navigation tries the stable build again.
        const entryFallback = isStable
            ? `
                        var url = new URL(window.location.href)
                        url.searchParams.set('stable_chunks', 'fallback')
                        window.location.replace(url.toString())`
            : `
                        await import((window.JS_URL || '') + '/static/' + ${JSON.stringify(jsFileFallback)})`
        const scriptCode = `
            // The server has already applied ?stable_chunks (1 and 0 also set the choice cookie),
            // so drop it from the address bar. A bookmarked or shared URL must not keep forcing a build.
            if (window.location.search.indexOf('stable_chunks=') !== -1) {
                var cleanUrl = new URL(window.location.href)
                cleanUrl.searchParams.delete('stable_chunks')
                window.history.replaceState(window.history.state, '', cleanUrl.toString())
            }
            window.ESBUILD_LOAD_SCRIPT = async function (file) {
                try {
                    await import((window.JS_URL || '') + '/static/' + file)
                } catch (error) {
                    console.error('Error loading chunk: "' + file + '"')
                    console.error(error)
                    if (file === ${JSON.stringify(jsFile)} && file !== ${JSON.stringify(jsFileFallback)}) {${entryFallback}
                    }
                }
            }
            window.ESBUILD_LOAD_SCRIPT(${JSON.stringify(jsFile)})
        `

        // Esbuild "chunks" a scene into possibly hundreds of tiny files. When we load the first few files,
        // they tell us which other files to load. This cascading loading is slow. That's why we cache
        // the list of chunks per scene, and load them all in parallel when a scene is loaded.
        //
        // The full map is written to its own content-hashed file in dist and fetched by the inline
        // loader, instead of being inlined into the HTML: the map is hundreds of KB that changed on
        // every deploy and had to be downloaded and parsed before the app could boot, on every page.

        // Don't use chunks in dev mode.
        // Django caches the generated index.html, and we'll end up loading the wrong chunks after one change.
        const chunksToServe = isDev ? {} : chunks
        const chunkMapFile = Object.keys(chunksToServe).length > 0 ? chunkMapFileName(entry, chunksToServe) : null
        if (chunkMapFile) {
            fse.writeFileSync(path.resolve(absWorkingDir, 'dist', chunkMapFile), chunkMapFileContents(chunksToServe))
        }
        const chunkCode = Object.keys(chunks).length > 0 ? chunkLoaderScript(chunksToServe, chunkMapFile) : ''

        // Fallback to non-hashed CSS (with cache-busting build ID) when the hashed version fails or
        // stalls (e.g. CDN returns 403, or the request hangs). Mirrors the JS fallback above.
        const cssFileFallback = `${entry}.css?t=${buildId}`
        // The stable build links its split eager stylesheets and keeps the full one as its fallback.
        const cssLoader =
            isStable && eagerCss.length > 0
                ? stableCssLoaderScript(eagerCss, cssFile, cssFileFallback)
                : cssFile
                  ? cssLoaderScript(cssFile, cssFileFallback)
                  : ''

        return `<script nonce="{{ request.csp_nonce }}" type="application/javascript">
                    // The stylesheet link is added just below, at runtime, so a slow CSS fetch does
                    // not hold up these boot scripts. The loader publishes window.ESBUILD_CSS_READY,
                    // and the app entry waits on it before its first render, so React does not paint
                    // real markup that no stylesheet reaches. See cssLoader.mjs.
                    ${cssLoader}
                    ${scriptCode}
                    ${chunkCode}
                </script>`
    }

    // With stable chunk names built, the backend picks the boot variant per request. See
    // frontend/bin/stableChunkNames.mjs and the stable_chunks context in posthog/utils.py.
    const scripts = stable
        ? `{% if stable_chunks %}${bootScript(stable.chunks, stable.entrypoints, { isStable: true, eagerCss: stable.eagerCss ?? [] })}{% else %}${bootScript(chunks, entrypoints)}{% endif %}`
        : bootScript(chunks, entrypoints)

    fse.writeFileSync(
        path.resolve(absWorkingDir, to),
        fse.readFileSync(path.resolve(absWorkingDir, from), { encoding: 'utf-8' }).replace(
            '</head>',
            `   ${scripts}
            </head>`
        )
    )
}

/** Makes copies: "index-TMOJQ3VI.js" -> "index.js" */
export function createHashlessEntrypoints(absWorkingDir, entrypoints) {
    for (const entrypoint of entrypoints) {
        const withoutHash = entrypoint.replace(/-([A-Z0-9]+).(js|css)$/, '.$2')
        fse.writeFileSync(
            path.resolve(absWorkingDir, withoutHash),
            fse.readFileSync(path.resolve(absWorkingDir, entrypoint))
        )
    }
}

const tsconfigPath = isDev ? 'tsconfig.dev.json' : 'tsconfig.json'

const { config: tsconfig } = ts.readConfigFile(
    path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', tsconfigPath),
    ts.sys.readFile
)

/** @type {import('esbuild').BuildOptions} */
export const commonConfig = {
    sourcemap: true,
    minify: !isDev,
    target: tsconfig.compilerOptions.target, // We want the same target as tsconfig, should fail if tsconfig not found
    resolveExtensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css', '.less'],
    publicPath: '/static',
    assetNames: 'assets/[name]-[hash]',
    chunkNames: '[name]-[hash]',
    // no hashes in dev mode for faster reloads --> we save the old hash in index.html otherwise
    entryNames: isDev ? '[dir]/[name]' : '[dir]/[name]-[hash]',
    plugins: [
        // @posthog/brand's PNG stubs locate their image via `new URL("./x.png", import.meta.url)`,
        // which esbuild leaves verbatim in the output: the URL then resolves relative to the
        // built chunk's URL, where the PNG doesn't exist (404), and IIFE builds like the toolbar
        // have no import.meta at all. Rewrite the stub to a static import so the `.png` file
        // loader emits the image with a hashed name and a correct publicPath URL.
        {
            name: 'brand-png-asset-urls',
            setup(build) {
                build.onLoad(
                    { filter: /@posthog[\\/]brand[\\/]dist[\\/].*[\\/]png[\\/][^\\/]+\.mjs$/ },
                    async (args) => {
                        const source = await fs.readFile(args.path, 'utf8')
                        if (!source.includes('.png')) {
                            // png/index.mjs barrels only re-export the leaf stubs - nothing to rewrite.
                            return undefined
                        }
                        const contents = source.replace(
                            /const src = new URL\((".*?\.png"), import\.meta\.url\)\.href;?/,
                            'import src from $1;'
                        )
                        if (contents === source) {
                            // Stub shape changed upstream - fail loudly rather than shipping 404ing URLs.
                            throw new Error(`brand-png-asset-urls: no rewritable URL stub found in ${args.path}`)
                        }
                        return { contents, loader: 'js' }
                    }
                )
            },
        },
        // monaco-vim imports monaco-editor internals without .js extensions (e.g. monaco-editor/esm/vs/editor/editor.api)
        // which esbuild can't resolve through monaco-editor's package.json exports map
        {
            name: 'resolve-monaco-esm',
            setup(build) {
                build.onResolve({ filter: /^monaco-editor\/esm\// }, (args) => {
                    if (args.path.endsWith('.js')) {
                        return
                    }
                    return build.resolve(args.path + '.js', {
                        kind: args.kind,
                        resolveDir: args.resolveDir,
                    })
                })
            },
        },
        // zod re-exports every error-message locale as `z.locales`. Any import that keeps the whole
        // `z` object (a named `z` import, the default import, a shared chunk anchor) then ships all
        // of them. We only use `en`, which zod imports directly, so the locales barrel exports `en`
        // only. The eager graph check has a tripwire for another locale file in case the path moves.
        {
            name: 'zod-en-locale-only',
            setup(build) {
                build.onLoad({ filter: /[\\/]zod[\\/]v4[\\/]locales[\\/]index\.js$/ }, (args) => ({
                    contents: 'export { default as en } from "./en.js";',
                    loader: 'js',
                    resolveDir: path.dirname(args.path),
                }))
            },
        },
        sassPlugin({
            async transform(source, resolveDir, filePath) {
                const plugins = [tailwindcss, autoprefixer, postcssPresetEnv({ stage: 0 })]
                if (!isDev) {
                    plugins.push(cssnano({ preset: 'default' }))
                }
                const result = await postcss(plugins).process(source, { from: filePath })
                // Tailwind reports each scanned source file as a PostCSS `dependency` message.
                // Surface them as esbuild watchFiles so editing a TSX file re-runs this
                // transform on tailwind.css in watch mode.
                const watchFiles = result.messages
                    .filter((message) => message.type === 'dependency' && message.file)
                    .map((message) => message.file)
                return { contents: result.css, loader: 'css', watchFiles }
            },
        }),
        lessLoader({ javascriptEnabled: true }),
        polyfillNode({
            globals: {
                buffer: false,
                process: true,
            },
            polyfills: {
                buffer: false,
                crypto: false,
                // The plugin stubs out fs by default but not fs/promises, which would pull in the whole fs polyfill.
                'fs/promises': 'empty',
                process: true,
                stream: false,
            },
        }),
    ],
    alias: {
        buffer: 'buffer',
        crypto: 'crypto-browserify',
        'node:crypto': 'crypto-browserify',
        stream: 'stream-browserify',
    },
    tsconfig: tsconfigPath,
    define: {
        global: 'globalThis',
        'process.env.NODE_ENV': isDev ? '"development"' : '"production"',
    },
    loader: {
        '.bin': 'file',
        '.wasm': 'file',
        '.ttf': 'file',
        '.png': 'file',
        '.gif': 'file',
        '.svg': 'file',
        '.woff': 'file',
        '.woff2': 'file',
        '.mp3': 'file',
        '.sql': 'text',
        '.yaml': 'text',
        '.md': 'text',
    },
    metafile: true,
}

function getInputFiles(result) {
    return new Set(
        result?.metafile
            ? Object.keys(result.metafile.inputs)
                  .map((key) => (key.includes(':') ? key.split(':')[1] : key))
                  .map((key) => (key.startsWith('/') ? key : path.resolve(process.cwd(), key)))
            : []
    )
}

function getChunks(result) {
    const chunks = {}
    for (const output of Object.values(result.metafile?.outputs || {})) {
        if (!output.entryPoint || output.entryPoint.startsWith('node_modules')) {
            continue
        }
        const importStatements = output.imports.filter(
            (i) => i.kind === 'import-statement' && i.path.startsWith('dist/chunk-')
        )
        const exports = output.exports.filter((e) => e !== 'default' && e !== 'scene')
        const isRootEntry = output.entryPoint === 'src/index.tsx' || output.entryPoint === 'src/exporter/index.tsx'
        if (importStatements.length > 0 && (exports.length > 0 || isRootEntry)) {
            chunks[exports[0] || 'index'] = importStatements.map((i) =>
                i.path.replace('dist/chunk-', '').replace('.js', '')
            )
        }
    }
    return chunks
}

function formatBytes(bytes) {
    if (bytes >= 1_000_000) {
        return `${(bytes / 1_000_000).toFixed(2)} MB`
    }
    if (bytes >= 1_000) {
        return `${(bytes / 1_000).toFixed(1)} KB`
    }
    return `${bytes} B`
}

function shortenInputPath(inputPath) {
    const pnpmMatch = inputPath.match(/node_modules\/\.pnpm\/([^/]+)\/node_modules\/(.+)$/)
    if (pnpmMatch) {
        const pkg = pnpmMatch[1].replace(/_.*$/, '')
        return `${pkg} (${pnpmMatch[2]})`
    }
    return inputPath
}

export function reportTopChunks(outputs, { topChunks = 10, topContributors = 5, label = 'chunks' } = {}) {
    if (!outputs) {
        return
    }
    const chunkEntries = Object.entries(outputs)
        .filter(([outputPath]) => /\/chunk-[A-Za-z0-9]+\.js$/.test(outputPath))
        .sort((a, b) => b[1].bytes - a[1].bytes)
        .slice(0, topChunks)
    if (chunkEntries.length === 0) {
        return
    }
    const lines = [`Top ${chunkEntries.length} ${label} by uncompressed size:`]
    for (const [outputPath, output] of chunkEntries) {
        const inputCount = Object.keys(output.inputs || {}).length
        lines.push(`  ${formatBytes(output.bytes).padStart(9)}  ${path.basename(outputPath)}  (${inputCount} inputs)`)
        const contributors = Object.entries(output.inputs || {})
            .sort((a, b) => b[1].bytesInOutput - a[1].bytesInOutput)
            .slice(0, topContributors)
        for (const [inputPath, info] of contributors) {
            lines.push(`               ${formatBytes(info.bytesInOutput).padStart(9)}  ${shortenInputPath(inputPath)}`)
        }
    }
    console.info(lines.join('\n'))
}

export async function buildInParallel(configs, { onBuildStart, onBuildComplete } = {}) {
    try {
        await Promise.all(
            configs.map((config) =>
                buildOrWatch({
                    ...config,
                    onBuildStart,
                    onBuildComplete,
                })
            )
        )
    } catch (error) {
        // esbuild already prints its own compile errors, but onBuildStart/onBuildComplete
        // failures (e.g. finalizeToolbarBuild) would otherwise die silently here.
        console.error(error)
        if (!isDev) {
            process.exit(1)
        }
    }

    if (!isDev) {
        process.exit(0)
    }
}

/** Get the main ".js" and ".css" files for a build */
function getBuiltEntryPoints(config, result) {
    // Normalise entryPoints: support both array form and object form { name: path }
    const entryValues = Array.isArray(config.entryPoints) ? config.entryPoints : Object.values(config.entryPoints || {})

    // Primary: scan the metafile directly — works regardless of entryNames overrides.
    // CSS outputs never have entryPoint set, so we find JS entries first, then locate
    // each companion CSS by matching the same base name (hashes differ between JS and CSS).
    const jsFiles = []
    for (const [outputPath, output] of Object.entries(result.metafile?.outputs || {})) {
        if (output.entryPoint && entryValues.includes(output.entryPoint) && outputPath.endsWith('.js')) {
            jsFiles.push(path.resolve(process.cwd(), outputPath))
        }
    }
    if (jsFiles.length > 0) {
        const allFiles = [...jsFiles]
        const allOutputPaths = Object.keys(result.metafile?.outputs || {})
        // Pair each entry JS with its companion CSS by stripping the optional
        // "-<hash>" suffix. The hash matcher excludes `-` so that a sibling
        // entry sharing a prefix can't have its CSS stolen — e.g. an `exporter`
        // entry must not match `dist/exporter-extra-HASH.css` (the `-extra-HASH`
        // segment contains a `-`, which fails the single-segment match).
        // esbuild's default hash is base32 (uppercase + digits, no hyphens) so
        // the constraint is compatible with default builds and allows mixed-
        // case alphabets too.
        const hashSuffixPattern = /(-[^./-]+)?\.js$/
        for (const jsFile of jsFiles) {
            const baseName = jsFile.replace(hashSuffixPattern, '')
            const escapedBase = baseName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
            const expectedCss = new RegExp(`^${escapedBase}(-[^./-]+)?\\.css$`)
            for (const outputPath of allOutputPaths) {
                if (!outputPath.endsWith('.css')) {
                    continue
                }
                const absoluteCss = path.resolve(process.cwd(), outputPath)
                if (expectedCss.test(absoluteCss)) {
                    allFiles.push(absoluteCss)
                }
            }
        }
        return allFiles
    }

    // Fallback: path-based convention for configs where metafile scan yields nothing
    let outfiles = []
    if (config.outdir) {
        // convert "src/index.tsx" --> /a/posthog/frontend/dist/index.js
        outfiles = entryValues.map((file) =>
            path
                .resolve(config.absWorkingDir, file)
                .replace('/src/', '/dist/')
                .replace(/\.[^.]+$/, '.js')
        )
    } else if (config.outfile) {
        outfiles = [path.resolve(config.absWorkingDir, config.outfile)]
    }

    const fallbackFiles = []
    for (const outfile of outfiles) {
        const fileNoExt = outfile.replace(/\.[^/]+$/, '')
        for (const file of Object.keys(result.metafile?.outputs || {})) {
            const absoluteFile = path.resolve(process.cwd(), file)
            if (
                (absoluteFile.startsWith(`${fileNoExt}-`) && (file.endsWith('.js') || file.endsWith('.css'))) ||
                absoluteFile === `${fileNoExt}.js` ||
                absoluteFile === `${fileNoExt}.css`
            ) {
                fallbackFiles.push(absoluteFile)
            }
        }
    }
    return fallbackFiles
}

let buildsInProgress = 0

// Serialize the heavy full-app bundles (PostHog App, Exporter). All esbuild contexts in a
// process multiplex over one Go service, so concurrent heavy rebuilds keep both build graphs
// resident at once — the summed peak is what OOM-kills the Docker builder. Each heavy build
// disposes its context before releasing the lock (see runBuild), so the next heavy build reuses
// the freed memory instead of stacking on top of it. Dev is unaffected: it keeps contexts alive
// for incremental watch rebuilds and isn't memory-constrained.
// onBuildComplete runs after the lock is released, so heavy post-build work there must take the
// lock too. The lock is not reentrant: fn must never call runExclusiveHeavy, or it waits forever.
let heavyBuildChain = Promise.resolve()
export function runExclusiveHeavy(fn) {
    const result = heavyBuildChain.then(fn)
    heavyBuildChain = result.then(
        () => {},
        () => {}
    )
    return result
}

export async function buildOrWatch(config) {
    const { absWorkingDir, name, heavy, onBuildStart, onBuildComplete, writeMetaFile, extraPlugins, ..._config } =
        config

    let buildPromise = null
    let buildAgain = false

    let inputFiles = new Set()

    // The aim is to make sure that when we request a build, then:
    // - we only build one thing at a time
    // - if we request a build when one is running, we'll queue it to start right after this build
    // - if we request a build multiple times when one is running, only one will start right after this build
    // - notify with callbacks when builds start and when they end.
    async function debouncedBuild() {
        if (buildPromise) {
            buildAgain = true
            return
        }
        buildAgain = false
        if (buildsInProgress === 0) {
            server?.pauseServer()
        }
        buildsInProgress++
        onBuildStart?.(config)
        buildPromise = runBuild()
        const buildResponse = await buildPromise
        buildPromise = null
        await onBuildComplete?.(config, buildResponse)
        buildsInProgress--
        if (buildsInProgress === 0) {
            server?.resumeServer()
            reloadLiveServer()
        }

        if (isDev && buildAgain) {
            void debouncedBuild()
        }
    }

    let esbuildContext = null
    let buildCount = 0
    const log = (logOpts) => {
        const icon = logOpts.success === undefined ? '🧱' : logOpts.success ? '🥇' : '🛑'
        let timingSuffix = ''
        if (logOpts.time) {
            timingSuffix = ` in ${(new Date() - logOpts.time) / 1000}s`
        }
        const message =
            logOpts.success === undefined
                ? buildCount === 1
                    ? 'Building'
                    : 'Rebuilding'
                : logOpts.success
                  ? buildCount === 1
                      ? 'Built'
                      : 'Rebuilt'
                  : buildCount === 1
                    ? 'Building failed'
                    : 'Rebuilding failed '

        console.info(`${icon} ${name ? `"${name}": ` : ''}${message}${timingSuffix}`)
    }

    async function runBuild() {
        if (!esbuildContext) {
            const combinedConfig = { ...commonConfig, ..._config }
            combinedConfig.plugins = [...commonConfig.plugins, ...(extraPlugins || [])]
            esbuildContext = await context(combinedConfig)
        }

        buildCount++
        const time = new Date()
        log({ name })

        // In production each build runs once then the process exits, so free the build graph
        // as soon as it's done instead of letting all contexts pile up until process.exit.
        // Dev keeps the context for incremental rebuilds. For heavy builds this dispose happens
        // inside the serialization lock, so the next heavy build starts with this one freed.
        async function rebuildAndRelease() {
            const result = await esbuildContext.rebuild()
            if (!isDev) {
                await esbuildContext.dispose()
                esbuildContext = null
            }
            return result
        }

        try {
            const buildResult = heavy && !isDev ? await runExclusiveHeavy(rebuildAndRelease) : await rebuildAndRelease()

            if (writeMetaFile) {
                await fs.writeFile(
                    `${config.name.toLowerCase().replace(/ /g, '-')}-esbuild-meta.json`,
                    JSON.stringify(buildResult.metafile)
                )
            }

            inputFiles = getInputFiles(buildResult)

            log({ success: true, name, time })
            return {
                entrypoints: getBuiltEntryPoints(config, buildResult),
                chunks: getChunks(buildResult),
                ...buildResult.metafile,
            }
        } catch (e) {
            if (isDev) {
                log({ success: false, name, time })
            } else {
                throw e
            }
        }
    }

    if (isDev) {
        chokidar
            .watch(
                [
                    path.resolve(absWorkingDir, 'src'),
                    path.resolve(absWorkingDir, '../common'),
                    path.resolve(absWorkingDir, '../products/*/manifest.tsx'),
                    path.resolve(absWorkingDir, '../products/*/frontend/**/*'),
                ],
                {
                    ignored: [/.*(Type|\.test\.stories)\.[tj]sx?$/, /(^|[/\\])node_modules([/\\]|$)/],
                    ignoreInitial: true,
                    followSymlinks: false,
                }
            )
            .on('all', async (event, filePath) => {
                if (inputFiles.size === 0) {
                    await buildPromise
                }

                // Manifests have been updated, so we need to rebuild urls.
                if (filePath.includes('manifest.tsx')) {
                    await import('../../frontend/build-products.mjs')
                }

                if (inputFiles.has(filePath)) {
                    void debouncedBuild()
                }
            })
    }

    await debouncedBuild()
}

export async function printResponse(response, { compact = true, color = true, verbose = false, ...opts } = {}) {
    let text = await analyzeMetafile('metafile' in response ? response.metafile : response, {
        color,
        verbose,
        ...opts,
    })
    if (compact) {
        text = text
            .split('\n')
            .filter((l) => !l.match(/^ {3}[^\n]+$/g) && l.trim())
            .join('\n')
    }
    console.info(text)
}

let clients = new Set()

function reloadLiveServer() {
    clients.forEach((client) => client.write(`data: reload\n\n`))
}

let server

export function startDevServer(absWorkingDir) {
    if (isDev) {
        console.info(`👀 Starting dev server`)
        server = startServer({ absWorkingDir })
        return server
    }
    console.info(`🛳 Starting production build`)
    return null
}

export function startServer(opts = {}) {
    const host = opts.host || defaultHost
    const port = opts.port || defaultPort
    const absWorkingDir = opts.absWorkingDir || '.'

    console.info(`🍱 Starting server at http://${host}:${port}`)

    let resolve = null
    let ifPaused = null

    function pauseServer() {
        if (!ifPaused) {
            ifPaused = new Promise((r) => (resolve = r))
        }
    }

    function resumeServer() {
        resolve?.()
        ifPaused = null
    }

    resumeServer()

    const app = express()
    app.on('error', function (e) {
        if (e.code === 'EADDRINUSE') {
            console.error(`🛑 http://${host}:${port} is already in use. Trying another port.`)
        } else {
            console.error(`🛑 ${e}`)
        }
        process.exit(1)
    })
    app.use(cors())
    app.get('/_reload', (request, response) => {
        response.writeHead(200, {
            'Content-Type': 'text/event-stream',
            Connection: 'keep-alive',
            'Cache-Control': 'no-cache',
        })
        clients.add(response)
        request.on('close', () => clients.delete(response))
    })
    app.get('*', async (req, res) => {
        if (req.url.startsWith('/static/')) {
            if (ifPaused) {
                if (!ifPaused.logged) {
                    console.info('⌛️ Waiting for build to complete...')
                    ifPaused.logged = true
                }
                await ifPaused
            }
            const pathFromUrl = req.url.replace(/^\/static\//, '')
            const filePath = path.resolve(absWorkingDir, 'dist', pathFromUrl)
            // protect against "/../" urls
            if (filePath.startsWith(path.resolve(absWorkingDir, 'dist'))) {
                res.sendFile(filePath.split('?')[0])
                return
            }
        }
        res.sendFile(path.resolve(absWorkingDir, 'dist', 'index.html'))
    })
    app.listen(port)

    return {
        pauseServer,
        resumeServer,
    }
}