import { assets, slideCount, type Asset } from './assets.generated.ts'
function body(asset: Asset): BodyInit {
if (asset.text != null) return asset.text
const bin = atob(asset.base64 ?? '')
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return bytes
}
// Hashed files (c/
/..) never change: cache them for a year.
const immutable = (path: string) => path.startsWith('c/')
function respond(path: string, method: string, status = 200) {
const asset = assets[path]!
const headers: Record = {
'content-type': asset.type,
'cache-control': immutable(path) ? 'public, max-age=31536000, immutable' : path === 'index.html' || path === 'sw.js' || path === 'manifest.webmanifest' ? 'no-cache' : 'public, max-age=3600',
'x-content-type-options': 'nosniff',
}
// Kody strips the package mount, so the page can be opened as / or //. The worker
// lives at //sw.js and registers with scope / to cover both; allow that here.
if (path === 'sw.js') headers['service-worker-allowed'] = '/'
// The service worker only trusts (and caches as the deck) a page carrying this header, so a captive
// portal, a platform error page or any other document can never replace the cached deck.
if (path === 'index.html') headers['x-invisible-software-deck'] = '1'
return new Response(method === 'HEAD' ? null : body(asset), { status, headers })
}
/**
* The app serves the deck page (index.html) for every path, its content-hashed fonts, images and
* phone demo under c/ (immutable), a favicon, /health and the PWA files (service worker, manifest,
* icons) that let the hosted deck work offline after one visit. Kody strips the package mount before
* forwarding; nothing here depends on the prefix (the page's asset URLs are relative).
*/
export default {
async fetch(request: Request): Promise {
if (request.method !== 'GET' && request.method !== 'HEAD') {
return new Response('Method not allowed', { status: 405 })
}
const { pathname } = new URL(request.url)
if (pathname.endsWith('/favicon.ico')) return respond('favicon.ico', request.method)
for (const file of ['sw.js', 'manifest.webmanifest', 'icon-192.png', 'icon-512.png']) {
if (pathname.endsWith(`/${file}`)) return respond(file, request.method)
}
// Content-hashed fonts, images and the phone demo, referenced relative to the page.
const at = pathname.indexOf('/c/')
if (at !== -1) {
const key = pathname.slice(at + 1)
if (key in assets) return respond(key, request.method)
return new Response('Not found', { status: 404 })
}
if (pathname.endsWith('/health')) return Response.json({ ok: true, slides: slideCount })
return respond('index.html', request.method)
},
}