← Public packages
@kentcdodds/starsnake
Starsnake: steer a snake-like ship Asteroids style, grow a crystal tail, and spend crystals on towers to defend your core. Mobile friendly.
Files
import { packageContext } from 'kody:runtime'
import { ASSETS } from './assets.ts'
import { BUILD } from './build-info.ts'
import { manifest, renderPage, type PageCtx } from './page.ts'
const HOST = /^[a-z0-9.-]+(:\d{1,5})?$/i
const FALLBACK_ORIGIN = 'https://starsnake.kentcdodds.com'
/** Public origin for absolute og:image URLs. The runtime may rewrite request.url, so prefer the forwarded/Host header. */
function publicOrigin(request: Request, url: URL) {
const raw = (request.headers.get('x-forwarded-host') || request.headers.get('host') || url.host).split(',')[0]!.trim()
if (!HOST.test(raw)) return FALLBACK_ORIGIN
const local = /^(localhost|127\.|\[::1\])/.test(raw)
return `${local ? 'http' : 'https'}://${raw.toLowerCase()}`
}
function pageCtx(request: Request, url: URL): PageCtx {
const appBase = String(packageContext?.appBase ?? '').replace(/\/+$/, '')
return { origin: publicOrigin(request, url), appBase, assetBase: `${appBase}/a` }
}
function asset(path: string) {
const a = ASSETS[path]
if (!a) return null
const bytes = Uint8Array.from(atob(a.b64), (c) => c.charCodeAt(0))
return new Response(bytes, { headers: { 'content-type': a.type, 'cache-control': 'public, max-age=86400' } })
}
export default {
fetch(request: Request) {
const url = new URL(request.url)
if (request.method !== 'GET' && request.method !== 'HEAD') return new Response('Method not allowed', { status: 405 })
const ctx = pageCtx(request, url)
let path = url.pathname
if (ctx.appBase && path.startsWith(ctx.appBase)) path = path.slice(ctx.appBase.length)
path = path.replace(/\/+$/, '') || '/'
if (path === '/health') return Response.json({ ok: true, service: 'starsnake', build: BUILD.buildId })
if (path === '/manifest.webmanifest') {
return new Response(JSON.stringify(manifest(ctx)), { headers: { 'content-type': 'application/manifest+json', 'cache-control': 'no-cache' } })
}
if (path.startsWith('/a/')) { const r = asset(path.slice(2)); if (r) return r }
if (path === '/') return new Response(renderPage(ctx), { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' } })
return new Response('Not found', { status: 404, headers: { 'content-type': 'text/plain' } })
},
}