Files
clean-architecture-frontend…/src/contracts/service-worker.ts
T
DongHyeonkaandClaude Opus 5.5 f2e14af0a8 fix(service-worker): report a drain timeout as CLIENT_DRAIN_TIMEOUT (06-07)
The worker sent ACTIVATE_REJECTED for a client refusal, a drain timeout and a
failed skipWaiting() alike, so the page blamed a dirty tab. Two worker reply
kinds now carry the timeout and the commit failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 00:36:28 +09:00

182 lines
6.0 KiB
TypeScript

/**
* §17–§18. Service Worker contract.
*
* One physical registration per scope covers PWA lifecycle, verified static
* asset fetch, Web Push and the optional sync wake-up. A separate registration
* for any of those is prohibited.
*/
export const SERVICE_WORKER_PROTOCOL_VERSION = 1 as const;
export const SERVICE_WORKER_CACHE_SCHEMA_VERSION = 1 as const;
export const SERVICE_WORKER_SCRIPT_PATH = "service-worker.js" as const;
export const SERVICE_WORKER_BOUNDS = Object.freeze({
assets: 256,
singleAssetBytes: 2 * 1024 * 1024,
assetSetBytes: 5 * 1024 * 1024,
fetchConcurrency: 4,
installDeadlineMs: 60_000,
clientDrainMs: 30_000,
/**
* Q-6.6-10b. The page waits the worker's whole drain window plus this, so
* a drain that ends just in time is followed by skipWaiting() and the reply.
*/
activationReplySlackMs: 5_000,
updateCheckIntervalMs: 6 * 60 * 60 * 1_000,
retainedPreviousCaches: 1,
reloadGuardBytes: 512,
reloadGuardTtlMs: 10 * 60 * 1_000,
});
export type ServiceWorkerHandlerId =
| "WEB_PUSH"
| "PWA_STATIC_ASSETS"
| "OFFLINE_SYNC_WAKEUP";
/**
* §17.3. Removal is staged. `ACTIVE` never transitions directly to `null`:
* a registration that already exists in a browser must first be unregistered,
* then have its owned resources purged, before the source may disappear.
*/
export type InstalledServiceWorkerSelection =
| Readonly<{
mode: "ACTIVE";
scriptPath: typeof SERVICE_WORKER_SCRIPT_PATH;
handlers: readonly ServiceWorkerHandlerId[];
}>
| Readonly<{
mode: "REMOVE_REGISTRATION";
scriptPath: typeof SERVICE_WORKER_SCRIPT_PATH;
}>
| Readonly<{
mode: "PURGE_OWNED_RESOURCES";
scriptPath: typeof SERVICE_WORKER_SCRIPT_PATH;
}>;
/** §17.7. Page and worker read the same compile-time identity tuple. */
export type ServiceWorkerProtocolIdentity = Readonly<{
serviceWorkerProtocolVersion: typeof SERVICE_WORKER_PROTOCOL_VERSION;
cacheSchemaVersion: typeof SERVICE_WORKER_CACHE_SCHEMA_VERSION;
buildId: string;
releaseId: string;
contractSetDigest: string;
staticAssetSetDigest: string;
}>;
export type ServiceWorkerMessageKind =
| "PAGE_HELLO"
| "WORKER_HELLO_ACK"
| "UPDATE_READY"
| "ACTIVATE_REQUEST"
| "ACTIVATE_ACCEPTED"
| "ACTIVATE_REJECTED"
/**
* 06-07. Worker replies that are not a client's refusal. A page of an older
* build does not know them and ends at its own CLIENT_DRAIN_TIMEOUT.
*/
| "ACTIVATE_DRAIN_TIMEOUT"
| "ACTIVATE_COMMIT_FAILED"
| "CLIENT_DRAIN_REQUEST"
| "CLIENT_DRAINED"
| "ACTIVATED_RELOAD_REQUIRED"
| "CACHE_RESET_REQUEST"
| "CACHE_RESET_RESULT"
| "SYNC_WAKE_OBSERVED";
export type ServiceWorkerMessage = Readonly<{
protocolVersion: typeof SERVICE_WORKER_PROTOCOL_VERSION;
kind: ServiceWorkerMessageKind;
messageId: string;
sourceBuildId: string;
targetBuildId?: string;
nonce?: string;
/** Present only on a successful CACHE_RESET_RESULT. */
cachesDeleted?: number;
}>;
/** §18.3. Compile-time asset manifest; the worker never fetches one. */
export interface StaticAssetManifestV1 {
readonly schemaVersion: 1;
readonly buildId: string;
readonly releaseId: string;
readonly setDigest: `sha256:${string}`;
readonly assets: readonly Readonly<{
url: string;
sha256: `sha256:${string}`;
bytes: number;
contentType: string;
}>[];
}
/**
* Vite's content-hashed file name (`name-<hash>.ext`). Only these are
* immutable: the build generator lists nothing else, and the worker answers
* from a previous release cache only for these (D-7).
*/
export const HASHED_STATIC_ASSET_NAME = /-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/;
/** §18.2. `ca-static-v1-<first 16 lower-hex of staticAssetSetDigest>`. */
export const STATIC_CACHE_PREFIX = "ca-static-v1-" as const;
export function staticCacheName(setDigest: string): string {
const hex = setDigest.replace(/^sha256:/, "").slice(0, 16);
if (!/^[0-9a-f]{16}$/.test(hex)) {
throw new TypeError("Static asset set digest is invalid.");
}
return `${STATIC_CACHE_PREFIX}${hex}`;
}
export function isOwnedStaticCacheName(name: string): boolean {
return (
name.startsWith(STATIC_CACHE_PREFIX) &&
/^[0-9a-f]{16}$/.test(name.slice(STATIC_CACHE_PREFIX.length))
);
}
export type ServiceWorkerStartOutcome =
| Readonly<{ kind: "ACTIVE"; buildId: string }>
| Readonly<{ kind: "RELOAD_TO_ENABLE" }>
| Readonly<{ kind: "UPDATE_WAITING" }>
| Readonly<{ kind: "DISABLED" }>
| Readonly<{ kind: "INCOMPATIBLE" }>
| Readonly<{ kind: "FAILED"; code: string }>;
export type ServiceWorkerActivationOutcome =
| Readonly<{ kind: "ACTIVATED_RELOAD_REQUIRED" }>
| Readonly<{ kind: "BLOCKED_DIRTY_CLIENT" }>
| Readonly<{ kind: "CLIENT_DRAIN_TIMEOUT" }>
| Readonly<{ kind: "NO_WAITING_WORKER" }>
| Readonly<{ kind: "PROTOCOL_MISMATCH" }>
| Readonly<{ kind: "FAILED"; code: string }>;
export type ServiceWorkerResetOutcome =
| Readonly<{ kind: "RESET"; cachesDeleted: number }>
| Readonly<{ kind: "NOT_CONTROLLED" }>
| Readonly<{ kind: "PROTOCOL_MISMATCH" }>
| Readonly<{ kind: "FAILED"; code: string }>;
export type ServiceWorkerRemovalOutcome =
| Readonly<{ kind: "ABSENT" }>
| Readonly<{ kind: "UNREGISTERED" }>
| Readonly<{ kind: "PURGED"; cachesDeleted: number; metadataDeleted: number }>
| Readonly<{ kind: "OWNERSHIP_MISMATCH" }>
| Readonly<{ kind: "FAILED"; operation: "LOOKUP" | "UNREGISTER" | "PURGE" }>;
export interface ServiceWorkerRuntimeHost {
start(): Promise<ServiceWorkerStartOutcome>;
requestActivation(): Promise<ServiceWorkerActivationOutcome>;
resetOwnedCaches(): Promise<ServiceWorkerResetOutcome>;
stop(): Promise<void>;
/**
* R-6.3. A new worker was activated (by any tab), so this page runs under a
* worker of another build and should reload. Every tab is told, including
* the one that asked. Returns the unsubscribe function.
*/
onReloadRequired?(listener: () => void): () => void;
/**
* R-6.3. An update finished installing and waits for `requestActivation()`.
* Returns the unsubscribe function.
*/
onUpdateWaiting?(listener: () => void): () => void;
}