cleanup
cleanup reconciles the service worker’s Cache Storage and its IndexedDB
metadata stores. It bounds long-term cache growth and heals any drift between the
cache, the meta store, and the tags index. It is intended to be run from the
service worker’s activate event.
Signature
Section titled “Signature”function cleanup(options: CleanupOptions): Promise<void>;
interface CleanupOptions { /** * Grace period in seconds past a cache entry's `expiresAt` before the * entry is dropped. Entries expired within this window are kept; entries * expired longer than this window are deleted from both the cache and * the meta store. */ maximumStaleAge: number;}maximumStaleAge— how many seconds an entry may remain past itsexpiresAtbefore it is dropped. An entry is deleted only once it has been expired for longer than this window; recently expired entries are kept so they can still serve as an offline fallback.
import { cleanup } from "@toapi/worker";
declare const self: ServiceWorkerGlobalScope;
self.addEventListener("activate", (event) => { // Keep entries for up to 7 days past expiry. event.waitUntil(cleanup({ maximumStaleAge: 60 * 60 * 24 * 7 }));});Wrapping the call in event.waitUntil(...) keeps the worker alive until cleanup
finishes.
Behavior
Section titled “Behavior”cleanup performs three things:
- Drops long-expired entries. It cursors the meta store and deletes every
record whose
expiresAtis older thanmaximumStaleAgeseconds, removing the matching entries from Cache Storage as well. Records with no expiry, or expired within the grace window, are kept. - Drops orphans. Any entry in Cache Storage that has no surviving meta record — for instance, left behind by a write that was interrupted — is deleted.
- Rebuilds the tags index. The tags store is rebuilt from the surviving meta records, healing any drift between the meta store and the tags index.