Sync API Reference
The consumer-facing TypeScript and Dart client API for wiring Oalo sync into your app.
The consumer-facing API for the sync library, for a developer wiring it into an
app without the server code. Read sync-overview.md first for the mental
model and the TS/Dart layering. HTTP fallback and scopes have their own pages.
Versions: @synclib-io/client 0.7.1, @synclib-io/sync 0.7.1,
@synclib-io/react 0.5.0, @synclib-io/core 0.1.2. Dart synclib_sync +
synclib_flutter are git dependencies pinned to main.
Install
TypeScript:
npm i @synclib-io/client # the surface you hold
npm i @synclib-io/react # React bindings, optional
# @synclib-io/sync and @synclib-io/core come in as deps
Dart (pubspec.yaml), both as git deps:
dependencies:
synclib_sync:
git: { url: git@github.com:synclib-io/synclib_sync.git, ref: main }
synclib_flutter:
git: { url: git@github.com:synclib-io/synclib_flutter.git, ref: main }
Construct + connect (TypeScript)
import { SynclibClient, SynclibStore } from "@synclib-io/client";
const store = await SynclibStore.create({ databaseName, wasmUrl }); // browser wasm
const client = new SynclibClient({
serverUrl, // ws(s):// endpoint; the lib derives the http base itself
channels: [{
topic: "sync:app:app_builder", // Oalo apps: always exactly this name
role: "bidirectional", // "push" | "pull" | "bidirectional"
tables: [{ name: "posts" }, { name: "profiles" }],
params: { locale: "en" }, // per-channel join params, forwarded on join
// activeScopes / scopeKind: omit for whole-app sync; see sync-scopes.md
}],
clientId, // optional; defaults to a persisted UUID
getToken: async () => jwt, // called at connect + on auth-failure refresh
connectParams: { slug, env }, // socket-level extras that select your app's data environment
merkleVerifyInterval: 24*60*60*1000, // optional; ms; omit to disable
});
await client.initialize(store); // hand it the store
await client.connect(); // the one explicit connect
Config shape: SynclibClientConfig has serverUrl, channels, getToken, and
optional clientId, connectParams, merkleVerifyInterval. The store is passed
separately to initialize(), not in the config. ChannelConfig is
{ topic, role, tables: {name, direction?}[], params?, activeScopes?, scopeKind? }.
Construct + connect (Dart)
import 'package:synclib_sync/synclib_sync.dart';
final client = SyncClient(SyncClientConfig(
dbPath: dbName, // or database: <pre-opened SynclibDatabase>
serverUrl: serverUrl,
clientId: clientId,
codec: SyncCodecType.json, // json (default) or msgpack
channels: [SyncChannel(
topic: 'sync:user:$userId',
role: ChannelRole.bidirectional,
tables: syncTables, // List<SyncTable>
params: {'token': token, 'locale': 'en'},
// activeScopes / scopeKind: omit for whole-app sync
)],
syncOnWrite: true,
autoSyncOnConnect: false, // true = auto catch-up on (re)connect
merkleVerifyInterval: const Duration(hours: 24),
));
await client.initialize();
await client.connect(token: token);
Dart config exposes more than TS: codec, dbPath/database, syncOnWrite,
autoSyncOnConnect, onConflict, merkleSkipColumns. There is no getToken
callback; you pass the token to connect(token:) and refresh with
updateToken(token).
Lifecycle
| Step | TS | Dart |
|---|---|---|
| create store | SynclibStore.create(...) | opened db / dbPath |
| attach store | client.initialize(store) | client.initialize() |
| connect | client.connect() | client.connect(token: ...) |
| catch up | client.syncUnified(opts?) | client.sync() / syncUnified(...) |
| observe connection | client.onConnectionStateChange(fn) | client.stateChanges |
| disconnect | client.disconnect() | client.disconnect() |
syncUnified() pushes pending local writes, then pulls what is newer per channel.
Options: TS { forceRefresh?: string[]; includeStripped?: boolean }; Dart adds
skipMerkle.
Reconnect obligation (TS): the TS wrapper does not auto-push on reconnect.
When onConnectionStateChange reports "connected", call syncUnified() yourself
to flush writes made while offline. Dart with autoSyncOnConnect: true does this
for you.
Channels: roles and joining or leaving
Each channel declares a role that gates its direction:
- pull only receives server rows (its tables never push local writes).
- push only sends local writes (never pulls).
- bidirectional does both.
The pull planner skips non-pull channels, and the push side sends only push and bidirectional channels' tables. One asymmetry to know: on the WebSocket path, role gates pulls, but a push flushes the whole pending queue regardless of channel. The HTTP fallback path respects role in both directions.
Channels in an Oalo app. Every table, shared and owned, goes on one channel
with the topic sync:app:app_builder (bidirectional for a signed-in member,
pull when signed out). The Base limits a member to shared rows plus their own
there. A signed-in member also joins sync:user:<user id> with no tables, as
a listener: live changes to their own rows are sent on it. Live changes to shared
rows are sent only on sync:app:app_builder, so keep the tables there.
Connect your own frontend has the full setup. (The
Dart example above follows the Flutter app Oalo creates: one sync:user:<id>
channel with every table, so it gets shared rows' changes on its next sync.)
Scopes narrow a channel to one screen's worth (see sync-scopes.md).
Joining and leaving at runtime. After connect you can change live membership:
- TS:
client.joinChannel(channel),leaveChannel(channel),leaveChannelById(id),isChannelJoined,getJoinedChannels. - Dart: the same, plus
joinChannelByTopic(topic, params:).
Both require an active connection. Important gotcha: joinChannel changes socket
membership and runs an on-join sync, but it does not add the channel to the
client's configured channel list, and the recurring push/pull plan is built from
that configured list. So a channel you join dynamically takes part in its on-join
sync but not in later periodic syncs unless you also update the config: TS
client.updateChannels(channels); Dart has no public config-channels setter today,
so declare such channels at construct time (or reconstruct the client).
Version note: this describes current
@synclib-io/sync(0.7.x).updateChannelsand scope-driven pulls are newer additions;joinChannel/leaveChannelare not. If your app pins an older 0.5.x, confirm the API before relying on it.
Reading + writing data
Reads and writes go through the local store, not the network. In Oalo's app
templates this is wrapped by generated hooks/providers (useXList,
useXMutations in TS; Riverpod providers in Dart). A raw consumer reads and
writes the store directly and lets the client sync it. Writes are pushed
automatically (debounced) when syncOnWrite is on.
React bindings (@synclib-io/react): SynclibProvider, useSynclibClient(),
useSynclibStore(), plus useSyncScope and useSyncStatus (see below).
On-demand fetch (fetch one screen's worth)
For a screen that needs rows not held locally (large tables, or while degraded),
pull just those rows instead of relying on a full sync. Same shape both languages;
returns PullPage { table, applied, received, nextSeqnum, hasMore }.
TypeScript (on SynclibClient):
const page = await client.fetchPage(table, { topic, since, limit }); // paged; loop on nextSeqnum until !hasMore
await client.ensureRow(table, id, topic); // one row by id; no-op while isSyncLive
await client.ensureRows(table, ids, topic); // many by id; no-op while isSyncLive
Dart (via SyncManager, see sync-http-fallback.md):
final page = await manager.fetchPage(table, topic: topic, since: since, limit: limit);
await manager.ensureRow(table, id, topic);
await manager.ensureRows(table, ids, topic);
fetchPage always fetches. ensureRow/ensureRows are no-ops while isSyncLive
is true, because the row is already local.
Gotcha: the third argument is the channel topic, even though some docstrings in the code call it
scopeand show values like"user". Pass the topic string (for example"sync:app:app_builder").
Integrity verification (merkle)
The only consumer knob is merkleVerifyInterval. When set, at the end of each
syncUnified() (and no more often than the interval) the client compares a
content hash of each table against the server and repairs any drift automatically
(block-level drill-down, then per-channel fetch/push). The first run just seeds
the timestamp. The timestamp only advances when every channel verifies clean, so
a failed run retries next sync. Recommended value: once a day.
Observing repairs: Dart exposes a merkleVerificationEvents stream. The TS
wrapper does not re-expose merkle events today, so a wrapper-only consumer
cannot tell when a repair ran.
Auth (what you must supply)
You supply a JWT bearer token. TS via getToken (called at connect and on
auth-failure) and updateToken() for a proactive refresh; Dart via
connect(token:) and updateToken(). The same token authenticates the HTTP
fallback. Tokens live about an hour, so refresh ahead of expiry.
connectParams / extra can carry slug and env, which select your app's data
environment (dev / prod).
The token is the one your Base returns from POST /api/auth/verify-code (and
/refresh-token). Your app never creates or signs one. Signed out, pass the
string app_builder:<app slug> instead: that connects with shared rows only,
read-only. The server derives identity and scope from the token, never from the
request. See Connect your own frontend and auth.md.
Sharp edges to know
- TS wrapper vs core split. A few methods live only on the lower-level
@synclib-io/syncSyncClient(for exampleupdateActiveScopes,resetScopeCursor), not on theSynclibClientwrapper. If you need those, hold the inner client. useSyncStatusis stubbed. In@synclib-io/reactit returns{ connectionState, syncState }but reads them once and does not re-render on change. For live transport status useonTransportChangeon the client instead (seesync-http-fallback.md).- Two scope APIs coexist. See
sync-scopes.md; pickactiveScopes, not the oldersyncScope, for real wire scoping.
Sign up, install the CLI, and deploy your repo in a few minutes.