# Sync — cross-device replication `@civility/cloud` pushes and pulls your local state to a Civility server, so a user's data follows them across devices. Use the `CloudStore` from [the store guide](./store.md), then add a `cloud` configuration. It _is_ a `Store`, so nothing about how you declare or use entities changes. How you read and write data doesn't change: local stays the source of truth, sync runs in the background. Every store write is a change, so concurrent offline edits on two devices follow Store's configured merge policy on the next sync. Civility stores and synchronizes application data; apps may encrypt it before writing and own their keys and recovery. > Protocol detail: [sync spec](../../spec/features/03_sync.md). Full API: [`jsr.io/@civility/cloud/doc`](https://jsr.io/@civility/cloud/doc). --- ## 1. Install ```sh deno add jsr:@civility/store deno add jsr:@civility/store/idb deno add jsr:@civility/cloud ``` --- ## 2. Configure sync In your [app store](../README.md#the-app-store-convention), add a `cloud` block to `CloudStore`. Every declared entity syncs by default. The collection/document names become the `storeName` keys used on the server — keep them stable across releases. ```ts // www/store/app.ts import { CloudStore } from '@civility/cloud' const cloud = new CloudStore({ storage: { db: backend }, documents: ['settings'], collections: ['items'], versions: [{ version: '1.0.0', schema }], cloud: { appId: 'me.example.myapp', // reverse-DNS id; must match the dashboard app }, }) export class App { /** Exposed to the application's connection and status layer. */ readonly cloud = cloud settings = cloud.document('settings', defaults) items = cloud.collection('items') async init() { await cloud.restore() // resume a saved session, if there is one } dispose() { cloud.dispose() // sync and store together } } ``` Store options stay at the top level; server options live under `cloud`: | Field (under `cloud`) | Type | Default | Notes | | --------------------- | ------------------------------------ | ------- | ----------------------------------------------------------------- | | `appId` | `string` | — | Reverse-DNS app id (e.g. `me.bpev.cook`). | | `manifest` | `AppManifest` | — | Registered on first sync — see [Registration](./registration.md). | | `blobPolicy` | `'eager' \| 'lazy' \| (ref) => bool` | eager | When to fetch blob bodies. Lazy = on demand. | | `syncInterval` | `number` | 30000 | Background sync period (ms). | | `selectiveSync` | `string[]` | — | Narrow which entities sync; the rest stay device-local. | Binary storage lives at `storage.blobs` alongside `storage.db`; see [Sync data and blobs](#5-sync-data-and-blobs). --- ## 3. Connection, control, and events Connect and authenticate from the application's interaction layer. Use the getters and events to reflect state; use the control methods for the occasional manual push or to pause the loop. ```ts // connection & auth cloud.connect(serverUrl) / cloud.login(email, password) / cloud.signup(...) / cloud.logout() cloud.restore() // resume a saved session + startSync cloud.saveConnection(url, token) / restoreConnection() / clearConnection() cloud.connected / authenticated / syncing / lastSync / appId // getters // sync control & blobs cloud.startSync() / stopSync() cloud.blockSync() / unblockSync() // pause the loop when the app needs to cloud.sync(): Promise // one cycle now cloud.forcePush() / forcePull() cloud.blob(hash) / cloud.evictBlob(hash) / cloud.compactBlobs(opts?) cloud.dispose() ``` Events (`cloud.addEventListener(...)`): | Event | Detail | | ---------------------------- | ------------------------------------------------------------------- | | `connected` / `disconnected` | — | | `auth` | login/logout/token change | | `sync` | `SyncEvent` — `{ pushed, pulled, serverHLC }` | | `error` | `SyncErrorEvent` — `{ error, context }` (phase: push/pull/blob_*/…) | --- ## 4. Offline-first habits Sync is background reconciliation, not request/response: - **Local is the source of truth.** Never block the application on a round-trip — a freshly-written record is queryable before it has ever reached the server. - **Make the app work with no server at all.** Sync is opt-in per user; everything should work before they connect. - **Reflect sync state, don't gate on it.** Show status through the getters and events; don't disable features when offline. - **Precache the shell** in `worker.ts` so the PWA opens offline (see the [README](../README.md#a-service-worker-precaches-the-shell)). --- ## 5. Sync data and blobs JSON changes and binary bodies use the same background sync lifecycle. Pass the local `BlobStore` as `storage.blobs`; blob references in documents and collections then cause their bodies to replicate alongside change data. With `blobPolicy: 'lazy'`, references sync immediately but bodies download on demand — important on mobile. ```ts const cloud = new CloudStore({ storage: { db: backend, blobs }, collections: ['photos'], versions: [{ version: '1.0.0', schema }], cloud: { appId: APP_ID, blobPolicy: 'lazy' }, }) const body = await cloud.blob(hash) // lazy-fetch a missing body await cloud.compactBlobs() // GC bodies no live reference points at (after a grace period) ``` The store-plus-reference pattern is shown in [Store → Local blobs](./store.md#4-local-blobs). For browser image rendering, use the `withBlobProxy` worker plugin (`@civility/cloud/worker`) or resolve a blob to an object URL. See the [gallery recipe](../recipes/gallery.md) for a full example. --- ## Application-owned encryption If your app encrypts values, write its ciphertext envelope as ordinary JSON; register a schema for that stored envelope. Civility does not issue a data key or unlock a device. Keep each nonce/ciphertext/tag bundle atomic for merges. Encrypt blob bytes before upload and retain discoverable references outside opaque payloads, or manage blob retention explicitly. Your app owns key setup, unlock, sharing, rotation, and recovery. Local Store reads remain available offline after the app shell loads, without visiting a Civility keychain popup. --- ## Sessions The sessions API lists the account's signed-in devices with rename and sign-out, so your application can let users end a lost device's session. Add `sessions:manage` to the authorization scope — the server refuses these calls without it, and full data access deliberately doesn't imply it. Build a sessions client from the saved connection: ```ts import { createSessionsHttp } from '@civility/cloud/api' const conn = await cloud.restoreConnection() if (conn) { const sessions = createSessionsHttp(conn.url, conn.token) } ``` Tokens minted before you added the scope don't carry it, so anyone who connected earlier gets a 401 here until they reconnect. Worth catching: a `listSessions()` that throws is better rendered as "reconnect to enable this" than as the raw error. --- ## Next - **[Store](./store.md)** — define local data and store blob references. - **[Services](./services.md)** — call AI and other credentialed services through the same server.