clone

a deno framework for local-first web apps that open instantly, work offline and sync when users choose

main
lofi / package / runtime / lifecycle.ts
lifecycle.ts 1.5K
1import { activeServerUrl, syncing } from "./config.ts";2// Package-owned browser lifecycle.3import { createForegroundRecovery, type ForegroundRecoveryState } from "./foreground-recovery.ts";4import { getRuntime } from "./runtime.ts";5import { isTransportPausedByInspector } from "./transport-gate.ts";67// Evaluated at document load: declaring a sink reloads the document on the8// SharedWorker path (see `session.ts`), so recovery activates on the boot that9// first has a sync location.10const recovery = typeof document === "undefined" ? null : createForegroundRecovery({11 enabled: Boolean(activeServerUrl()),12 pageTarget: globalThis,13 visibilityTarget: document,14 isVisible: () => document.visibilityState === "visible",15 isOnline: () => navigator.onLine,16 // Reconnect only while the user's election stands and the inspector has not17 // paused the transport — a configured server alone is not consent.18 shouldReconnect: () => syncing() && !isTransportPausedByInspector(),19 reconnect: async () => {20 const runtime = await getRuntime();21 await runtime.db.reconnect();22 },23});2425export function getForegroundRecoveryState(): ForegroundRecoveryState {26 return recovery?.getState() ?? {27 mode: activeServerUrl() ? "managed" : "local-only",28 status: "idle",29 attempts: 0,30 lastReason: "none",31 };32}3334export function subscribeForegroundRecovery(listener: () => void): () => void {35 return recovery?.subscribe(listener) ?? (() => undefined);36}3738import.meta.hot?.dispose(() => recovery?.dispose());