// First run on a device: pull whatever Loro history the server log holds for // this user, then mark the replica ready. Afterwards the local docs are the // source of truth and the sync engine keeps them flowing. If the server is // unreachable the app starts empty and the pull is retried on the next call // (fresh offline installs just stay empty). import * as db from './db'; import { startSync, syncNow } from '../sync/engine'; import { deviceId } from './identity'; import { httpPeer } from '../sync/transports/http'; import { registerSeedDevice } from './identity'; let bootPromise: Promise | null = null; export function ensureBootstrapped(): Promise { bootPromise ??= runBootstrap(); return bootPromise; } export function resetBootstrapForTests(): void { bootPromise = null; } async function runBootstrap(): Promise { const peer = httpPeer(await deviceId()); if (await db.getMeta('bootstrapped')) { startSync(peer); return; } try { const manifest = await peer.manifest(); startSync(peer); if (manifest.length) await syncNow(); } catch { // Unreachable or unauthenticated: start empty, retry on the next call. bootPromise = null; return; } // Name the seed's peer so the imported example history reads from a device. await registerSeedDevice(); await db.setMeta('bootstrapped', true); }