diff --git a/src/adapters/platform/browser-lifecycle.ts b/src/adapters/platform/browser-lifecycle.ts index 3e82e224..3340529f 100644 --- a/src/adapters/platform/browser-lifecycle.ts +++ b/src/adapters/platform/browser-lifecycle.ts @@ -1,9 +1,20 @@ /** - * §20.4. The single owner of window lifecycle listeners. + * §20.4. The shared owner of window lifecycle listeners. * - * No capability adds its own `visibilitychange`, `online`, `offline`, `focus`, - * `pagehide` or `pageshow` listener. They subscribe here instead, so the - * listener count stays constant and leak inspection (§23.14) is meaningful. + * When this runtime exists, a capability that needs `visibilitychange`, + * `online`, `offline`, `focus`, `pagehide` or `pageshow` subscribes here + * instead of adding its own listener, so the listeners this runtime holds stay + * constant and leak inspection (§23.14) can count them. + * + * 05-03. The rule is narrower than "the only such listener in the page": + * - The runtime exists only when a Service Worker or realtime capability is + * composed (`startAfterMount` in `optional-runtime-host.ts`). The default + * composition has none, and `browserLifecycle()` returns null there. + * - Two adapters hold their own window listener: the telemetry collector's + * `pagehide` page-exit flush (attached while a queue waits for a flush, and + * composed by default) and the native file picker's `focus` listener (held + * while a picker is open, to notice dismissal). + * No check enforces this. A new exception belongs in the list above. * * §20.6: nothing in this module is a correctness boundary. `beforeunload` is a * user prompt, never a place to complete a command, write a checkpoint or diff --git a/src/bootstrap/optional-runtime-host.ts b/src/bootstrap/optional-runtime-host.ts index 916ac188..21714859 100644 --- a/src/bootstrap/optional-runtime-host.ts +++ b/src/bootstrap/optional-runtime-host.ts @@ -85,8 +85,9 @@ export function createOptionalRuntimeHost( if (stopPromise) return stopPromise; if (startPromise) return startPromise; startPromise = (async () => { - // 1. The lifecycle observer is the single window listener owner. It is - // only created when something downstream can actually consume it. + // 1. The lifecycle observer owns the shared window lifecycle listeners + // (exceptions are listed in browser-lifecycle.ts). It is only created + // when something downstream can actually consume it. if (serviceWorker || capabilities.realtime.length > 0) { lifecycle = createBrowserLifecycleRuntime(input.browserLifecycleHost); } diff --git a/tests/unit/browser-lifecycle.test.ts b/tests/unit/browser-lifecycle.test.ts new file mode 100644 index 00000000..7854ace5 --- /dev/null +++ b/tests/unit/browser-lifecycle.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createBrowserLifecycleRuntime, + type BrowserLifecycleEvent, +} from "../../src/adapters/platform/index.ts"; + +type Listener = (event: unknown) => void; + +// 05-03. Records listeners per target so the test can count what the runtime +// attached and fire events without a DOM. +function createHost(initial: { hidden?: boolean; online?: boolean } = {}) { + const listeners = new Map>(); + const target = (scope: string) => ({ + addEventListener: (type: string, listener: Listener) => { + const key = `${scope}:${type}`; + const set = listeners.get(key) ?? new Set(); + set.add(listener); + listeners.set(key, set); + }, + removeEventListener: (type: string, listener: Listener) => { + listeners.get(`${scope}:${type}`)?.delete(listener); + }, + }); + const document = { + ...target("document"), + visibilityState: initial.hidden ? "hidden" : "visible", + }; + const host = { + ...target("window"), + document, + navigator: { onLine: initial.online ?? true }, + }; + const count = (key?: string) => + [...listeners.entries()] + .filter(([name]) => key === undefined || name === key) + .reduce((total, [, set]) => total + set.size, 0); + const fire = (key: string, event: unknown = {}) => { + for (const listener of [...(listeners.get(key) ?? [])]) listener(event); + }; + return { host, document, count, fire }; +} + +function create(initial?: Parameters[0]) { + const fake = createHost(initial); + const runtime = createBrowserLifecycleRuntime( + fake.host as unknown as Parameters[0], + ); + return { ...fake, runtime }; +} + +describe("browser lifecycle runtime", () => { + it("attaches one listener per lifecycle event and no beforeunload", () => { + const { count } = create(); + for (const key of [ + "document:visibilitychange", + "window:online", + "window:offline", + "window:focus", + "window:pagehide", + "window:pageshow", + ]) { + expect(count(key)).toBe(1); + } + expect(count("window:beforeunload")).toBe(0); + expect(count()).toBe(6); + }); + + it("starts a new generation only on a bfcache restore", () => { + const { runtime, fire } = create(); + const events: BrowserLifecycleEvent[] = []; + runtime.subscribe((event) => events.push(event)); + + expect(runtime.getSnapshot()).toMatchObject({ + generation: 1, + pageState: "ACTIVE", + }); + fire("window:pageshow", { persisted: false }); + expect(runtime.getSnapshot()).toMatchObject({ + generation: 1, + pageState: "ACTIVE", + }); + + fire("window:pagehide", { persisted: true }); + expect(runtime.getSnapshot().pageState).toBe("PAGEHIDE"); + fire("window:pageshow", { persisted: true }); + expect(runtime.getSnapshot()).toMatchObject({ + generation: 2, + pageState: "BFCACHE_RESTORED", + }); + expect(events.map((event) => event.kind)).toEqual([ + "PAGESHOW", + "PAGEHIDE", + "PAGESHOW", + ]); + expect(events.at(-1)).toMatchObject({ + persisted: true, + snapshot: { generation: 2 }, + }); + }); + + it("tracks visibility and connectivity and isolates a throwing subscriber", () => { + const { runtime, document, fire } = create({ hidden: true, online: false }); + expect(runtime.getSnapshot()).toMatchObject({ + visibility: "HIDDEN", + connectivityHint: "OFFLINE", + }); + const received = vi.fn(); + runtime.subscribe(() => { + throw new Error("subscriber defect"); + }); + runtime.subscribe(received); + + document.visibilityState = "visible"; + fire("document:visibilitychange"); + fire("window:online"); + expect(runtime.getSnapshot()).toMatchObject({ + visibility: "VISIBLE", + connectivityHint: "ONLINE", + }); + expect(received).toHaveBeenCalledTimes(2); + }); + + it("holds beforeunload only while a dirty source is registered", () => { + const { runtime, count, fire } = create(); + let dirty = false; + const unregister = runtime.registerDirtySource(() => dirty); + const unregisterBroken = runtime.registerDirtySource(() => { + throw new Error("reporter defect"); + }); + expect(count("window:beforeunload")).toBe(1); + + const clean = { preventDefault: vi.fn() }; + fire("window:beforeunload", clean); + expect(clean.preventDefault).not.toHaveBeenCalled(); + + dirty = true; + const prompted = { preventDefault: vi.fn() }; + fire("window:beforeunload", prompted); + expect(prompted.preventDefault).toHaveBeenCalledOnce(); + + unregister(); + expect(count("window:beforeunload")).toBe(1); + unregisterBroken(); + expect(count("window:beforeunload")).toBe(0); + }); + + it("removes every listener on dispose and ignores later subscriptions", () => { + const { runtime, count, fire } = create(); + runtime.registerDirtySource(() => true); + const received = vi.fn(); + runtime.subscribe(received); + expect(count()).toBe(7); + + runtime.dispose(); + expect(count()).toBe(0); + + const late = vi.fn(); + runtime.subscribe(late); + runtime.registerDirtySource(() => true); + fire("window:focus"); + expect(count()).toBe(0); + expect(received).not.toHaveBeenCalled(); + expect(late).not.toHaveBeenCalled(); + }); +});