Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/lib/pwa/registerServiceWorker.ts
T

48 lines
1.7 KiB
TypeScript

/**
* Service-worker registration helper used by `root.tsx`. Kept in its own
* module so it can be unit-tested without rendering a React tree.
*
* The function is a no-op when:
* - `navigator.serviceWorker` is unavailable (SSR, older browsers).
* - `window.location.protocol` is not http(s) — file:// previews would
* otherwise throw SecurityError.
* - `import.meta.env.DEV` is true — the dev server hot-reloads, and
* a cached SW would shadow new bundles.
*
* Refs: docs/improvement-plan/10-compliance-polish/lighthouse.md (Step (d)).
*/
import { SERVICE_WORKER_VERSION } from "./serviceWorkerRecoveryBootstrap";
export const SERVICE_WORKER_SCRIPT_URL = `/sw.js?v=${encodeURIComponent(SERVICE_WORKER_VERSION)}`;
export type RegisterServiceWorkerOptions = {
scriptUrl?: string;
scope?: string;
/** Inject an override container so tests can supply a fake navigator. */
navigatorRef?: Navigator;
/** Inject an override container so tests can disable DEV gating. */
isDev?: boolean;
/** Optional client-side telemetry hook; registration failure remains non-fatal. */
onError?: (error: unknown) => void;
};
export async function registerServiceWorker(options: RegisterServiceWorkerOptions = {}): Promise<ServiceWorkerRegistration | null> {
const navigatorRef = options.navigatorRef ?? (typeof navigator === "undefined" ? undefined : navigator);
if (!navigatorRef || !("serviceWorker" in navigatorRef)) {
return null;
}
if (options.isDev) {
return null;
}
try {
return await navigatorRef.serviceWorker.register(options.scriptUrl ?? SERVICE_WORKER_SCRIPT_URL, {
scope: options.scope ?? "/",
});
} catch (err) {
options.onError?.(err);
return null;
}
}