fix(web): review findings on the Worker platform (v4 Phase 2)
- Missing files no longer get the app shell: `not_found_handling: "none"` and worker/spa.ts answer /assets/*, /data/* and file-like misses with a real 404 (no-store). A stale hashed chunk used to get index.html with the year-long immutable cache of /assets/*. Routes get the shell with 200; unknown paths and unknown game slugs get it with 404. - Recharts is off the first load again (~314 -> ~195 KB gzip): drop the vendor-charts group, which captured React and clsx, and give vendor-react the top priority. - Web build target restored (Safari/iOS 15.4): Vite 8's default shipped Radix class static blocks unlowered, a blank page on iOS 15. - The allow-list cache shares only loaded values, never an in-flight promise: a cancelled first /img request hung every later one. - /img answers upstream resets and R2 errors with a 502 instead of an uncaught exception, and releases unused upstream bodies. - Per-route canonical + robots (useSeoHead) instead of a static root canonical and og:url on every page. - Legacy hash redirect: crafted hashes (#//host, #/\host) go home instead of throwing before React mounts. - Chunk-reload guard is time-windowed and storage-safe. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
15 files changed
+401
-74
No files matched your search
@@ -17,13 +17,11 @@
|
||||
<link rel="icon" type="image/svg+xml" href="%BASE_URL%favicon.svg" />
|
||||
<link rel="apple-touch-icon" href="%BASE_URL%icon-192.png" />
|
||||
<link rel="manifest" href="%BASE_URL%manifest.webmanifest" />
|
||||
<link rel="canonical" href="https://freeitchgames.win/" />
|
||||
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="Itch.io Free Games DB" />
|
||||
<meta property="og:title" content="Itch.io Free Games Database" />
|
||||
<meta property="og:description" content="A curated, auto-updating catalog of 2,600+ free games on itch.io. Browse, filter, and analyze." />
|
||||
<meta property="og:url" content="https://freeitchgames.win/" />
|
||||
<meta property="og:image" content="https://freeitchgames.win/og.png" />
|
||||
<meta property="og:image:type" content="image/png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useThemeEffect } from '@/hooks/useThemeEffect'
|
||||
import { useDensityEffect } from '@/hooks/useDensityEffect'
|
||||
import { useBackButton } from '@/hooks/useBackButton'
|
||||
import { useSeoHead } from '@/hooks/useSeoHead'
|
||||
import Dashboard from '@/routes/dashboard'
|
||||
import Games from '@/routes/games'
|
||||
import Deleted from '@/routes/deleted'
|
||||
@@ -49,6 +50,7 @@ export default function App() {
|
||||
useThemeEffect()
|
||||
useDensityEffect()
|
||||
useBackButton()
|
||||
useSeoHead()
|
||||
const mainRef = useRef<HTMLElement>(null)
|
||||
return (
|
||||
<LegalGate>
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useEffect } from 'react'
|
||||
import { matchRoutes, useLocation } from 'react-router'
|
||||
import { SITE_ORIGIN } from '@/lib/config'
|
||||
import { isTauri } from '@/lib/runtime'
|
||||
|
||||
// Pages worth indexing. Keep in sync with the <Routes> in App.tsx (and
|
||||
// worker/spa.ts, which answers unknown paths and game slugs with a 404).
|
||||
const INDEXED = ['/', '/games', '/games/:slug', '/charts', '/deleted', '/about', '/suggest'].map((path) => ({
|
||||
path,
|
||||
}))
|
||||
|
||||
function headTag<T extends HTMLElement>(selector: string, create: () => T): T {
|
||||
return document.head.querySelector<T>(selector) ?? document.head.appendChild(create())
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-route canonical URL and robots directive (web only). index.html ships
|
||||
* no static canonical on purpose: every route is served the same file, and a
|
||||
* static root canonical would mark each game page a duplicate of the home
|
||||
* page. Runs in App() outside the legal gate, so crawlers get it too.
|
||||
*/
|
||||
export function useSeoHead(): void {
|
||||
const { pathname } = useLocation()
|
||||
useEffect(() => {
|
||||
if (isTauri()) return
|
||||
const path = pathname.length > 1 ? pathname.replace(/\/+$/, '') : '/'
|
||||
const canonical = headTag('link[rel="canonical"]', () => {
|
||||
const link = document.createElement('link')
|
||||
link.rel = 'canonical'
|
||||
return link
|
||||
})
|
||||
canonical.href = SITE_ORIGIN + path
|
||||
const robots = headTag('meta[name="robots"]', () => {
|
||||
const meta = document.createElement('meta')
|
||||
meta.name = 'robots'
|
||||
return meta
|
||||
})
|
||||
robots.content = matchRoutes(INDEXED, path) ? 'index,follow' : 'noindex'
|
||||
}, [pathname])
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { isTauri } from './runtime'
|
||||
|
||||
const SITE_ORIGIN = 'https://freeitchgames.win'
|
||||
export const SITE_ORIGIN = 'https://freeitchgames.win'
|
||||
|
||||
// The catalog JSON is bundled into the site at build time (vite.config.ts →
|
||||
// catalogData → dist/data/). The web app reads it same-origin; the Tauri apps
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { legacyHashTarget } from './legacy'
|
||||
|
||||
const ORIGIN = 'https://freeitchgames.win'
|
||||
|
||||
describe('legacyHashTarget', () => {
|
||||
it.each([
|
||||
['#/games/dev-itch-io-x', `${ORIGIN}/games/dev-itch-io-x`],
|
||||
['#/games?q=vn&page=2', `${ORIGIN}/games?q=vn&page=2`],
|
||||
['#/about#licenses', `${ORIGIN}/about#licenses`],
|
||||
['#/add', '/'],
|
||||
['#/workflows', '/'],
|
||||
])('rewrites %s', (hash, expected) => {
|
||||
expect(legacyHashTarget(hash, ORIGIN)).toBe(expected)
|
||||
})
|
||||
|
||||
it.each(['#//evil.com/x', '#/\\evil.com', '#//[', '#/.//evil.com'])(
|
||||
'sends crafted hash %s home instead of to another origin',
|
||||
(hash) => {
|
||||
const target = legacyHashTarget(hash, ORIGIN)
|
||||
expect(target === '/' || new URL(target!, ORIGIN).origin === ORIGIN).toBe(true)
|
||||
expect(new URL(target!, ORIGIN).pathname.startsWith('//')).toBe(false)
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['', '#', '#section', '#!/x'])('leaves other hashes alone (%s)', (hash) => {
|
||||
expect(legacyHashTarget(hash, ORIGIN)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -25,14 +25,38 @@ export function clearLegacyCredentials(): void {
|
||||
// Routes that existed in v3 but are gone from the public app.
|
||||
const RETIRED_ROUTES = new Set(['/add', '/workflows'])
|
||||
|
||||
/**
|
||||
* Where a v3 hash link (`#/games/x`) should land, or null for other hashes.
|
||||
* A crafted hash that resolves to another origin (`#//host`, `#/\host`) or
|
||||
* does not parse goes to the home page.
|
||||
*/
|
||||
export function legacyHashTarget(hash: string, origin: string): string | null {
|
||||
if (!hash.startsWith('#/')) return null
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(hash.slice(1), origin)
|
||||
} catch {
|
||||
return '/'
|
||||
}
|
||||
// '#/.//evil.com' normalizes to the pathname '//evil.com': same origin, but
|
||||
// no page of ours, and replaceState would read it as another host.
|
||||
if (url.origin !== origin || url.pathname.startsWith('//') || RETIRED_ROUTES.has(url.pathname)) {
|
||||
return '/'
|
||||
}
|
||||
return url.href
|
||||
}
|
||||
|
||||
/**
|
||||
* v3 used hash routing (`/#/games/x`). Rewrite such links to real paths
|
||||
* before the router mounts, so shared links and bookmarks keep working.
|
||||
*/
|
||||
export function redirectLegacyHashRoute(): void {
|
||||
const { hash } = window.location
|
||||
if (!hash.startsWith('#/')) return
|
||||
const target = hash.slice(1)
|
||||
const pathname = target.split(/[?#]/)[0]
|
||||
window.history.replaceState(null, '', RETIRED_ROUTES.has(pathname) ? '/' : target)
|
||||
const target = legacyHashTarget(window.location.hash, window.location.origin)
|
||||
if (target === null) return
|
||||
try {
|
||||
window.history.replaceState(null, '', target)
|
||||
} catch {
|
||||
// Never let a bad link keep the app from mounting.
|
||||
window.history.replaceState(null, '', '/')
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -51,10 +51,19 @@ clearLegacyCredentials()
|
||||
if (!isTauri()) redirectLegacyHashRoute()
|
||||
|
||||
// A deploy replaces hashed chunk files; a tab opened before it would fail to
|
||||
// lazy-load a route. Reload once to pick up the new build.
|
||||
// lazy-load a route. Reload to pick up the new build — at most once per 30 s,
|
||||
// so a chunk that still fails after the reload shows the error page (with its
|
||||
// Reload button) instead of looping. Without storage there is no loop guard,
|
||||
// so no automatic reload either.
|
||||
const RELOAD_KEY = 'reloaded-after-deploy'
|
||||
window.addEventListener('vite:preloadError', (event) => {
|
||||
if (sessionStorage.getItem('reloaded-after-deploy')) return
|
||||
sessionStorage.setItem('reloaded-after-deploy', '1')
|
||||
try {
|
||||
const last = Number(sessionStorage.getItem(RELOAD_KEY)) || 0
|
||||
if (Date.now() - last < 30_000) return
|
||||
sessionStorage.setItem(RELOAD_KEY, String(Date.now()))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
window.location.reload()
|
||||
})
|
||||
|
||||
+15
-7
@@ -17,24 +17,32 @@ export default defineConfig({
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
sourcemap: false,
|
||||
// Web floor: Safari/iOS 15.4 (iPhone 6s/7/SE1 stop at iOS 15.8). Vite 8's
|
||||
// default (Safari 16.4) would ship Radix's class static blocks unlowered:
|
||||
// a SyntaxError, i.e. a blank page, on older iOS. Tauri keeps the default
|
||||
// (the macOS app documents Safari 16.4+).
|
||||
target: isTauri ? 'baseline-widely-available' : ['chrome111', 'edge111', 'firefox114', 'safari15.4', 'ios15.4'],
|
||||
chunkSizeWarningLimit: 600,
|
||||
rolldownOptions: {
|
||||
output: {
|
||||
codeSplitting: {
|
||||
// Higher priority wins when a module matches several groups.
|
||||
// Higher priority wins when a module matches several groups. Groups
|
||||
// also pull in their dependencies, so React must be claimed first.
|
||||
// No vendor-charts group: it would capture shared deps (React, clsx)
|
||||
// and put Recharts on the first load. Recharts is only reached from
|
||||
// the lazy chart tabs, so default splitting keeps it lazy.
|
||||
groups: [
|
||||
{ name: 'vendor-charts', test: /node_modules[\\/](recharts|d3-|victory-vendor)/, priority: 50 },
|
||||
{
|
||||
name: 'vendor-react',
|
||||
test: /node_modules[\\/](react|react-dom|react-router|react-router-dom|scheduler)[\\/]/,
|
||||
priority: 100,
|
||||
},
|
||||
{ name: 'vendor-query', test: /node_modules[\\/]@tanstack[\\/]/, priority: 40 },
|
||||
{
|
||||
name: 'vendor-ui',
|
||||
test: /node_modules[\\/](@radix-ui|lucide-react|sonner)[\\/]/,
|
||||
priority: 30,
|
||||
},
|
||||
{
|
||||
name: 'vendor-react',
|
||||
test: /node_modules[\\/](react|react-dom|react-router|react-router-dom|scheduler)[\\/]/,
|
||||
priority: 20,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Catalog facts the Worker needs, read from the site's own static assets
|
||||
* (the build bundles them under /data, see vite-plugins/catalog-data.ts).
|
||||
* Cached per isolate: every deploy starts fresh isolates, and a deploy is
|
||||
* the only way these files change.
|
||||
*/
|
||||
|
||||
export interface DataSource {
|
||||
assets: Pick<Fetcher, 'fetch'>
|
||||
origin: string
|
||||
}
|
||||
|
||||
let urlMap: Map<string, string> | undefined
|
||||
|
||||
export function resetDataCache(): void {
|
||||
urlMap = undefined
|
||||
}
|
||||
|
||||
async function fetchJson<T>(src: DataSource, file: string): Promise<T> {
|
||||
const res = await src.assets.fetch(new Request(`${src.origin}/data/${file}`))
|
||||
if (!res.ok) throw new Error(`${file}: ${res.status}`)
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
/**
|
||||
* Only the loaded value is shared, never an in-flight promise: a pending
|
||||
* subrequest belongs to the request that started it, and if that request is
|
||||
* cancelled (client disconnect) the promise never settles — every other
|
||||
* request awaiting it would hang. Concurrent cold requests each load; a
|
||||
* failure is not cached, so the next request retries.
|
||||
*/
|
||||
async function cachedLoad<T>(get: () => T | undefined, set: (v: T) => void, load: () => Promise<T>): Promise<T> {
|
||||
const hit = get()
|
||||
if (hit !== undefined) return hit
|
||||
const value = await load()
|
||||
set(value)
|
||||
return value
|
||||
}
|
||||
|
||||
/** Catalog game URL → thumbnail URL. */
|
||||
export function catalogUrls(src: DataSource): Promise<Map<string, string>> {
|
||||
return cachedLoad(
|
||||
() => urlMap,
|
||||
(v) => (urlMap = v),
|
||||
async () => new Map(Object.entries(await fetchJson<Record<string, string>>(src, 'urls.json'))),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { handleImg, parseImgPath, r2Key, resetAllowList, type ImgDeps } from './img'
|
||||
import { resetDataCache } from './data'
|
||||
import { handleImg, parseImgPath, r2Key, type ImgDeps } from './img'
|
||||
|
||||
const ORIGIN = 'https://freeitchgames.win'
|
||||
const PATH = 'aW1nLzI0OTQ3OTQzLnBuZw==/original/3wlrR0.png'
|
||||
@@ -33,7 +34,7 @@ function get(path: string, headers: Record<string, string> = {}) {
|
||||
return { request: new Request(url, { headers }), url }
|
||||
}
|
||||
|
||||
beforeEach(() => resetAllowList())
|
||||
beforeEach(() => resetDataCache())
|
||||
|
||||
describe('parseImgPath', () => {
|
||||
it('accepts catalog-shaped paths and keeps encoding', () => {
|
||||
@@ -139,6 +140,26 @@ describe('handleImg', () => {
|
||||
expect((await handleImg(req.request, req.url, b.deps)).status).toBe(502)
|
||||
})
|
||||
|
||||
it('answers upstream network errors with a 502 instead of throwing', async () => {
|
||||
const reset = vi.fn().mockRejectedValue(new TypeError('Network connection lost.'))
|
||||
const { deps } = makeDeps({ fetch: reset as unknown as typeof fetch })
|
||||
const req = get(`/img/160/${PATH}`)
|
||||
const res = await handleImg(req.request, req.url, deps)
|
||||
expect(res.status).toBe(502)
|
||||
expect(res.headers.get('cache-control')).toBe('no-store')
|
||||
})
|
||||
|
||||
it('does not let a stalled first request block the others', async () => {
|
||||
const assetsFetch = vi
|
||||
.fn()
|
||||
.mockReturnValueOnce(new Promise(() => {})) // e.g. its request was cancelled
|
||||
.mockResolvedValue(Response.json({ u: UPSTREAM }))
|
||||
const { deps } = makeDeps({ assets: { fetch: assetsFetch } as unknown as ImgDeps['assets'] })
|
||||
const req = get(`/img/160/${PATH}`)
|
||||
void handleImg(req.request, req.url, deps)
|
||||
expect((await handleImg(req.request, req.url, deps)).status).toBe(200)
|
||||
})
|
||||
|
||||
it('returns 503 when the allow-list is unavailable and retries later', async () => {
|
||||
const assetsFetch = vi
|
||||
.fn()
|
||||
|
||||
+53
-48
@@ -12,6 +12,7 @@
|
||||
* widths exist. When a transform fails (quota error 9422, bad source) the
|
||||
* original is streamed through with a short cache instead of being stored.
|
||||
*/
|
||||
import { catalogUrls } from './data'
|
||||
import { SECURITY_HEADERS } from './http'
|
||||
|
||||
const ITCH_IMG = 'https://img.itch.zone/'
|
||||
@@ -53,26 +54,15 @@ export async function r2Key(width: number, upstream: string): Promise<string> {
|
||||
return `w${width}/${hex}.webp`
|
||||
}
|
||||
|
||||
// Catalog thumbnails, loaded once per isolate from the static assets.
|
||||
let allowList: Promise<Set<string>> | undefined
|
||||
|
||||
export function resetAllowList(): void {
|
||||
allowList = undefined
|
||||
}
|
||||
|
||||
function loadAllowList(assets: ImgDeps['assets'], origin: string): Promise<Set<string>> {
|
||||
allowList ??= assets
|
||||
.fetch(new Request(`${origin}/data/urls.json`))
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(`urls.json: ${res.status}`)
|
||||
return res.json() as Promise<Record<string, string>>
|
||||
})
|
||||
.then((urls) => new Set(Object.values(urls)))
|
||||
.catch((e: unknown) => {
|
||||
allowList = undefined // retry on the next request
|
||||
throw e
|
||||
})
|
||||
return allowList
|
||||
// Set of catalog thumbnail URLs, derived once per loaded map.
|
||||
const thumbSets = new WeakMap<Map<string, string>, Set<string>>()
|
||||
function thumbnailSet(urls: Map<string, string>): Set<string> {
|
||||
let set = thumbSets.get(urls)
|
||||
if (!set) {
|
||||
set = new Set(urls.values())
|
||||
thumbSets.set(urls, set)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
function imageResponse(body: BodyInit | null, type: string, cacheControl: string): Response {
|
||||
@@ -99,43 +89,58 @@ export async function handleImg(request: Request, url: URL, deps: ImgDeps): Prom
|
||||
if (!parsed) return plain(400)
|
||||
const { width, upstream } = parsed
|
||||
|
||||
let allowed: Set<string>
|
||||
let thumbnails: Set<string>
|
||||
try {
|
||||
allowed = await loadAllowList(deps.assets, url.origin)
|
||||
const urls = await catalogUrls({ assets: deps.assets, origin: url.origin })
|
||||
thumbnails = thumbnailSet(urls)
|
||||
} catch {
|
||||
return plain(503, 'no-store')
|
||||
}
|
||||
if (!allowed.has(upstream)) return plain(404)
|
||||
if (!thumbnails.has(upstream)) return plain(404)
|
||||
|
||||
const cacheKey = new Request(`${url.origin}${url.pathname}`)
|
||||
const cached = await deps.cache?.match(cacheKey)
|
||||
if (cached) return cached
|
||||
|
||||
const key = await r2Key(width, upstream)
|
||||
const stored = await deps.bucket.get(key)
|
||||
if (stored) {
|
||||
const res = imageResponse(stored.body, 'image/webp', YEAR)
|
||||
if (deps.cache) deps.waitUntil(deps.cache.put(cacheKey, res.clone()))
|
||||
return res
|
||||
}
|
||||
// Upstream resets and R2 errors reject: answer with a controlled 502, not
|
||||
// an uncaught exception (Cloudflare error 1101).
|
||||
try {
|
||||
const key = await r2Key(width, upstream)
|
||||
const stored = await deps.bucket.get(key)
|
||||
if (stored) {
|
||||
const res = imageResponse(stored.body, 'image/webp', YEAR)
|
||||
if (deps.cache) deps.waitUntil(deps.cache.put(cacheKey, res.clone()))
|
||||
return res
|
||||
}
|
||||
|
||||
const transformed = await deps.fetch(upstream, {
|
||||
cf: { image: { width, fit: 'scale-down', format: 'webp', quality: 78, anim: false } },
|
||||
} as RequestInit)
|
||||
if (transformed.ok && transformed.headers.get('content-type') === 'image/webp') {
|
||||
const bytes = await transformed.arrayBuffer()
|
||||
const res = imageResponse(bytes, 'image/webp', YEAR)
|
||||
deps.waitUntil(deps.bucket.put(key, bytes, { httpMetadata: { contentType: 'image/webp' } }))
|
||||
if (deps.cache) deps.waitUntil(deps.cache.put(cacheKey, res.clone()))
|
||||
return res
|
||||
}
|
||||
const transformed = await deps.fetch(upstream, {
|
||||
cf: { image: { width, fit: 'scale-down', format: 'webp', quality: 78, anim: false } },
|
||||
} as RequestInit)
|
||||
if (transformed.ok && transformed.headers.get('content-type') === 'image/webp') {
|
||||
const bytes = await transformed.arrayBuffer()
|
||||
const res = imageResponse(bytes, 'image/webp', YEAR)
|
||||
deps.waitUntil(deps.bucket.put(key, bytes, { httpMetadata: { contentType: 'image/webp' } }))
|
||||
if (deps.cache) deps.waitUntil(deps.cache.put(cacheKey, res.clone()))
|
||||
return res
|
||||
}
|
||||
discard(transformed)
|
||||
|
||||
// Transformation unavailable (quota 9422, unsupported source…): stream the
|
||||
// original, cache it briefly at the edge, do not store it.
|
||||
const original = await deps.fetch(upstream, { cf: { cacheEverything: true, cacheTtl: 86400 } } as RequestInit)
|
||||
// itch.zone answers 403 for some broken originals: treat like a missing image.
|
||||
if ([403, 404, 410].includes(original.status)) return plain(404, DAY)
|
||||
const type = original.headers.get('content-type') ?? ''
|
||||
if (!original.ok || !type.startsWith('image/') || type.includes('svg')) return plain(502, 'no-store')
|
||||
return imageResponse(request.method === 'HEAD' ? null : original.body, type, DAY)
|
||||
// Transformation unavailable (quota 9422, unsupported source…): stream the
|
||||
// original, cache it briefly at the edge, do not store it.
|
||||
const original = await deps.fetch(upstream, { cf: { cacheEverything: true, cacheTtl: 86400 } } as RequestInit)
|
||||
const type = original.headers.get('content-type') ?? ''
|
||||
const usable = original.ok && type.startsWith('image/') && !type.includes('svg')
|
||||
if (!usable || request.method === 'HEAD') discard(original)
|
||||
// itch.zone answers 403 for some broken originals: treat like a missing image.
|
||||
if ([403, 404, 410].includes(original.status)) return plain(404, DAY)
|
||||
if (!usable) return plain(502, 'no-store')
|
||||
return imageResponse(request.method === 'HEAD' ? null : original.body, type, DAY)
|
||||
} catch {
|
||||
return plain(502, 'no-store')
|
||||
}
|
||||
}
|
||||
|
||||
/** Release the connection of a response whose body is not used. */
|
||||
function discard(res: Response): void {
|
||||
res.body?.cancel().catch(() => {})
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
/**
|
||||
* Worker for freeitchgames.win. Static assets (the app and /data/*) are served
|
||||
* by the assets layer without invoking this script; only the paths listed in
|
||||
* wrangler.jsonc `assets.run_worker_first` reach it.
|
||||
* Worker for freeitchgames.win. Existing static assets (the app, /data/*) are
|
||||
* served by the assets layer without invoking this script. It runs for the
|
||||
* paths in wrangler.jsonc `assets.run_worker_first`, and for every request
|
||||
* that matches no asset (`not_found_handling: "none"`, see spa.ts).
|
||||
*/
|
||||
import { handleImg } from './img'
|
||||
import { json } from './http'
|
||||
import { handleMiss } from './spa'
|
||||
|
||||
export default {
|
||||
async fetch(request, env, ctx): Promise<Response> {
|
||||
@@ -23,6 +25,6 @@ export default {
|
||||
if (url.pathname === '/api/health') return json({ ok: true })
|
||||
if (url.pathname.startsWith('/api/')) return json({ error: 'not_found' }, 404)
|
||||
|
||||
return env.ASSETS.fetch(request)
|
||||
return handleMiss(request, url, env.ASSETS)
|
||||
},
|
||||
} satisfies ExportedHandler<Env>
|
||||
@@ -0,0 +1,66 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { resetDataCache } from './data'
|
||||
import { handleMiss } from './spa'
|
||||
|
||||
const ORIGIN = 'https://freeitchgames.win'
|
||||
const SHELL = '<!doctype html><div id="root"></div>'
|
||||
|
||||
function assets(urls: Record<string, string> | 'down' = { 'https://dev.itch.io/cookies': 'https://img.itch.zone/a/b/c.png' }) {
|
||||
return {
|
||||
fetch: vi.fn(async (req: Request) => {
|
||||
const { pathname } = new URL(req.url)
|
||||
if (pathname === '/') return new Response(SHELL, { headers: { 'content-type': 'text/html' } })
|
||||
if (pathname === '/data/urls.json') {
|
||||
return urls === 'down' ? new Response(null, { status: 500 }) : Response.json(urls)
|
||||
}
|
||||
return new Response(null, { status: 404 })
|
||||
}),
|
||||
} as unknown as Fetcher
|
||||
}
|
||||
|
||||
async function miss(path: string, init: RequestInit = {}, binding = assets()) {
|
||||
const url = new URL(path, ORIGIN)
|
||||
return handleMiss(new Request(url, init), url, binding)
|
||||
}
|
||||
|
||||
beforeEach(() => resetDataCache())
|
||||
|
||||
describe('handleMiss', () => {
|
||||
it.each(['/assets/charts-OLDHASH.js', '/data/game_info_999.json', '/nope.png', '/games/x.json'])(
|
||||
'answers a missing file %s with a real 404, never the app shell',
|
||||
async (path) => {
|
||||
const res = await miss(path)
|
||||
expect(res.status).toBe(404)
|
||||
expect(res.headers.get('content-type')).toContain('application/json')
|
||||
expect(res.headers.get('cache-control')).toBe('no-store')
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps CORS on /data misses for the desktop and Android apps', async () => {
|
||||
const res = await miss('/data/nope.json')
|
||||
expect(res.headers.get('access-control-allow-origin')).toBe('*')
|
||||
})
|
||||
|
||||
it.each(['/', '/games', '/games/', '/charts', '/about', '/errors/404', '/games/dev-itch-io-cookies'])(
|
||||
'serves the app shell for route %s',
|
||||
async (path) => {
|
||||
const res = await miss(path)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe(SHELL)
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['/unknown', '/games/not-in-catalog', '/add'])('serves the shell with 404 for %s', async (path) => {
|
||||
const res = await miss(path)
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.text()).toBe(SHELL)
|
||||
})
|
||||
|
||||
it('does not turn game pages into 404s when the catalog cannot be read', async () => {
|
||||
expect((await miss('/games/whatever', {}, assets('down'))).status).toBe(200)
|
||||
})
|
||||
|
||||
it('rejects other methods', async () => {
|
||||
expect((await miss('/games', { method: 'POST' })).status).toBe(405)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Requests that match no static asset (wrangler.jsonc `not_found_handling:
|
||||
* "none"` sends them here).
|
||||
*
|
||||
* - Anything that looks like a file (under /assets/ or /data/, or with an
|
||||
* extension) is a real 404 — never the app shell, which the browser would
|
||||
* otherwise cache under a hashed chunk URL or try to parse as JSON.
|
||||
* - App routes get the shell (index.html) with 200; unknown paths and game
|
||||
* slugs that are not in the catalog get the same shell with 404, so the SPA
|
||||
* still renders its Not Found page but crawlers see a real 404.
|
||||
*/
|
||||
import { catalogUrls, type DataSource } from './data'
|
||||
import { json } from './http'
|
||||
|
||||
// Keep in sync with the <Routes> in src/App.tsx.
|
||||
const ROUTES = new Set(['/', '/games', '/charts', '/deleted', '/settings', '/about', '/suggest'])
|
||||
const GAME_ROUTE = /^\/games\/([a-z0-9-]+)$/
|
||||
const ERROR_PREVIEW_ROUTE = /^\/errors\/[a-z0-9-]+$/
|
||||
|
||||
// Keep in sync with slugify() in src/lib/utils.ts.
|
||||
function slugify(url: string): string {
|
||||
return url
|
||||
.replace(/^https?:\/\//, '')
|
||||
.replace(/[^a-z0-9-]/gi, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
const slugSets = new WeakMap<Map<string, string>, Set<string>>()
|
||||
|
||||
async function isGameSlug(slug: string, src: DataSource): Promise<boolean> {
|
||||
let urls: Map<string, string>
|
||||
try {
|
||||
urls = await catalogUrls(src)
|
||||
} catch {
|
||||
return true // catalog unavailable: don't turn real pages into 404s
|
||||
}
|
||||
let slugs = slugSets.get(urls)
|
||||
if (!slugs) {
|
||||
slugs = new Set([...urls.keys()].map(slugify))
|
||||
slugSets.set(urls, slugs)
|
||||
}
|
||||
return slugs.has(slug)
|
||||
}
|
||||
|
||||
async function isAppRoute(pathname: string, src: DataSource): Promise<boolean> {
|
||||
const path = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname
|
||||
if (ROUTES.has(path) || ERROR_PREVIEW_ROUTE.test(path)) return true
|
||||
const game = GAME_ROUTE.exec(path)
|
||||
return game !== null && (await isGameSlug(game[1], src))
|
||||
}
|
||||
|
||||
export async function handleMiss(request: Request, url: URL, assets: Fetcher): Promise<Response> {
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
||||
return json({ error: 'method_not_allowed' }, 405, { Allow: 'GET, HEAD' })
|
||||
}
|
||||
const last = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)
|
||||
if (/^\/(assets|data)\//.test(url.pathname) || last.includes('.')) {
|
||||
// CORS on /data misses too, so the desktop/Android apps see a 404, not a CORS error.
|
||||
const cors = url.pathname.startsWith('/data/') ? { 'Access-Control-Allow-Origin': '*' } : undefined
|
||||
return json({ error: 'not_found' }, 404, cors)
|
||||
}
|
||||
// "/" rather than "/index.html": auto-trailing-slash would redirect the latter.
|
||||
const shell = await assets.fetch(new Request(new URL('/', url), request))
|
||||
if (shell.status !== 200 || (await isAppRoute(url.pathname, { assets, origin: url.origin }))) {
|
||||
return shell
|
||||
}
|
||||
return new Response(shell.body, { status: 404, headers: shell.headers })
|
||||
}
|
||||
@@ -16,9 +16,14 @@
|
||||
// Vite build output (app + bundled catalog under /data). Never a source dir.
|
||||
"directory": "./dist",
|
||||
"binding": "ASSETS",
|
||||
"not_found_handling": "single-page-application",
|
||||
// Misses go to the Worker, not to an asset-layer SPA fallback: that would
|
||||
// answer a stale hashed chunk (/assets/x-OLD.js after a deploy) with
|
||||
// index.html + the year-long immutable cache of /assets/*. The Worker
|
||||
// returns real 404s for files and serves the app shell for routes
|
||||
// (worker/spa.ts).
|
||||
"not_found_handling": "none",
|
||||
"html_handling": "auto-trailing-slash",
|
||||
// Everything else is served straight from static assets (free, cached).
|
||||
// Existing assets never invoke the Worker (free, cached); these paths always do.
|
||||
"run_worker_first": ["/img/*", "/api/*"]
|
||||
},
|
||||
// Resized cover images, written once per image + width by worker/img.ts.
|
||||
|
||||
Reference in new issue
Block a user