feat(bankai): bankai v10 — the isomorphic compiler & server on Vite 8
One command, zero config, and only the client ever bundles: v8 server code is plain ESM that Node runs as-authored, so there is no server build to rot (the lesson of v9). - start: Vite middleware mode + HMR with per-request streaming SSR via ssrLoadModule; a virtual client entry generates the browser glue so the user writes exactly one isomorphic module (plan decision D5). - build: client bundle via Vite 8/Rolldown, manifest-derived route assets in dist/bankai.json, service worker built with the precache list injected (choo-service-worker convention, manifest edition), brotli+gzip precompression of every text asset. - serve: immutable caching + precompressed negotiation for hashed assets, 103 Early Hints (res.writeEarlyHints) with the route's assets before every page, streaming SSR, and a window.initialState tail with script-breakout-safe serialization and choo internals filtered out. - inspect: raw/gzip/brotli size report. Integration tests drive the real counter example through build and serve, asserting the 103 interim response at the HTTP level. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014NgfSjHE11oFpoSnLVKLXd
This commit is contained in:
co-authored by
Claude Fable 5
parent
d755af5ca0
commit
7e08b585ac
+1
-1
@@ -11,7 +11,7 @@
|
|||||||
"node": ">=24"
|
"node": ">=24"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node --test packages/core/test/ packages/html/test/ packages/component/test/ packages/devtools/test/ packages/migrate/test/",
|
"test": "node --test packages/core/test/ packages/html/test/ packages/component/test/ packages/devtools/test/ packages/migrate/test/ packages/bankai/test/",
|
||||||
"test:e2e": "node --test test/e2e/",
|
"test:e2e": "node --test test/e2e/",
|
||||||
"bench": "node bench/render.js",
|
"bench": "node bench/render.js",
|
||||||
"bench:browser": "node bench/real-browser.js"
|
"bench:browser": "node bench/real-browser.js"
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// bankai <command> [entry] [options]
|
||||||
|
//
|
||||||
|
// bankai start <entry> dev server: Vite + HMR + streaming SSR
|
||||||
|
// bankai build <entry> production build (client bundle, manifest,
|
||||||
|
// service worker, precompression)
|
||||||
|
// bankai serve production server for a built app: static
|
||||||
|
// assets + 103 Early Hints + streaming SSR
|
||||||
|
// bankai inspect size report for the built output
|
||||||
|
//
|
||||||
|
// options: --port <n> --out <dir> --title <text>
|
||||||
|
|
||||||
|
import { parseArgs } from 'node:util'
|
||||||
|
|
||||||
|
const { values, positionals } = parseArgs({
|
||||||
|
allowPositionals: true,
|
||||||
|
options: {
|
||||||
|
port: { type: 'string' },
|
||||||
|
out: { type: 'string', default: 'dist' },
|
||||||
|
title: { type: 'string', default: 'choo' }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const [command, entry] = positionals
|
||||||
|
const port = values.port ? Number(values.port) : 8080
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (command === 'start') {
|
||||||
|
requireEntry(entry)
|
||||||
|
const { default: dev } = await import('./lib/dev.js')
|
||||||
|
const { origin } = await dev({ entry, port, title: values.title })
|
||||||
|
console.log(`bankai: dev server streaming on ${origin}`)
|
||||||
|
} else if (command === 'build') {
|
||||||
|
requireEntry(entry)
|
||||||
|
const { default: build } = await import('./lib/build.js')
|
||||||
|
const { outDir, compressed } = await build({ entry, outDir: values.out, title: values.title })
|
||||||
|
console.log(`bankai: built to ${outDir} (${compressed} asset(s) precompressed) — bankai serve to run it`)
|
||||||
|
} else if (command === 'serve') {
|
||||||
|
const { default: serve } = await import('./lib/serve.js')
|
||||||
|
const { origin } = await serve({ outDir: values.out, port })
|
||||||
|
console.log(`bankai: production server on ${origin}`)
|
||||||
|
} else if (command === 'inspect') {
|
||||||
|
const { default: inspect } = await import('./lib/inspect.js')
|
||||||
|
await inspect({ outDir: values.out })
|
||||||
|
} else {
|
||||||
|
console.log('usage: bankai <start|build|serve|inspect> [entry] [--port n] [--out dir] [--title text]')
|
||||||
|
process.exit(command ? 1 : 0)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('bankai:', err.message)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireEntry (value) {
|
||||||
|
if (!value) {
|
||||||
|
console.error('bankai: an entry module is required, e.g. bankai start app.js')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export { default as dev } from './lib/dev.js'
|
||||||
|
export { default as build } from './lib/build.js'
|
||||||
|
export { default as serve } from './lib/serve.js'
|
||||||
|
export { default as inspect } from './lib/inspect.js'
|
||||||
|
export { documentHead, documentTail, serializeState, assetLinks } from './lib/document.js'
|
||||||
|
export { resolveApp } from './lib/app.js'
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// The isomorphic entry contract (plan decision D5): the entry module's
|
||||||
|
// default export is either a choo app instance (typically
|
||||||
|
// `export default app.mount('body')` — mount() on the server records the
|
||||||
|
// selector and returns the app) or a factory returning one (preferred:
|
||||||
|
// fresh state per request). One module, three consumers: browser mount,
|
||||||
|
// server render, build metadata.
|
||||||
|
|
||||||
|
export function resolveApp (mod, entry) {
|
||||||
|
const value = mod && mod.default
|
||||||
|
if (!value) {
|
||||||
|
throw new Error(`bankai: ${entry} has no default export — export your choo app (or a function returning one)`)
|
||||||
|
}
|
||||||
|
// a factory is a plain function; an app instance has .mount
|
||||||
|
const app = typeof value === 'function' && !value.mount ? value() : value
|
||||||
|
if (typeof app.toStream !== 'function') {
|
||||||
|
throw new Error(`bankai: the default export of ${entry} is not a choo v8 app (missing toStream)`)
|
||||||
|
}
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectorOf (app) {
|
||||||
|
return app.selector || 'body'
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
// bankai build — the production build. Only the CLIENT is bundled: the
|
||||||
|
// server side of a choo v8 app is plain ESM that Node runs as-authored,
|
||||||
|
// so there is no server build to rot. Outputs:
|
||||||
|
// dist/assets/* hashed client chunks + css
|
||||||
|
// dist/.vite/manifest.json Vite's build manifest
|
||||||
|
// dist/bankai.json bankai's route/asset metadata for serving
|
||||||
|
// dist/sw.js service worker (if <entry dir>/sw.js exists),
|
||||||
|
// with the precached asset list defined in
|
||||||
|
// *.br / *.gz precompressed siblings for every text asset
|
||||||
|
|
||||||
|
import { readFile, writeFile, readdir, stat, access } from 'node:fs/promises'
|
||||||
|
import { join, dirname, resolve } from 'node:path'
|
||||||
|
import { brotliCompress, gzip, constants } from 'node:zlib'
|
||||||
|
import { promisify } from 'node:util'
|
||||||
|
|
||||||
|
import bankaiPlugin, { CLIENT_ID } from './plugin.js'
|
||||||
|
|
||||||
|
const brotli = promisify(brotliCompress)
|
||||||
|
const gzipP = promisify(gzip)
|
||||||
|
|
||||||
|
export default async function buildApp ({ entry, outDir = 'dist', title = 'choo' }) {
|
||||||
|
const { build } = await import('vite')
|
||||||
|
entry = resolve(entry)
|
||||||
|
outDir = resolve(outDir)
|
||||||
|
|
||||||
|
await build({
|
||||||
|
appType: 'custom',
|
||||||
|
plugins: [bankaiPlugin(entry)],
|
||||||
|
logLevel: 'warn',
|
||||||
|
build: {
|
||||||
|
outDir,
|
||||||
|
emptyOutDir: true,
|
||||||
|
manifest: true,
|
||||||
|
rollupOptions: { input: { main: CLIENT_ID } }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// derive the route-independent asset set from Vite's manifest
|
||||||
|
const manifest = JSON.parse(await readFile(join(outDir, '.vite', 'manifest.json'), 'utf8'))
|
||||||
|
const entryChunk = Object.values(manifest).find((m) => m.isEntry)
|
||||||
|
const modulepreload = (entryChunk.imports || []).map((key) => '/' + manifest[key].file)
|
||||||
|
const assets = {
|
||||||
|
scripts: ['/' + entryChunk.file],
|
||||||
|
modulepreload,
|
||||||
|
css: collectCss(manifest, entryChunk)
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta = { title, entry, assets, builtAt: new Date().toISOString() }
|
||||||
|
await writeFile(join(outDir, 'bankai.json'), JSON.stringify(meta, null, 2))
|
||||||
|
|
||||||
|
// service worker: <entry dir>/sw.js, built standalone with the asset
|
||||||
|
// list injected — the choo-service-worker convention, manifest edition
|
||||||
|
const swSource = join(dirname(entry), 'sw.js')
|
||||||
|
if (await exists(swSource)) {
|
||||||
|
const precache = ['/', ...assets.scripts, ...assets.modulepreload, ...assets.css]
|
||||||
|
await build({
|
||||||
|
appType: 'custom',
|
||||||
|
logLevel: 'warn',
|
||||||
|
define: { __BANKAI_ASSETS__: JSON.stringify(precache) },
|
||||||
|
build: {
|
||||||
|
outDir,
|
||||||
|
emptyOutDir: false,
|
||||||
|
rollupOptions: {
|
||||||
|
input: { sw: swSource },
|
||||||
|
output: { entryFileNames: 'sw.js' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// precompress text assets so the server never compresses at request time
|
||||||
|
const compressed = await precompress(outDir)
|
||||||
|
|
||||||
|
return { outDir, meta, compressed }
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectCss (manifest, entryChunk) {
|
||||||
|
const css = new Set(entryChunk.css || [])
|
||||||
|
for (const key of entryChunk.imports || []) {
|
||||||
|
for (const file of manifest[key].css || []) css.add(file)
|
||||||
|
}
|
||||||
|
return [...css].map((file) => '/' + file)
|
||||||
|
}
|
||||||
|
|
||||||
|
const COMPRESSIBLE = /\.(js|mjs|css|html|json|svg|txt|map)$/
|
||||||
|
|
||||||
|
async function precompress (dir) {
|
||||||
|
let count = 0
|
||||||
|
for (const name of await readdir(dir)) {
|
||||||
|
const path = join(dir, name)
|
||||||
|
const info = await stat(path)
|
||||||
|
if (info.isDirectory()) {
|
||||||
|
count += await precompress(path)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!COMPRESSIBLE.test(name) || info.size < 1024) continue
|
||||||
|
const data = await readFile(path)
|
||||||
|
await writeFile(path + '.br', await brotli(data, {
|
||||||
|
params: { [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY }
|
||||||
|
}))
|
||||||
|
await writeFile(path + '.gz', await gzipP(data, { level: constants.Z_BEST_COMPRESSION }))
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exists (path) {
|
||||||
|
try {
|
||||||
|
await access(path)
|
||||||
|
return true
|
||||||
|
} catch (e) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
// bankai start — the dev server: Vite middleware mode for the module
|
||||||
|
// graph and HMR, per-request streaming SSR of the same entry through
|
||||||
|
// vite.ssrLoadModule so server code shares Vite's transforms and cache.
|
||||||
|
|
||||||
|
import { createServer } from 'node:http'
|
||||||
|
|
||||||
|
import bankaiPlugin, { CLIENT_URL } from './plugin.js'
|
||||||
|
import { resolveApp } from './app.js'
|
||||||
|
import { documentHead, documentTail } from './document.js'
|
||||||
|
|
||||||
|
export default async function dev ({ entry, port = 8080, title = 'choo' }) {
|
||||||
|
const { createServer: createViteServer } = await import('vite')
|
||||||
|
|
||||||
|
const vite = await createViteServer({
|
||||||
|
appType: 'custom',
|
||||||
|
server: { middlewareMode: true },
|
||||||
|
plugins: [bankaiPlugin(entry)],
|
||||||
|
logLevel: 'warn'
|
||||||
|
})
|
||||||
|
|
||||||
|
const server = createServer((req, res) => {
|
||||||
|
vite.middlewares(req, res, async () => {
|
||||||
|
// not an asset Vite knows: this is a page navigation — SSR it
|
||||||
|
try {
|
||||||
|
const mod = await vite.ssrLoadModule(entry)
|
||||||
|
const app = resolveApp(mod, entry)
|
||||||
|
const state = {}
|
||||||
|
|
||||||
|
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
|
||||||
|
res.write(documentHead({
|
||||||
|
title,
|
||||||
|
scripts: ['/@vite/client', CLIENT_URL]
|
||||||
|
}))
|
||||||
|
|
||||||
|
for await (const chunk of app.toStream(req.url, state)) {
|
||||||
|
res.write(chunk)
|
||||||
|
}
|
||||||
|
res.end(documentTail(state))
|
||||||
|
} catch (err) {
|
||||||
|
vite.ssrFixStacktrace(err)
|
||||||
|
console.error(err)
|
||||||
|
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain' })
|
||||||
|
res.end('bankai dev error:\n\n' + (err.stack || err.message))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
await new Promise((resolve) => server.listen(port, resolve))
|
||||||
|
return {
|
||||||
|
server,
|
||||||
|
vite,
|
||||||
|
port: server.address().port,
|
||||||
|
origin: `http://localhost:${server.address().port}`,
|
||||||
|
close: async () => {
|
||||||
|
await vite.close()
|
||||||
|
await new Promise((resolve) => server.close(resolve))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// The HTML document around the app's streamed body. bankai owns the
|
||||||
|
// <head> (charset, viewport, title, asset links) and the tail
|
||||||
|
// (window.initialState + </html>); the app's view owns <body>.
|
||||||
|
// Page scripts live in <head> (type=module defers itself); the one
|
||||||
|
// exception is the initialState script, which must be inline and is
|
||||||
|
// emitted after the body — inline scripts execute during parse, module
|
||||||
|
// scripts only after it, so the order still holds.
|
||||||
|
|
||||||
|
export function documentHead ({ title, css = [], modulepreload = [], scripts = [] }) {
|
||||||
|
let head = '<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n'
|
||||||
|
if (title) head += `<title>${escapeHtml(title)}</title>\n`
|
||||||
|
for (const href of css) {
|
||||||
|
head += `<link rel="stylesheet" href="${escapeHtml(href)}">\n`
|
||||||
|
}
|
||||||
|
for (const href of modulepreload) {
|
||||||
|
head += `<link rel="modulepreload" href="${escapeHtml(href)}">\n`
|
||||||
|
}
|
||||||
|
for (const src of scripts) {
|
||||||
|
head += `<script type="module" src="${escapeHtml(src)}"></script>\n`
|
||||||
|
}
|
||||||
|
head += '</head>\n'
|
||||||
|
return head
|
||||||
|
}
|
||||||
|
|
||||||
|
export function documentTail (state) {
|
||||||
|
return `\n<script>window.initialState=${serializeState(state)}</script>\n</html>\n`
|
||||||
|
}
|
||||||
|
|
||||||
|
// choo internals that every boot recomputes \u2014 no point shipping them
|
||||||
|
const RECOMPUTED = new Set(['events', 'cache', 'prefetch'])
|
||||||
|
|
||||||
|
// JSON that is safe to embed in an inline <script>: no '</script>' or
|
||||||
|
// '<!--' breakouts, no raw line separators
|
||||||
|
export function serializeState (state) {
|
||||||
|
return JSON.stringify(state, function (key, value) {
|
||||||
|
if (this === state && RECOMPUTED.has(key)) return undefined
|
||||||
|
return value
|
||||||
|
})
|
||||||
|
.replace(/</g, '\\u003c')
|
||||||
|
.replace(/\u2028/g, '\\u2028')
|
||||||
|
.replace(/\u2029/g, '\\u2029')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Early Hints / Link header values for a route's assets
|
||||||
|
export function assetLinks ({ css = [], modulepreload = [], scripts = [] }) {
|
||||||
|
const links = []
|
||||||
|
for (const href of scripts) links.push(`<${href}>; rel=modulepreload`)
|
||||||
|
for (const href of modulepreload) links.push(`<${href}>; rel=modulepreload`)
|
||||||
|
for (const href of css) links.push(`<${href}>; rel=preload; as=style`)
|
||||||
|
return links
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml (str) {
|
||||||
|
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
// bankai inspect — what did the build produce, and how big is it on the
|
||||||
|
// wire? Reads the manifest + dist and prints raw/gzip/brotli sizes.
|
||||||
|
|
||||||
|
import { readFile, readdir, stat } from 'node:fs/promises'
|
||||||
|
import { join, resolve, relative } from 'node:path'
|
||||||
|
|
||||||
|
export default async function inspect ({ outDir = 'dist' }) {
|
||||||
|
outDir = resolve(outDir)
|
||||||
|
const meta = JSON.parse(await readFile(join(outDir, 'bankai.json'), 'utf8'))
|
||||||
|
|
||||||
|
const rows = []
|
||||||
|
await walk(outDir, rows, outDir)
|
||||||
|
rows.sort((a, b) => b.raw - a.raw)
|
||||||
|
|
||||||
|
console.log(`\nbankai build — ${meta.title} (${meta.builtAt})\n`)
|
||||||
|
console.log(' ' + 'file'.padEnd(44) + 'raw'.padStart(10) + 'gzip'.padStart(10) + 'brotli'.padStart(10))
|
||||||
|
let totals = { raw: 0, gz: 0, br: 0 }
|
||||||
|
for (const row of rows) {
|
||||||
|
totals.raw += row.raw
|
||||||
|
totals.gz += row.gz || 0
|
||||||
|
totals.br += row.br || 0
|
||||||
|
console.log(' ' + row.file.padEnd(44) + kb(row.raw) + kb(row.gz) + kb(row.br))
|
||||||
|
}
|
||||||
|
console.log(' ' + 'total'.padEnd(44) + kb(totals.raw) + kb(totals.gz) + kb(totals.br) + '\n')
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
async function walk (dir, rows, root) {
|
||||||
|
for (const name of await readdir(dir)) {
|
||||||
|
if (name === '.vite') continue
|
||||||
|
const path = join(dir, name)
|
||||||
|
const info = await stat(path)
|
||||||
|
if (info.isDirectory()) {
|
||||||
|
await walk(path, rows, root)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (name.endsWith('.br') || name.endsWith('.gz')) continue
|
||||||
|
const row = { file: relative(root, path), raw: info.size, gz: null, br: null }
|
||||||
|
row.gz = await sizeOf(path + '.gz')
|
||||||
|
row.br = await sizeOf(path + '.br')
|
||||||
|
rows.push(row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sizeOf (path) {
|
||||||
|
try {
|
||||||
|
return (await stat(path)).size
|
||||||
|
} catch (e) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function kb (bytes) {
|
||||||
|
if (bytes === null) return '—'.padStart(10)
|
||||||
|
return (bytes < 1024 ? bytes + ' B' : (bytes / 1024).toFixed(1) + ' kB').padStart(10)
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
// Vite plugin: a virtual client entry that mounts the user's app. The
|
||||||
|
// user writes one isomorphic module; bankai generates the two lines of
|
||||||
|
// browser glue instead of asking for a second file.
|
||||||
|
|
||||||
|
export const CLIENT_ID = 'bankai:client'
|
||||||
|
const RESOLVED_CLIENT_ID = '\0' + CLIENT_ID
|
||||||
|
|
||||||
|
// the URL a browser uses to import the virtual module through Vite's dev
|
||||||
|
// middleware ('\0' encodes as '__x00__')
|
||||||
|
export const CLIENT_URL = '/@id/__x00__' + CLIENT_ID
|
||||||
|
|
||||||
|
export default function bankaiPlugin (entry) {
|
||||||
|
return {
|
||||||
|
name: 'bankai',
|
||||||
|
resolveId (id) {
|
||||||
|
if (id === CLIENT_ID) return RESOLVED_CLIENT_ID
|
||||||
|
},
|
||||||
|
load (id) {
|
||||||
|
if (id === RESOLVED_CLIENT_ID) {
|
||||||
|
return [
|
||||||
|
`import create from ${JSON.stringify(entry)}`,
|
||||||
|
'const app = typeof create === "function" && !create.mount ? create() : create',
|
||||||
|
'app.mount(app.selector || "body")'
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
// bankai serve — the production server. Static assets from dist
|
||||||
|
// (precompressed variants negotiated, hashed assets cached forever);
|
||||||
|
// everything else is a page: 103 Early Hints from the build manifest,
|
||||||
|
// then streaming SSR of the entry module — imported natively, because
|
||||||
|
// the server side never needed a build.
|
||||||
|
|
||||||
|
import { createServer } from 'node:http'
|
||||||
|
import { createReadStream } from 'node:fs'
|
||||||
|
import { readFile, stat } from 'node:fs/promises'
|
||||||
|
import { join, normalize, extname, resolve } from 'node:path'
|
||||||
|
import { pathToFileURL } from 'node:url'
|
||||||
|
|
||||||
|
import { resolveApp } from './app.js'
|
||||||
|
import { documentHead, documentTail, assetLinks } from './document.js'
|
||||||
|
|
||||||
|
const MIME = {
|
||||||
|
'.html': 'text/html; charset=utf-8',
|
||||||
|
'.js': 'text/javascript; charset=utf-8',
|
||||||
|
'.mjs': 'text/javascript; charset=utf-8',
|
||||||
|
'.css': 'text/css; charset=utf-8',
|
||||||
|
'.json': 'application/json; charset=utf-8',
|
||||||
|
'.svg': 'image/svg+xml',
|
||||||
|
'.map': 'application/json',
|
||||||
|
'.txt': 'text/plain; charset=utf-8',
|
||||||
|
'.woff2': 'font/woff2',
|
||||||
|
'.png': 'image/png',
|
||||||
|
'.webp': 'image/webp',
|
||||||
|
'.ico': 'image/x-icon'
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function serve ({ outDir = 'dist', port = 8080 }) {
|
||||||
|
outDir = resolve(outDir)
|
||||||
|
const meta = JSON.parse(await readFile(join(outDir, 'bankai.json'), 'utf8'))
|
||||||
|
const mod = await import(pathToFileURL(meta.entry))
|
||||||
|
const links = assetLinks(meta.assets)
|
||||||
|
|
||||||
|
const server = createServer(async (req, res) => {
|
||||||
|
const url = new URL(req.url, 'http://localhost')
|
||||||
|
const pathname = decodeURIComponent(url.pathname)
|
||||||
|
|
||||||
|
// static asset?
|
||||||
|
const file = normalize(join(outDir, pathname))
|
||||||
|
if (file.startsWith(outDir) && extname(pathname)) {
|
||||||
|
if (await isFile(file)) return sendFile(req, res, file, pathname)
|
||||||
|
if (MIME[extname(pathname)]) {
|
||||||
|
// a missing asset is a miss, not a page
|
||||||
|
res.writeHead(404, { 'content-type': 'text/plain' })
|
||||||
|
return res.end('not found: ' + pathname)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// page: hints first, then stream
|
||||||
|
try {
|
||||||
|
const app = resolveApp(mod, meta.entry)
|
||||||
|
const state = {}
|
||||||
|
|
||||||
|
if (links.length && res.writeEarlyHints) {
|
||||||
|
res.writeEarlyHints({ link: links })
|
||||||
|
}
|
||||||
|
res.writeHead(200, {
|
||||||
|
'content-type': 'text/html; charset=utf-8',
|
||||||
|
link: links.join(', ')
|
||||||
|
})
|
||||||
|
res.write(documentHead({ title: meta.title, ...meta.assets }))
|
||||||
|
for await (const chunk of app.toStream(req.url, state)) {
|
||||||
|
res.write(chunk)
|
||||||
|
}
|
||||||
|
res.end(documentTail(state))
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err)
|
||||||
|
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain' })
|
||||||
|
res.end('bankai: render error')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
await new Promise((resolveListen) => server.listen(port, resolveListen))
|
||||||
|
return {
|
||||||
|
server,
|
||||||
|
port: server.address().port,
|
||||||
|
origin: `http://localhost:${server.address().port}`,
|
||||||
|
close: () => new Promise((resolveClose) => server.close(resolveClose))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function isFile (path) {
|
||||||
|
try {
|
||||||
|
return (await stat(path)).isFile()
|
||||||
|
} catch (e) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendFile (req, res, file, pathname) {
|
||||||
|
const headers = {
|
||||||
|
'content-type': MIME[extname(file)] || 'application/octet-stream',
|
||||||
|
// hashed build assets are immutable; everything else revalidates
|
||||||
|
'cache-control': pathname.startsWith('/assets/')
|
||||||
|
? 'public, max-age=31536000, immutable'
|
||||||
|
: 'no-cache',
|
||||||
|
vary: 'accept-encoding'
|
||||||
|
}
|
||||||
|
|
||||||
|
// negotiate precompressed siblings written at build time
|
||||||
|
const accepted = String(req.headers['accept-encoding'] || '')
|
||||||
|
for (const [encoding, ext] of [['br', '.br'], ['gzip', '.gz']]) {
|
||||||
|
if (accepted.includes(encoding) && await isFile(file + ext)) {
|
||||||
|
headers['content-encoding'] = encoding
|
||||||
|
res.writeHead(200, headers)
|
||||||
|
createReadStream(file + ext).pipe(res)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.writeHead(200, headers)
|
||||||
|
createReadStream(file).pipe(res)
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"name": "bankai",
|
||||||
|
"version": "10.0.0-dev",
|
||||||
|
"description": "The isomorphic choo compiler & server: one command, streaming SSR, zero config",
|
||||||
|
"type": "module",
|
||||||
|
"bin": {
|
||||||
|
"bankai": "./cli.js"
|
||||||
|
},
|
||||||
|
"exports": {
|
||||||
|
".": "./index.js"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"cli.js",
|
||||||
|
"index.js",
|
||||||
|
"lib"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"vite": "^8.0.0"
|
||||||
|
},
|
||||||
|
"repository": "choojs/choo",
|
||||||
|
"keywords": [
|
||||||
|
"choo",
|
||||||
|
"bankai",
|
||||||
|
"ssr",
|
||||||
|
"streaming",
|
||||||
|
"compiler"
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
// The full production pipeline against the real counter example:
|
||||||
|
// build → artifacts on disk → serve → 103 Early Hints, streamed SSR,
|
||||||
|
// filtered initialState, precompressed asset negotiation.
|
||||||
|
|
||||||
|
import { test, before, after } from 'node:test'
|
||||||
|
import assert from 'node:assert'
|
||||||
|
import http from 'node:http'
|
||||||
|
import { access, mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { join, dirname } from 'node:path'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
import build from '../lib/build.js'
|
||||||
|
import serve from '../lib/serve.js'
|
||||||
|
|
||||||
|
const repo = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')
|
||||||
|
const entry = join(repo, 'examples', 'counter', 'app.js')
|
||||||
|
|
||||||
|
let outDir, meta, srv
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
outDir = await mkdtemp(join(tmpdir(), 'bankai-test-'))
|
||||||
|
;({ meta } = await build({ entry, outDir, title: 'counter' }))
|
||||||
|
srv = await serve({ outDir, port: 0 })
|
||||||
|
})
|
||||||
|
|
||||||
|
after(async () => {
|
||||||
|
await srv?.close()
|
||||||
|
if (outDir) await rm(outDir, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
function get (path, headers = {}) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = http.request({ host: 'localhost', port: srv.port, path, headers }, (res) => {
|
||||||
|
const chunks = []
|
||||||
|
res.on('data', (d) => chunks.push(d))
|
||||||
|
res.on('end', () => resolve({
|
||||||
|
status: res.statusCode,
|
||||||
|
headers: res.headers,
|
||||||
|
body: Buffer.concat(chunks),
|
||||||
|
interim: req.interim
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
req.interim = []
|
||||||
|
req.on('information', (info) => req.interim.push(info))
|
||||||
|
req.on('error', reject)
|
||||||
|
req.end()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
test('build produced manifest, metadata and precompressed assets', async () => {
|
||||||
|
await access(join(outDir, '.vite', 'manifest.json'))
|
||||||
|
await access(join(outDir, 'bankai.json'))
|
||||||
|
assert.strictEqual(meta.assets.scripts.length, 1, 'one entry chunk')
|
||||||
|
const chunk = meta.assets.scripts[0]
|
||||||
|
await access(join(outDir, chunk.slice(1)))
|
||||||
|
await access(join(outDir, chunk.slice(1) + '.br'))
|
||||||
|
await access(join(outDir, chunk.slice(1) + '.gz'))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('pages get 103 Early Hints carrying the route assets', async () => {
|
||||||
|
const res = await get('/')
|
||||||
|
assert.strictEqual(res.interim.length, 1, 'one interim response')
|
||||||
|
assert.strictEqual(res.interim[0].statusCode, 103)
|
||||||
|
assert.match(String(res.interim[0].headers.link), /rel=modulepreload/)
|
||||||
|
assert.match(String(res.headers.link), /rel=modulepreload/, 'Link header repeated on the final response')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('pages stream SSR html with a filtered initialState tail', async () => {
|
||||||
|
const res = await get('/')
|
||||||
|
const text = res.body.toString()
|
||||||
|
assert.strictEqual(res.status, 200)
|
||||||
|
assert.match(text, /<h1>count is 0<\/h1>/, 'server-rendered view')
|
||||||
|
assert.match(text, /<script type="module" src="\/assets\//, 'client entry wired')
|
||||||
|
assert.match(text, /window\.initialState=/, 'state serialized')
|
||||||
|
assert.ok(!/initialState=.*"events"/.test(text), 'internals filtered from state')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('hashed assets are immutable and served precompressed on request', async () => {
|
||||||
|
const chunk = meta.assets.scripts[0]
|
||||||
|
|
||||||
|
const plain = await get(chunk)
|
||||||
|
assert.strictEqual(plain.status, 200)
|
||||||
|
assert.match(plain.headers['content-type'], /javascript/)
|
||||||
|
assert.match(plain.headers['cache-control'], /immutable/)
|
||||||
|
assert.strictEqual(plain.headers['content-encoding'], undefined)
|
||||||
|
|
||||||
|
const br = await get(chunk, { 'accept-encoding': 'br, gzip' })
|
||||||
|
assert.strictEqual(br.headers['content-encoding'], 'br')
|
||||||
|
assert.ok(br.body.length < plain.body.length, 'brotli variant is smaller')
|
||||||
|
|
||||||
|
const gz = await get(chunk, { 'accept-encoding': 'gzip' })
|
||||||
|
assert.strictEqual(gz.headers['content-encoding'], 'gzip')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('the service worker builds with the precache list injected', async () => {
|
||||||
|
const res = await get('/sw.js')
|
||||||
|
assert.strictEqual(res.status, 200)
|
||||||
|
const sw = res.body.toString()
|
||||||
|
assert.ok(!sw.includes('__BANKAI_ASSETS__'), 'define was applied')
|
||||||
|
assert.ok(sw.includes(meta.assets.scripts[0]), 'hashed entry chunk in the precache list')
|
||||||
|
assert.match(sw, /[`"']\/[`"']\s*,/, 'root page precached (any quote style the minifier picks)')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('missing assets 404; extensionless paths fall through to SSR', async () => {
|
||||||
|
const miss = await get('/assets/nope-not-real.js')
|
||||||
|
assert.strictEqual(miss.status, 404)
|
||||||
|
|
||||||
|
const page = await get('/some/page')
|
||||||
|
assert.strictEqual(page.status, 200, 'wildcard route rendered')
|
||||||
|
assert.match(page.body.toString(), /count is 0/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { test } from 'node:test'
|
||||||
|
import assert from 'node:assert'
|
||||||
|
|
||||||
|
import { documentHead, documentTail, serializeState, assetLinks } from '../lib/document.js'
|
||||||
|
|
||||||
|
test('documentHead renders title, css, preloads and module scripts', () => {
|
||||||
|
const head = documentHead({
|
||||||
|
title: 'a < b',
|
||||||
|
css: ['/assets/x.css'],
|
||||||
|
modulepreload: ['/assets/dep.js'],
|
||||||
|
scripts: ['/assets/main.js']
|
||||||
|
})
|
||||||
|
assert.match(head, /<title>a < b<\/title>/)
|
||||||
|
assert.match(head, /<link rel="stylesheet" href="\/assets\/x.css">/)
|
||||||
|
assert.match(head, /<link rel="modulepreload" href="\/assets\/dep.js">/)
|
||||||
|
assert.match(head, /<script type="module" src="\/assets\/main.js"><\/script>/)
|
||||||
|
assert.match(head, /^<!doctype html>/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('serializeState blocks script breakouts and drops recomputed internals', () => {
|
||||||
|
const json = serializeState({
|
||||||
|
events: { RENDER: 'render' },
|
||||||
|
cache: null,
|
||||||
|
prefetch: [],
|
||||||
|
count: 3,
|
||||||
|
evil: '</script><script>alert(1)</script>',
|
||||||
|
nested: { events: 'keep me' }
|
||||||
|
})
|
||||||
|
assert.ok(!json.includes('</script'), 'no closing-script breakout')
|
||||||
|
const parsed = JSON.parse(json.replace(/\\u003c/g, '<'))
|
||||||
|
assert.strictEqual(parsed.count, 3)
|
||||||
|
assert.strictEqual(parsed.events, undefined, 'top-level events dropped')
|
||||||
|
assert.strictEqual(parsed.cache, undefined)
|
||||||
|
assert.strictEqual(parsed.prefetch, undefined)
|
||||||
|
assert.strictEqual(parsed.nested.events, 'keep me', 'only top-level internals dropped')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('documentTail is an inline script plus the html close', () => {
|
||||||
|
const tail = documentTail({ count: 1 })
|
||||||
|
assert.match(tail, /<script>window.initialState=\{"count":1\}<\/script>/)
|
||||||
|
assert.match(tail, /<\/html>/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('assetLinks builds Early Hints link values', () => {
|
||||||
|
const links = assetLinks({
|
||||||
|
scripts: ['/assets/main.js'],
|
||||||
|
modulepreload: ['/assets/dep.js'],
|
||||||
|
css: ['/assets/x.css']
|
||||||
|
})
|
||||||
|
assert.deepStrictEqual(links, [
|
||||||
|
'</assets/main.js>; rel=modulepreload',
|
||||||
|
'</assets/dep.js>; rel=modulepreload',
|
||||||
|
'</assets/x.css>; rel=preload; as=style'
|
||||||
|
])
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user