/** * StrictMode/HMR single-ownership + deferred teardown (API ยง2). A booted shell's * dispose is deferred one macrotask keyed by the SHELL object, so a synchronous * re-mount (StrictMode/HMR, or a different provider reusing a prebuilt Shell) * adopts the same shell by cancelling the pending dispose before it fires. */ import type { Shell } from '@astrale-os/shell' export interface BootRef { key: string | null shell: Shell | null /** Bumped per boot attempt; an in-flight init/whoami whose generation is stale is ignored. */ generation: number } /** * Pending deferred teardowns keyed by the SHELL object (not the provider): a new * adopter of the same shell โ€” a StrictMode/HMR re-setup, OR a different provider * instance reusing a prebuilt Shell โ€” cancels the pending dispose before it * fires, so the old provider's timer can never dispose a shell the new one just * adopted. Config-built shells are unique per boot, so they never collide here. */ const pendingTeardowns = new WeakMap>() export function cancelTeardown(shell: Shell): void { const timer = pendingTeardowns.get(shell) if (timer !== undefined) { clearTimeout(timer) pendingTeardowns.delete(shell) } } /** Defer a shell's dispose one macrotask, resetting the owning ref when it fires. */ export function scheduleTeardown(shell: Shell, ref: BootRef): void { cancelTeardown(shell) const timer = setTimeout(() => { pendingTeardowns.delete(shell) ref.generation += 1 disposeShell(shell) if (ref.shell === shell) ref.shell = null ref.key = null }, 0) pendingTeardowns.set(shell, timer) } export function disposeShell(shell: Shell): void { // Best-effort: dispose never rejects meaningfully for a booted shell. try { const result = shell.dispose() as unknown if (result instanceof Promise) result.catch(() => undefined) } catch { /* swallow โ€” teardown must not throw */ } }