Skip to content
← Public packages

@kentcdodds/the-last-software-engineer

The Last Software Engineer: Kent C. Dodds's React Summit US 2026 talk deck. Judgment and product engineering in an AI era.

FollowForkOpen app

Files

sw.js

68 lines · 2.3 KB · JavaScript
// Offline support for the hosted deck. On install it caches the page plus every file the page
// uses (fonts and images are separate content-hashed files under a/, listed at build time), so
// the deck works with no network at all after one visit. The worker only activates once every
// file is stored (cache.addAll is all or nothing), so "ready" means "fully offline-capable".
// Pages load network-first (2.5s timeout) so an online visit gets the latest publish; with no
// network the cached page is served at once. Hashed files never change, so they're cache-first.
const VERSION = '__VERSION__'
const CACHE = `last-swe-deck-${VERSION}`
const BASE = new URL('./', self.location).href
const PAGE = BASE
const PRECACHE = '__PRECACHE__'.map((path) => new URL(path, BASE).href)

self.addEventListener('install', (event) => {
	event.waitUntil(
		caches
			.open(CACHE)
			.then((cache) => cache.addAll(PRECACHE.map((url) => new Request(url, { cache: 'reload' }))))
			.then(() => self.skipWaiting()),
	)
})

self.addEventListener('activate', (event) => {
	event.waitUntil(
		caches
			.keys()
			.then((keys) => Promise.all(keys.filter((key) => key.startsWith('last-swe-deck-') && key !== CACHE).map((key) => caches.delete(key))))
			.then(() => self.clients.claim()),
	)
})

const withTimeout = (promise, ms) =>
	new Promise((resolve, reject) => {
		const timer = setTimeout(() => reject(new Error('timeout')), ms)
		promise.then(
			(value) => {
				clearTimeout(timer)
				resolve(value)
			},
			(error) => {
				clearTimeout(timer)
				reject(error)
			},
		)
	})

self.addEventListener('fetch', (event) => {
	const { request } = event
	if (request.method !== 'GET') return
	if (request.mode === 'navigate') {
		// Every path serves the same page, so the page is cached under one key.
		event.respondWith(
			withTimeout(fetch(request), 2500)
				.then(async (response) => {
					if (response.ok) {
						const cache = await caches.open(CACHE)
						await cache.put(PAGE, response.clone())
					}
					return response
				})
				.catch(async () => (await caches.match(PAGE, { cacheName: CACHE })) ?? Response.error()),
		)
		return
	}
	const url = request.url.split('#')[0]
	if (PRECACHE.includes(url)) {
		event.respondWith(caches.match(url, { cacheName: CACHE }).then((hit) => hit ?? fetch(request)))
	}
})