garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/build.ts

raw

#!/usr/bin/env bun
/**
 * Build the hub's web page into `dist/` โ€” `index.html`, `app.js`, `app.css`, `sw.js`, `manifest.json`, the logo โ€”
 * which `build.rs` embeds in the midas binary. `./deploy.sh` runs this first.
 *
 * `--serve` adds a dev server on :3200 that forwards `/v1/*` to the workspace's hub
 * (`MIDAS_HUB`, as in `~/.config/midas/hub.env`), so the page runs against the
 * real workspace while it is edited.
 */
import {existsSync, rmSync} from 'node:fs'
import path from 'node:path'

const root = import.meta.dir
const dist = path.join(root, 'dist')
const serve = process.argv.includes('--serve')
const HUB = process.env.MIDAS_HUB || 'http://127.0.0.1:4791'
const PORT = Number(process.env.PORT || 3200)

async function build() {
    if (existsSync(dist)) rmSync(dist, {recursive: true})
    const result = await Bun.build({
        entrypoints: [path.join(root, 'src/index.ts')],
        // Fixed names: index.html names them, and the hub serves exactly these (src/web.rs).
        naming: 'app.[ext]',
        minify: !serve,
        outdir: dist,
        sourcemap: serve ? 'inline' : 'none',
        target: 'browser',
    })
    if (!result.success) {
        for (const log of result.logs) console.error(log)
        throw new Error('build failed')
    }
    // The font goes inside app.css, as data: the hub serves only the files it names (src/web.rs).
    const css = path.join(dist, 'app.css')
    const fonts = /url\(["']?([^"')]+\.woff2)["']?\)/g
    let text = await Bun.file(css).text()
    for (const [whole, file] of [...text.matchAll(fonts)]) {
        const bytes = Buffer.from(await Bun.file(file).arrayBuffer()).toString('base64')
        text = text.replace(whole, `url(data:font/woff2;base64,${bytes})`)
    }
    await Bun.write(css, text)
    // As they are: the service worker (at the root, for its scope), the manifest a phone installs the page from, and the logo.
    for (const f of ['index.html', 'sw.js', 'manifest.json', 'icon.svg', 'icon-192.png', 'icon-512.png']) await Bun.write(path.join(dist, f), Bun.file(path.join(root, 'src', f)))
    // Gzipped beside them, for a browser that says it takes gzip: a phone opening the page fetched 420 KB as it was.
    for (const f of ['app.js', 'app.css']) {
        await Bun.write(path.join(dist, `${f}.gz`), Bun.gzipSync(new Uint8Array(await Bun.file(path.join(dist, f)).arrayBuffer()), {level: 9}))
    }
    const kb = (f: string) => Math.round(Bun.file(path.join(dist, f)).size / 1024)
    console.log(`built dist/ (app.js ${kb('app.js')} KB, ${kb('app.js.gz')} KB gzipped; app.css ${kb('app.css')} KB, ${kb('app.css.gz')} KB gzipped)`)
}

await build()

if (serve) {
    // The board's stream (`/v1/stream`) is a WebSocket: carried to the hub's, message for message.
    type Pipe = {hub?: WebSocket; early: string[]}
    Bun.serve<Pipe>({
        port: PORT,
        websocket: {
            open(ws) {
                const hub = new WebSocket(HUB.replace(/^http/, 'ws') + '/v1/stream')
                ws.data.hub = hub
                hub.onopen = () => ws.data.early.splice(0).forEach((t) => hub.send(t))
                hub.onmessage = (e) => ws.send(String(e.data))
                hub.onclose = () => ws.close()
            },
            message(ws, msg) {
                const hub = ws.data.hub
                if (hub?.readyState === WebSocket.OPEN) hub.send(String(msg))
                else ws.data.early.push(String(msg))
            },
            close(ws) {
                ws.data.hub?.close()
            },
        },
        async fetch(req, server) {
            const url = new URL(req.url)
            if (url.pathname === '/v1/stream' && server.upgrade(req, {data: {early: []}})) return undefined
            if (url.pathname.startsWith('/v1/')) {
                return fetch(HUB + url.pathname + url.search, {
                    method: req.method,
                    headers: req.headers,
                    body: req.method === 'GET' ? undefined : await req.text(),
                })
            }
            const file = Bun.file(path.join(dist, url.pathname === '/' ? 'index.html' : url.pathname.slice(1)))
            // Its type said outright: a Response from a file sends none, and a browser draws no SVG without it.
            if (await file.exists()) return new Response(file, {headers: {'content-type': file.type}})
            // A place of the page (`/sessions/s3`): the page, as the hub answers it (src/web.rs).
            if (!url.pathname.split('/').pop()?.includes('.')) return new Response(Bun.file(path.join(dist, 'index.html')))
            return new Response('not found', {status: 404})
        },
    })
    console.log(`serving on http://localhost:${PORT}, /v1 โ†’ ${HUB}`)
}