Skip to content
← Public packages

@kentcdodds/invisible-software

Invisible software: a phone-only step-through demo plus a chart of AI agent benchmark progress.

FollowForkOpen app

app/router.ts

68 lines · 2.4 KB · TypeScript
Raw
import { assets, type Asset } from './assets.generated.ts'

const decoded = new Map<string, Uint8Array<ArrayBuffer>>()

function body(path: string, asset: Asset): BodyInit {
	if (asset.text != null) return asset.text
	let bytes = decoded.get(path)
	if (!bytes) {
		const bin = atob(asset.base64 ?? '')
		bytes = new Uint8Array(bin.length)
		for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
		decoded.set(path, bytes)
	}
	return bytes
}

function respond(path: string, method: string) {
	const asset = assets[path]
	if (!asset) return null
	return new Response(method === 'HEAD' ? null : body(path, asset), {
		headers: {
			'content-type': asset.type,
			'cache-control':
				path.endsWith('.html') ? 'no-cache' : 'public, max-age=3600',
			'x-content-type-options': 'nosniff',
		},
	})
}

/**
 * Kody strips the package mount before forwarding. `/` is the landing page,
 * `/demo` the phone demo (step in the #hash), `/graph` the benchmark chart.
 * Pages only use relative URLs, so they work under any prefix.
 */
export default {
	async fetch(request: Request): Promise<Response> {
		if (request.method !== 'GET' && request.method !== 'HEAD') {
			return new Response('Method not allowed', { status: 405 })
		}
		const { pathname } = new URL(request.url)
		const clipAt = pathname.indexOf('/c/')
		if (clipAt !== -1) {
			const path = 'c/' + decodeURIComponent(pathname.slice(clipAt + 3))
			return (
				respond(path, request.method) ??
				new Response('Not found', { status: 404 })
			)
		}
		// The browser's preload scanner can fetch <img src="assets/..."> before a page's runtime
		// <base href=".../c/"> exists, resolving it beside the page instead; serve those too.
		const bare = pathname.match(/\/((?:assets|fonts|icons)\/.+)$/)
		if (bare) {
			const hit = respond('c/' + decodeURIComponent(bare[1]), request.method)
			if (hit) return hit
		}
		if (pathname.endsWith('/favicon.ico')) {
			return respond('c/icons/favicon.ico', request.method) as Response
		}
		if (pathname.endsWith('/health')) {
			return Response.json({ ok: true })
		}
		const page = pathname.replace(/\/+$/, '')
		if (page === '' ) return respond('home.html', request.method) as Response
		if (page === '/demo') return respond('index.html', request.method) as Response
		if (page === '/graph') return respond('graph.html', request.method) as Response
		return new Response('Not found', { status: 404 })
	},
}