@terreno/syncdb 56.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +419 -0
- package/dist/auth/betterAuthAdapter.d.ts +22 -0
- package/dist/auth/betterAuthAdapter.d.ts.map +1 -0
- package/dist/auth/betterAuthAdapter.js +181 -0
- package/dist/auth/betterAuthAdapter.js.map +1 -0
- package/dist/auth/betterAuthAdapter.test.d.ts +2 -0
- package/dist/auth/betterAuthAdapter.test.d.ts.map +1 -0
- package/dist/auth/betterAuthAdapter.test.js +350 -0
- package/dist/auth/betterAuthAdapter.test.js.map +1 -0
- package/dist/auth/types.d.ts +42 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/auth/types.js +9 -0
- package/dist/auth/types.js.map +1 -0
- package/dist/client.d.ts +246 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +1415 -0
- package/dist/client.js.map +1 -0
- package/dist/client.test.d.ts +2 -0
- package/dist/client.test.d.ts.map +1 -0
- package/dist/client.test.js +2310 -0
- package/dist/client.test.js.map +1 -0
- package/dist/crypto/aesGcmCodec.d.ts +33 -0
- package/dist/crypto/aesGcmCodec.d.ts.map +1 -0
- package/dist/crypto/aesGcmCodec.js +80 -0
- package/dist/crypto/aesGcmCodec.js.map +1 -0
- package/dist/crypto/aesGcmCodec.test.d.ts +2 -0
- package/dist/crypto/aesGcmCodec.test.d.ts.map +1 -0
- package/dist/crypto/aesGcmCodec.test.js +83 -0
- package/dist/crypto/aesGcmCodec.test.js.map +1 -0
- package/dist/crypto/identityCodec.d.ts +7 -0
- package/dist/crypto/identityCodec.d.ts.map +1 -0
- package/dist/crypto/identityCodec.js +9 -0
- package/dist/crypto/identityCodec.js.map +1 -0
- package/dist/crypto/keyProviders.d.ts +34 -0
- package/dist/crypto/keyProviders.d.ts.map +1 -0
- package/dist/crypto/keyProviders.js +102 -0
- package/dist/crypto/keyProviders.js.map +1 -0
- package/dist/crypto/keyProviders.test.d.ts +2 -0
- package/dist/crypto/keyProviders.test.d.ts.map +1 -0
- package/dist/crypto/keyProviders.test.js +189 -0
- package/dist/crypto/keyProviders.test.js.map +1 -0
- package/dist/crypto/types.d.ts +24 -0
- package/dist/crypto/types.d.ts.map +1 -0
- package/dist/crypto/types.js +8 -0
- package/dist/crypto/types.js.map +1 -0
- package/dist/debug/debugChannel.d.ts +52 -0
- package/dist/debug/debugChannel.d.ts.map +1 -0
- package/dist/debug/debugChannel.js +73 -0
- package/dist/debug/debugChannel.js.map +1 -0
- package/dist/debug/debugChannel.test.d.ts +2 -0
- package/dist/debug/debugChannel.test.d.ts.map +1 -0
- package/dist/debug/debugChannel.test.js +105 -0
- package/dist/debug/debugChannel.test.js.map +1 -0
- package/dist/debug/debugLog.d.ts +111 -0
- package/dist/debug/debugLog.d.ts.map +1 -0
- package/dist/debug/debugLog.js +150 -0
- package/dist/debug/debugLog.js.map +1 -0
- package/dist/debug/debugLog.test.d.ts +2 -0
- package/dist/debug/debugLog.test.d.ts.map +1 -0
- package/dist/debug/debugLog.test.js +121 -0
- package/dist/debug/debugLog.test.js.map +1 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +51 -0
- package/dist/index.js.map +1 -0
- package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts +2 -0
- package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts.map +1 -0
- package/dist/isolated/defaultPersisterFactoryNative.isolated.js +38 -0
- package/dist/isolated/defaultPersisterFactoryNative.isolated.js.map +1 -0
- package/dist/mutations/conflicts.d.ts +31 -0
- package/dist/mutations/conflicts.d.ts.map +1 -0
- package/dist/mutations/conflicts.js +73 -0
- package/dist/mutations/conflicts.js.map +1 -0
- package/dist/mutations/outbox.d.ts +174 -0
- package/dist/mutations/outbox.d.ts.map +1 -0
- package/dist/mutations/outbox.js +385 -0
- package/dist/mutations/outbox.js.map +1 -0
- package/dist/mutations/outbox.test.d.ts +2 -0
- package/dist/mutations/outbox.test.d.ts.map +1 -0
- package/dist/mutations/outbox.test.js +643 -0
- package/dist/mutations/outbox.test.js.map +1 -0
- package/dist/mutations/resolveConflict.d.ts +32 -0
- package/dist/mutations/resolveConflict.d.ts.map +1 -0
- package/dist/mutations/resolveConflict.js +101 -0
- package/dist/mutations/resolveConflict.js.map +1 -0
- package/dist/mutations/resolveConflict.test.d.ts +2 -0
- package/dist/mutations/resolveConflict.test.d.ts.map +1 -0
- package/dist/mutations/resolveConflict.test.js +282 -0
- package/dist/mutations/resolveConflict.test.js.map +1 -0
- package/dist/persisters/defaultPersisterFactory.d.ts +9 -0
- package/dist/persisters/defaultPersisterFactory.d.ts.map +1 -0
- package/dist/persisters/defaultPersisterFactory.js +9 -0
- package/dist/persisters/defaultPersisterFactory.js.map +1 -0
- package/dist/persisters/defaultPersisterFactory.native.d.ts +10 -0
- package/dist/persisters/defaultPersisterFactory.native.d.ts.map +1 -0
- package/dist/persisters/defaultPersisterFactory.native.js +44 -0
- package/dist/persisters/defaultPersisterFactory.native.js.map +1 -0
- package/dist/persisters/defaultPersisterFactory.test.d.ts +2 -0
- package/dist/persisters/defaultPersisterFactory.test.d.ts.map +1 -0
- package/dist/persisters/defaultPersisterFactory.test.js +177 -0
- package/dist/persisters/defaultPersisterFactory.test.js.map +1 -0
- package/dist/persisters/defaultPersisterFactory.web.d.ts +17 -0
- package/dist/persisters/defaultPersisterFactory.web.d.ts.map +1 -0
- package/dist/persisters/defaultPersisterFactory.web.js +65 -0
- package/dist/persisters/defaultPersisterFactory.web.js.map +1 -0
- package/dist/persisters/encryptedIndexedDbPersister.d.ts +46 -0
- package/dist/persisters/encryptedIndexedDbPersister.d.ts.map +1 -0
- package/dist/persisters/encryptedIndexedDbPersister.js +171 -0
- package/dist/persisters/encryptedIndexedDbPersister.js.map +1 -0
- package/dist/persisters/encryptedIndexedDbPersister.test.d.ts +2 -0
- package/dist/persisters/encryptedIndexedDbPersister.test.d.ts.map +1 -0
- package/dist/persisters/encryptedIndexedDbPersister.test.js +352 -0
- package/dist/persisters/encryptedIndexedDbPersister.test.js.map +1 -0
- package/dist/persisters/memoryPersister.d.ts +19 -0
- package/dist/persisters/memoryPersister.d.ts.map +1 -0
- package/dist/persisters/memoryPersister.js +31 -0
- package/dist/persisters/memoryPersister.js.map +1 -0
- package/dist/persisters/memoryPersister.test.d.ts +2 -0
- package/dist/persisters/memoryPersister.test.d.ts.map +1 -0
- package/dist/persisters/memoryPersister.test.js +113 -0
- package/dist/persisters/memoryPersister.test.js.map +1 -0
- package/dist/persisters/types.d.ts +65 -0
- package/dist/persisters/types.d.ts.map +1 -0
- package/dist/persisters/types.js +2 -0
- package/dist/persisters/types.js.map +1 -0
- package/dist/react/hooks.d.ts +132 -0
- package/dist/react/hooks.d.ts.map +1 -0
- package/dist/react/hooks.js +269 -0
- package/dist/react/hooks.js.map +1 -0
- package/dist/react/hooks.test.d.ts +2 -0
- package/dist/react/hooks.test.d.ts.map +1 -0
- package/dist/react/hooks.test.js +645 -0
- package/dist/react/hooks.test.js.map +1 -0
- package/dist/react/index.d.ts +11 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +11 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/provider.d.ts +11 -0
- package/dist/react/provider.d.ts.map +1 -0
- package/dist/react/provider.js +17 -0
- package/dist/react/provider.js.map +1 -0
- package/dist/storage/idb.d.ts +27 -0
- package/dist/storage/idb.d.ts.map +1 -0
- package/dist/storage/idb.js +72 -0
- package/dist/storage/idb.js.map +1 -0
- package/dist/storage/idb.test.d.ts +2 -0
- package/dist/storage/idb.test.d.ts.map +1 -0
- package/dist/storage/idb.test.js +100 -0
- package/dist/storage/idb.test.js.map +1 -0
- package/dist/storage/purgeUnknownStream.test.d.ts +2 -0
- package/dist/storage/purgeUnknownStream.test.d.ts.map +1 -0
- package/dist/storage/purgeUnknownStream.test.js +64 -0
- package/dist/storage/purgeUnknownStream.test.js.map +1 -0
- package/dist/storage/schema.d.ts +33 -0
- package/dist/storage/schema.d.ts.map +1 -0
- package/dist/storage/schema.js +92 -0
- package/dist/storage/schema.js.map +1 -0
- package/dist/storage/store.d.ts +136 -0
- package/dist/storage/store.d.ts.map +1 -0
- package/dist/storage/store.js +275 -0
- package/dist/storage/store.js.map +1 -0
- package/dist/storage/store.test.d.ts +2 -0
- package/dist/storage/store.test.d.ts.map +1 -0
- package/dist/storage/store.test.js +357 -0
- package/dist/storage/store.test.js.map +1 -0
- package/dist/storage/types.d.ts +146 -0
- package/dist/storage/types.d.ts.map +1 -0
- package/dist/storage/types.js +32 -0
- package/dist/storage/types.js.map +1 -0
- package/dist/storage/wipe.d.ts +22 -0
- package/dist/storage/wipe.d.ts.map +1 -0
- package/dist/storage/wipe.js +43 -0
- package/dist/storage/wipe.js.map +1 -0
- package/dist/storage/wipe.test.d.ts +2 -0
- package/dist/storage/wipe.test.d.ts.map +1 -0
- package/dist/storage/wipe.test.js +95 -0
- package/dist/storage/wipe.test.js.map +1 -0
- package/dist/sync/bootstrap.d.ts +64 -0
- package/dist/sync/bootstrap.d.ts.map +1 -0
- package/dist/sync/bootstrap.js +160 -0
- package/dist/sync/bootstrap.js.map +1 -0
- package/dist/sync/bootstrap.test.d.ts +2 -0
- package/dist/sync/bootstrap.test.d.ts.map +1 -0
- package/dist/sync/bootstrap.test.js +447 -0
- package/dist/sync/bootstrap.test.js.map +1 -0
- package/dist/sync/cursor.d.ts +67 -0
- package/dist/sync/cursor.d.ts.map +1 -0
- package/dist/sync/cursor.js +74 -0
- package/dist/sync/cursor.js.map +1 -0
- package/dist/sync/cursor.test.d.ts +2 -0
- package/dist/sync/cursor.test.d.ts.map +1 -0
- package/dist/sync/cursor.test.js +73 -0
- package/dist/sync/cursor.test.js.map +1 -0
- package/dist/sync/deltaApplier.d.ts +30 -0
- package/dist/sync/deltaApplier.d.ts.map +1 -0
- package/dist/sync/deltaApplier.js +61 -0
- package/dist/sync/deltaApplier.js.map +1 -0
- package/dist/sync/deltaApplier.test.d.ts +2 -0
- package/dist/sync/deltaApplier.test.d.ts.map +1 -0
- package/dist/sync/deltaApplier.test.js +212 -0
- package/dist/sync/deltaApplier.test.js.map +1 -0
- package/dist/sync/entityRepair.d.ts +45 -0
- package/dist/sync/entityRepair.d.ts.map +1 -0
- package/dist/sync/entityRepair.js +91 -0
- package/dist/sync/entityRepair.js.map +1 -0
- package/dist/sync/entityRepair.test.d.ts +2 -0
- package/dist/sync/entityRepair.test.d.ts.map +1 -0
- package/dist/sync/entityRepair.test.js +146 -0
- package/dist/sync/entityRepair.test.js.map +1 -0
- package/dist/sync/httpChannel.d.ts +74 -0
- package/dist/sync/httpChannel.d.ts.map +1 -0
- package/dist/sync/httpChannel.js +123 -0
- package/dist/sync/httpChannel.js.map +1 -0
- package/dist/sync/httpChannel.test.d.ts +2 -0
- package/dist/sync/httpChannel.test.d.ts.map +1 -0
- package/dist/sync/httpChannel.test.js +215 -0
- package/dist/sync/httpChannel.test.js.map +1 -0
- package/dist/sync/replayCoordinator.d.ts +212 -0
- package/dist/sync/replayCoordinator.d.ts.map +1 -0
- package/dist/sync/replayCoordinator.js +1110 -0
- package/dist/sync/replayCoordinator.js.map +1 -0
- package/dist/sync/replayCoordinator.test.d.ts +2 -0
- package/dist/sync/replayCoordinator.test.d.ts.map +1 -0
- package/dist/sync/replayCoordinator.test.js +1496 -0
- package/dist/sync/replayCoordinator.test.js.map +1 -0
- package/dist/sync/socketTransport.d.ts +56 -0
- package/dist/sync/socketTransport.d.ts.map +1 -0
- package/dist/sync/socketTransport.js +292 -0
- package/dist/sync/socketTransport.js.map +1 -0
- package/dist/sync/socketTransport.test.d.ts +2 -0
- package/dist/sync/socketTransport.test.d.ts.map +1 -0
- package/dist/sync/socketTransport.test.js +346 -0
- package/dist/sync/socketTransport.test.js.map +1 -0
- package/dist/sync/transport.d.ts +80 -0
- package/dist/sync/transport.d.ts.map +1 -0
- package/dist/sync/transport.js +5 -0
- package/dist/sync/transport.js.map +1 -0
- package/dist/testing/fakeTransport.d.ts +55 -0
- package/dist/testing/fakeTransport.d.ts.map +1 -0
- package/dist/testing/fakeTransport.js +139 -0
- package/dist/testing/fakeTransport.js.map +1 -0
- package/dist/testing/fakeTransport.test.d.ts +2 -0
- package/dist/testing/fakeTransport.test.d.ts.map +1 -0
- package/dist/testing/fakeTransport.test.js +112 -0
- package/dist/testing/fakeTransport.test.js.map +1 -0
- package/dist/testing/index.d.ts +13 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +13 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/types.d.ts +271 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +9 -0
- package/dist/types.js.map +1 -0
- package/package.json +71 -0
- package/src/auth/betterAuthAdapter.test.ts +455 -0
- package/src/auth/betterAuthAdapter.ts +214 -0
- package/src/auth/types.ts +49 -0
- package/src/client.test.ts +2670 -0
- package/src/client.ts +1748 -0
- package/src/crypto/aesGcmCodec.test.ts +103 -0
- package/src/crypto/aesGcmCodec.ts +98 -0
- package/src/crypto/identityCodec.ts +10 -0
- package/src/crypto/keyProviders.test.ts +228 -0
- package/src/crypto/keyProviders.ts +153 -0
- package/src/crypto/types.ts +23 -0
- package/src/debug/debugChannel.test.ts +121 -0
- package/src/debug/debugChannel.ts +112 -0
- package/src/debug/debugLog.test.ts +139 -0
- package/src/debug/debugLog.ts +272 -0
- package/src/index.ts +157 -0
- package/src/isolated/defaultPersisterFactoryNative.isolated.ts +45 -0
- package/src/mutations/conflicts.ts +108 -0
- package/src/mutations/outbox.test.ts +754 -0
- package/src/mutations/outbox.ts +585 -0
- package/src/mutations/resolveConflict.test.ts +338 -0
- package/src/mutations/resolveConflict.ts +115 -0
- package/src/persisters/defaultPersisterFactory.native.ts +53 -0
- package/src/persisters/defaultPersisterFactory.test.ts +207 -0
- package/src/persisters/defaultPersisterFactory.ts +12 -0
- package/src/persisters/defaultPersisterFactory.web.ts +78 -0
- package/src/persisters/encryptedIndexedDbPersister.test.ts +381 -0
- package/src/persisters/encryptedIndexedDbPersister.ts +218 -0
- package/src/persisters/memoryPersister.test.ts +136 -0
- package/src/persisters/memoryPersister.ts +52 -0
- package/src/persisters/types.ts +71 -0
- package/src/react/hooks.test.tsx +761 -0
- package/src/react/hooks.ts +409 -0
- package/src/react/index.ts +11 -0
- package/src/react/provider.tsx +27 -0
- package/src/storage/idb.test.ts +116 -0
- package/src/storage/idb.ts +112 -0
- package/src/storage/purgeUnknownStream.test.ts +74 -0
- package/src/storage/schema.ts +103 -0
- package/src/storage/store.test.ts +424 -0
- package/src/storage/store.ts +461 -0
- package/src/storage/types.ts +159 -0
- package/src/storage/wipe.test.ts +111 -0
- package/src/storage/wipe.ts +58 -0
- package/src/sync/bootstrap.test.ts +486 -0
- package/src/sync/bootstrap.ts +217 -0
- package/src/sync/cursor.test.ts +84 -0
- package/src/sync/cursor.ts +113 -0
- package/src/sync/deltaApplier.test.ts +237 -0
- package/src/sync/deltaApplier.ts +84 -0
- package/src/sync/entityRepair.test.ts +161 -0
- package/src/sync/entityRepair.ts +124 -0
- package/src/sync/httpChannel.test.ts +265 -0
- package/src/sync/httpChannel.ts +220 -0
- package/src/sync/replayCoordinator.test.ts +1709 -0
- package/src/sync/replayCoordinator.ts +1370 -0
- package/src/sync/socketTransport.test.ts +413 -0
- package/src/sync/socketTransport.ts +379 -0
- package/src/sync/transport.ts +76 -0
- package/src/testing/fakeTransport.test.ts +125 -0
- package/src/testing/fakeTransport.ts +206 -0
- package/src/testing/index.ts +18 -0
- package/src/types.ts +284 -0
package/README.md
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
# @terreno/syncdb
|
|
2
|
+
|
|
3
|
+
Local-first data layer for Terreno apps. A TinyBase `MergeableStore` (encrypted IndexedDB on web, expo-sqlite on native) is the UI's source of truth: reads come from the local store, writes apply optimistically and enqueue in a durable outbox, and the server reconciles asynchronously over a socket delta protocol with HTTP snapshot catch-up. Every mutation executes the existing `@terreno/api` modelRouter write path — identical permissions, hooks, and validation as REST. Supersedes `@terreno/rtk` for data-synchronization concerns (see [the migration guide](../docs/how-to/migrate-rtk-to-syncdb.md)).
|
|
4
|
+
|
|
5
|
+
## Architecture
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
FRONTEND (@terreno/syncdb) BACKEND (@terreno/api)
|
|
9
|
+
┌───────────────────────────────────┐ ┌────────────────────────────────────┐
|
|
10
|
+
│ React hooks (useQuery, useEntity, │ │ modelRouter(path, Model, {sync}) │
|
|
11
|
+
│ useMutate, useSyncStatus, ...) │ │ └─ sync registry + validation │
|
|
12
|
+
│ │ ▲ │ │ │
|
|
13
|
+
│ ▼ │ │ │ syncPlugin (schema) │
|
|
14
|
+
│ TinyBase MergeableStore │ │ └─ stamps _syncSeq per write │
|
|
15
|
+
│ {collection} tables + _outbox │ │ │
|
|
16
|
+
│ + _cursors + _conflicts │ │ SyncApp (HTTP) RealtimeApp │
|
|
17
|
+
│ │ ▲ │ │ /sync/snapshot (Socket.io + │
|
|
18
|
+
│ ▼ │ │ │ /sync/mutate change streams)│
|
|
19
|
+
│ Persister (AES-GCM IndexedDB on │ │ /sync/key │ │
|
|
20
|
+
│ web, expo-sqlite on native) │ └─────────┬───────────────┼──────────┘
|
|
21
|
+
└──────┬─────────────────▲──────────┘ │ │
|
|
22
|
+
│ │ │ │
|
|
23
|
+
│ sync:mutate ─────────────────────────────►│ │
|
|
24
|
+
│ sync:ack / sync:nack ◄────────────────────┘ │
|
|
25
|
+
│ sync:delta ◄──────────────────────────────────────────────┘
|
|
26
|
+
│ GET /sync/snapshot (bootstrap + catch-up, HTTP)
|
|
27
|
+
└── POST /sync/mutate (fallback while the socket is down)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
bun install @terreno/syncdb
|
|
34
|
+
# native persistence (optional peer) — use `expo install` so the version matches your SDK:
|
|
35
|
+
bunx expo install expo-sqlite
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Install `expo-sqlite` in the **app**, not only in a library that depends on `@terreno/syncdb`: Expo autolinking walks the app's own dependencies, so a nested copy leaves the ExpoSQLite native module out of the build and native persistence fails to start. Rebuild the native project after adding it — reloading JS is not enough.
|
|
39
|
+
|
|
40
|
+
React bindings live on the `@terreno/syncdb/react` subpath so the main entry stays importable without react.
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
### Backend
|
|
45
|
+
|
|
46
|
+
Apply both required plugins to the schema, add a `sync` config to the modelRouter (three-argument form required), and register `SyncApp` (HTTP routes) plus `RealtimeApp` (socket + `sync:delta` emission):
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import {
|
|
50
|
+
isDeletedPlugin,
|
|
51
|
+
modelRouter,
|
|
52
|
+
OwnerQueryFilter,
|
|
53
|
+
Permissions,
|
|
54
|
+
RealtimeApp,
|
|
55
|
+
SyncApp,
|
|
56
|
+
syncPlugin,
|
|
57
|
+
TerrenoApp,
|
|
58
|
+
} from "@terreno/api";
|
|
59
|
+
|
|
60
|
+
todoSchema.plugin(isDeletedPlugin); // soft delete — required (deletes must remain queryable tombstones)
|
|
61
|
+
todoSchema.plugin(syncPlugin); // stamps a per-stream _syncSeq on every write
|
|
62
|
+
|
|
63
|
+
const todoRouter = modelRouter("/todos", Todo, {
|
|
64
|
+
permissions: {
|
|
65
|
+
create: [Permissions.IsAuthenticated],
|
|
66
|
+
delete: [Permissions.IsOwner],
|
|
67
|
+
list: [Permissions.IsAuthenticated],
|
|
68
|
+
read: [Permissions.IsOwner],
|
|
69
|
+
update: [Permissions.IsOwner],
|
|
70
|
+
},
|
|
71
|
+
preCreate: (body, req) => ({...body, ownerId: (req.user as unknown as UserDocument)?._id}),
|
|
72
|
+
queryFilter: OwnerQueryFilter,
|
|
73
|
+
sync: {
|
|
74
|
+
scope: {type: "owner"}, // stream = todos|owner:{ownerId}
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
new TerrenoApp({userModel: User})
|
|
79
|
+
.register(todoRouter)
|
|
80
|
+
.register(new SyncApp()) // GET /sync/snapshot, POST /sync/mutate, GET /sync/key
|
|
81
|
+
.register(new RealtimeApp()) // Socket.io server; installs sync:subscribe/sync:mutate handlers
|
|
82
|
+
.start();
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Registration is validated at startup: a model with a `sync` config but no `isDeletedPlugin`, no `syncPlugin`, a missing scope field, or a custom scope without a `snapshotFilter` throws with an actionable message. The registry also creates the `{scopeField, _syncSeq}` compound index that snapshot/catch-up queries use.
|
|
86
|
+
|
|
87
|
+
Index requirement: `TerrenoApp.start()` awaits `ensureSyncIndexes()` before listening, which builds both the per-model snapshot indexes and the bookkeeping indexes registering `SyncApp` enqueues (`SyncCounter.stream` and `SyncMutation.mutationId` uniques, the `SyncScopeMove` lookups, `SyncKey.userId`). These are correctness requirements, not just performance: the unique `mutationId` index is what makes duplicate mutation deliveries idempotent, and the unique `stream` index is what keeps the counter upsert race from minting duplicate seqs — so they must not depend on Mongoose `autoIndex`, which is commonly disabled in production. An index-build failure fails startup loudly; hosts that build the Express app without `TerrenoApp.start()` should await `ensureSyncIndexes()` themselves.
|
|
88
|
+
|
|
89
|
+
`RealtimeApp` requires a MongoDB replica set (change streams). Socket auth accepts legacy JWTs by default; add Better Auth sessions with `new RealtimeApp({betterAuth: {auth, userModel: User}})`.
|
|
90
|
+
|
|
91
|
+
### Frontend
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
import {betterAuthAdapter, createSyncDb} from "@terreno/syncdb";
|
|
95
|
+
import {SyncDbProvider, useMutate, useQuery, useSyncStatus} from "@terreno/syncdb/react";
|
|
96
|
+
import {createBetterAuthClient} from "@terreno/rtk";
|
|
97
|
+
|
|
98
|
+
const authClient = createBetterAuthClient({baseURL: "http://localhost:4000"});
|
|
99
|
+
|
|
100
|
+
export const syncDb = createSyncDb({
|
|
101
|
+
authProvider: betterAuthAdapter(authClient),
|
|
102
|
+
baseUrl: "http://localhost:4000",
|
|
103
|
+
collections: ["todos"],
|
|
104
|
+
name: "myapp",
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// After login. Resolves even when offline — the app works local-first and
|
|
108
|
+
// syncs when connectivity returns.
|
|
109
|
+
await syncDb.start();
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
```tsx
|
|
113
|
+
const App = () => (
|
|
114
|
+
<SyncDbProvider client={syncDb}>
|
|
115
|
+
<TodoList />
|
|
116
|
+
</SyncDbProvider>
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
const TodoList: React.FC = () => {
|
|
120
|
+
const todos = useQuery<Todo>("todos", {filter: (t) => !t.completed});
|
|
121
|
+
const {create, update, remove} = useMutate("todos");
|
|
122
|
+
const status = useSyncStatus(); // {isOnline, isSyncing, queuedCount, conflictCount, streams}
|
|
123
|
+
|
|
124
|
+
// create({data: {title: "Milk"}}) applies locally, enqueues in the durable
|
|
125
|
+
// outbox, and replays to the server (socket first, HTTP fallback).
|
|
126
|
+
// update({id, data: {completed: true}}) merges fields; remove({id}) soft-deletes.
|
|
127
|
+
...
|
|
128
|
+
};
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Client API surface
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
const client = createSyncDb({
|
|
135
|
+
name, // persisted database name
|
|
136
|
+
collections, // string[] — synced collections
|
|
137
|
+
authProvider, // {getToken, getUserId, onAuthChange}
|
|
138
|
+
baseUrl?, // server origin (required unless transport + httpChannel injected)
|
|
139
|
+
keyProvider?, // web encryption key provider (default: server-derived via GET /sync/key)
|
|
140
|
+
persisterFactory?, // platform persister override
|
|
141
|
+
transport?, httpChannel?, // test/DI overrides
|
|
142
|
+
reconcileIntervalMs?, // periodic reconcile (default 5 min; 0 disables)
|
|
143
|
+
seqJumpReconcileMinIntervalMs?, // seq-jump reconcile rate limit (default 30s)
|
|
144
|
+
batchSize?, // max mutations per batched drain send (default 50; server caps at 100)
|
|
145
|
+
haltQueueOnConflict?, // conflict policy — see "Conflict handling modes" below (default false)
|
|
146
|
+
onDecryptFailure?, // override the default wipe+re-bootstrap on undecryptable data (web)
|
|
147
|
+
tombstoneRetentionMs?, // client-side tombstone compaction window (default 90 days; 0 disables)
|
|
148
|
+
onAuthRequired?, // fires once per auth-pause episode — prompt for re-login
|
|
149
|
+
wipeOnSignOut?, // signOut() also wipes local data (default false; see "Sign-out" below)
|
|
150
|
+
startAuthRetryAttempts?, // start() attempts at resolving a user (default 3; 1 disables retrying)
|
|
151
|
+
startAuthRetryDelayMs?, // delay between those attempts (default 250ms)
|
|
152
|
+
debug?, // in-memory debug event log — see "Debug log" below (default off)
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
client.start() / client.stop(); // start() is idempotent while already started (a second call is a no-op)
|
|
156
|
+
client.mutate({collection, operation, id?, data?}); // → {mutationId, id}
|
|
157
|
+
client.reconcile(); // HTTP snapshot catch-up for every collection; also runs tombstone compaction on success
|
|
158
|
+
client.forceResync(); // purge every known stream locally and re-bootstrap — see "Forcing a full resync"
|
|
159
|
+
client.replayOutbox(); // drain queued mutations now
|
|
160
|
+
client.resolveConflict({mutationId, strategy: "useServer" | "keepMine"});
|
|
161
|
+
client.retryFailed({entityId}); // re-enable an entity's queued successors after a terminal validation failure
|
|
162
|
+
client.goOffline() / client.goOnline(); // simulated outage — see "Simulated offline" below
|
|
163
|
+
client.signOut(); // explicit sign-out teardown (wipes only with wipeOnSignOut)
|
|
164
|
+
client.getSyncStatus(); // {isOnline, isSyncing, queuedCount, conflictCount, failedCount, blockedEntities,
|
|
165
|
+
// paused?, draining, sentThisDrain, totalThisDrain, streams, persistence}
|
|
166
|
+
// persistence: "durable" | "memory" | "error" — see "Encryption at rest" below
|
|
167
|
+
client.onStatusChange(cb);
|
|
168
|
+
client.store / client.outbox; // low-level access
|
|
169
|
+
client.debug; // the debug log when `debug` is enabled, else undefined
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
`start()` needs an authenticated user, and it is normally called right after a login completes — so a `null` from `authProvider.getUserId()` is usually a transient session-fetch race rather than a real logged-out state. It therefore retries up to `startAuthRetryAttempts` times (default 3, `startAuthRetryDelayMs` apart) before rejecting with "requires an authenticated user". Set `startAuthRetryAttempts: 1` to fail fast.
|
|
173
|
+
|
|
174
|
+
React hooks (`@terreno/syncdb/react`): `SyncDbProvider`, `useSyncDbClient`, `useEntity(collection, id)`, `useQuery(collection, {filter?, sort?, includeDeleted?})`, `useEntityIds(collection, options?)`, `useMutate(collection)`, `useSyncStatus()`, `useConflicts()`, `useSyncDebugLog()`.
|
|
175
|
+
|
|
176
|
+
**Prefer `useEntityIds` for large lists.** It takes the same options as `useQuery` but returns only the ordered ids, with an array whose identity changes only when the id membership or order changes. Paired with a per-row `useEntity`, a field update re-renders that one row instead of the whole list:
|
|
177
|
+
|
|
178
|
+
```tsx
|
|
179
|
+
const ids = useEntityIds<Todo>("todos", {filter: (t) => !t.completed, sort: byCreatedDesc});
|
|
180
|
+
return <>{ids.map((id) => <TodoRow id={id} key={id} />)}</>; // TodoRow calls useEntity("todos", id)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Public API surface
|
|
184
|
+
|
|
185
|
+
The package has three entry points, and only what they export is API:
|
|
186
|
+
|
|
187
|
+
- `@terreno/syncdb` — the client (`createSyncDb`), protocol/status/conflict types, the Better Auth adapter, key providers and codecs, persister factories, the transport/HTTP-channel constructors (for DI), `wipeLocalData`, `generateMutationId`, `listConflicts`, and `OUTBOX_TABLE` for inspecting queued mutations via `client.store.raw.getTable(...)`.
|
|
188
|
+
- `@terreno/syncdb/react` — the hooks above plus `SyncDbProvider` (a separate subpath because `react` is an optional peer dependency).
|
|
189
|
+
- `@terreno/syncdb/testing` — test doubles (`createFakeTransport`), kept out of production bundles.
|
|
190
|
+
|
|
191
|
+
Everything else under `src/` is internal and can change in a patch release. In particular the cursor mutators, outbox/conflict writers, raw row shapes, the IndexedDB helpers, and the debug broadcast bridge are deliberately unexported: writing to a reserved table behind the client's back breaks the invariants replay and reconcile depend on.
|
|
192
|
+
|
|
193
|
+
## Client operations
|
|
194
|
+
|
|
195
|
+
### Simulated offline
|
|
196
|
+
|
|
197
|
+
`goOffline()` disconnects the transport and pauses replay, reconcile, and the periodic timer while keeping the resolved user and persistence alive — mutations keep applying locally and queueing durably, and `getSyncStatus().isOnline` reports `false`. `goOnline()` reconnects, resubscribes, and restarts the timer; the reconnect status event then triggers a reconcile and drains the outbox. This is how the example app's dev panel and the e2e suites exercise offline behavior without touching the real network.
|
|
198
|
+
|
|
199
|
+
### Sign-out
|
|
200
|
+
|
|
201
|
+
`signOut()` is the explicit, host-app-initiated teardown: it does everything `stop()` does (disconnect, clear listeners and timers, flush and destroy the persister) and also clears the in-memory current-user pointer. It wipes local data **only** when `createSyncDb` was given `wipeOnSignOut: true`. That is deliberate (INV-2): a bare logout or a 401 never wipes, because unsynced local mutations belong to the user who may sign back in moments later. Local data is otherwise only wiped on a confirmed *different*-user login. Call `start()` again to sync as the next signed-in user.
|
|
202
|
+
|
|
203
|
+
### Forcing a full resync
|
|
204
|
+
|
|
205
|
+
`forceResync()` purges every known stream locally and re-bootstraps from cursor 0, without touching the outbox or recorded conflicts. Use it when a device is suspected to have diverged (a support "resync my data" button) rather than as routine catch-up — `reconcile()` is the incremental path. It re-discovers stream membership first, since a stale local set is itself one of the ways a device diverges. The result reports what happened instead of failing silently:
|
|
206
|
+
|
|
207
|
+
```typescript
|
|
208
|
+
const {ok, reason, streams, purged, repaired} = await client.forceResync();
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
| `reason` (only when `ok: false`) | Meaning |
|
|
212
|
+
|---|---|
|
|
213
|
+
| `noHttpChannel` | No HTTP channel is configured (no `baseUrl` and none injected). |
|
|
214
|
+
| `offline` | The client is in a simulated outage (`goOffline()`). |
|
|
215
|
+
| `authPaused` | Replay/reconcile are auth-paused, or the resync itself hit a 401. Sign in again. |
|
|
216
|
+
| `noStreams` | The server reported no streams for this user and there was no local set to fall back on. Stable — retrying reproduces it. |
|
|
217
|
+
| `superseded` | A `stop()`/`start()` cycle or a different-user login took over mid-resync, so the pass abandoned its work rather than writing into a store that now belongs to another lifecycle or user. Retry once things settle. |
|
|
218
|
+
|
|
219
|
+
`purged`/`repaired` are still meaningful on a `superseded` result: they report the work done before the abort.
|
|
220
|
+
|
|
221
|
+
### Debug log
|
|
222
|
+
|
|
223
|
+
`createSyncDb({debug: true})` (or `{debug: {capacity}}`) enables an in-memory ring buffer of sync events — local mutations, acks/nacks, inbound deltas, conflicts, reconcile/replay passes, connectivity changes. It is off by default with zero overhead; when on, `client.debug.snapshot()` returns a plain serializable object (the shape a future MCP introspection tool returns), and `useSyncDebugLog()` exposes `{events, stats, log, clear}` for a live debugger UI (see `example-frontend/app/syncdb-debug.tsx`). On the web the log is mirrored across windows/tabs over a `BroadcastChannel`, so a debugger opened in a second window sees the app window's local mutations; the bridge is closed by `stop()`/`signOut()` and re-opened by `start()`.
|
|
224
|
+
|
|
225
|
+
## Batched replay & stop-the-line policy
|
|
226
|
+
|
|
227
|
+
Queued mutations drain in contiguous chunks (≤ `batchSize`, default 50) over `POST /sync/mutate/batch` (or `sync:mutateBatch` when the socket is connected) rather than one request per mutation — an offline session of hundreds of edits costs `~N/batchSize` round-trips instead of `N`. Ordering is never sacrificed for this: a chunk carries at most one mutation per entity (a second mutation for an entity already in the chunk cuts it short — the next chunk picks it up once the first has acked and the send-time `baseVersion` refresh has run), and the server applies a batch strictly in array order, stopping at the first non-ack (results shorter than the request means the client re-sends the untouched tail — safe by idempotency). If the server or transport doesn't support batching (HTTP 404, or a socket that never acknowledges `sync:mutateBatch`), the client falls back to single-mutation sends in the same global order and re-probes batch support on the next reconnect.
|
|
228
|
+
|
|
229
|
+
Not every failure is handled the same way — the table below is the client's stop-the-line policy:
|
|
230
|
+
|
|
231
|
+
| Outcome | Policy |
|
|
232
|
+
|---|---|
|
|
233
|
+
| `error` (transient), transport failure/timeout, `unauthorized` | **Halts the whole drain.** Jittered backoff (or auth-pause) applies; nothing after it sends until the retry/re-auth. |
|
|
234
|
+
| `rate_limited` | Treated **exactly like a transport failure**: back to `queued` with the same unlimited jittered backoff (the server's `retryAfterMs`, when present, is a floor on that backoff), never counted against the error-nack budget (`errorNackCount`). A rate limit is the server asking the client to slow down — it must never look like a durable-data error or push the client toward terminal `failed`. Halts the whole drain, same as a transport failure. |
|
|
235
|
+
| `conflict` | **Blocks only that entity** by default: the entity's later queued mutations are skipped (stay `queued`, budgets untouched) until the user resolves the conflict via `resolveConflict`; other entities keep draining. Set `haltQueueOnConflict: true` to escalate a conflict into a whole-drain halt instead (for apps with cross-entity ordering dependencies where an unresolved conflict must not let anything past it). |
|
|
236
|
+
| `validation` | Terminal for that mutation (existing `markFailed` behavior) and its entity's queued successors are skipped-and-surfaced the same way a conflict blocks — a successor built on a rejected write is likely also invalid. Re-enable them with `client.retryFailed({entityId})` once the underlying issue is fixed. A block with no queued successor left (e.g. its failed row aged out via `prune()`) is garbage-collected automatically — a brand-new mutation for that entity is never quarantined forever. |
|
|
237
|
+
|
|
238
|
+
### Conflict handling modes
|
|
239
|
+
|
|
240
|
+
- **Default (`haltQueueOnConflict: false`)** — per-entity blocking. A conflict on one entity never stalls unrelated entities; only that entity's own queue is paused pending `resolveConflict`. Best for apps where entities are largely independent (e.g. a todo list).
|
|
241
|
+
- **`haltQueueOnConflict: true`** — whole-drain halt. Any conflict stops the ENTIRE drain until it's resolved, even for unrelated entities. Choose this when later-queued mutations (in any entity/collection, or across collections via foreign-key-style references) may depend on assumptions invalidated by the conflicting write, and blindly continuing risks compounding the problem. This is the stronger guarantee when your data model has cross-collection references (e.g. a todo referencing a project id) and you want ordering correctness to trump availability of unrelated entities during a conflict.
|
|
242
|
+
|
|
243
|
+
`client.getSyncStatus().blockedEntities` reports how many distinct entities are currently blocked (conflict or skipped validation failure) so the UI can surface it (see `SyncStatusBanner`'s failed/conflict badges).
|
|
244
|
+
|
|
245
|
+
### Cross-collection reference blocking (per-entity mode)
|
|
246
|
+
|
|
247
|
+
Under the default per-entity blocking mode, a conflict or validation failure on one entity does not, by itself, stop mutations for *unrelated* entities. But apps commonly have cross-collection references — e.g. creating a project P and then a todo T with `{projectId: P}` — where T is meaningless if P never lands on the server. To keep that case safe without requiring `haltQueueOnConflict: true` for the whole app, the coordinator also blocks a queued mutation whose parsed `args` contain, anywhere (recursively through nested objects/arrays), a string that exactly equals the entity id of a currently-blocked entity belonging to the same user. So if P conflicts, T (referencing P's id) stays `queued` and is never sent until P's conflict is resolved — even though T's own entity has no conflict of its own. This blocking is recomputed fresh on every drain pass from current block state (never a persisted dependency graph), so resolving P via `resolveConflict`/`retryFailed` naturally unblocks T on the next drain. It is intentionally conservative — a false-positive block (a string that happens to match a blocked id but isn't really a reference) is safe; a false negative is not.
|
|
248
|
+
|
|
249
|
+
If your data model has enough cross-collection references that you want ordering guaranteed for ALL entities (not just ones whose args happen to reference a blocked id), use `haltQueueOnConflict: true` instead — see "Conflict handling modes" above.
|
|
250
|
+
|
|
251
|
+
## Stream scoping
|
|
252
|
+
|
|
253
|
+
Streams are the unit of ordered delivery and cursor resumption, keyed `{collection}|{scope}` — multi-tenant by default:
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
sync: {scope: {type: "owner"}} // todos|owner:{ownerId} (field defaults to "ownerId")
|
|
257
|
+
sync: {scope: {type: "owner", field: "userId"}} // todos|owner:{userId}
|
|
258
|
+
sync: {scope: {type: "tenant", field: "organizationId"}} // todos|tenant:{orgId}
|
|
259
|
+
sync: {scope: {type: "broadcast"}} // todos|all
|
|
260
|
+
sync: {
|
|
261
|
+
scope: (doc) => String(doc.workspaceId), // todos|custom:{value}
|
|
262
|
+
snapshotFilter: (user) => ({workspaceId: {$in: [...]}}), // REQUIRED for custom scopes
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
- **Owner** streams are always keyed by the authenticated socket's own user id — a client-supplied id never selects the stream.
|
|
267
|
+
- **Tenant** (and custom) subscriptions resolve the user's memberships via `SyncAppOptions.getUserScopes`:
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
new SyncApp({
|
|
271
|
+
getUserScopes: async (user, entry) => {
|
|
272
|
+
const memberships = await Membership.find({userId: user.id});
|
|
273
|
+
return memberships.map((m) => String(m.organizationId));
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
- **`snapshotFilter`** is the server-side query restricting `GET /sync/snapshot` to the caller's documents. It is derived automatically for owner (`{field: user.id}`) and tenant (`{field: {$in: getUserScopes(...)}}`) scopes; custom resolver scopes must supply one (a stream function cannot be inverted into a Mongo query) — validated at registration.
|
|
279
|
+
- **`responseHandler`** on the sync config sanitizes payloads for snapshots and deltas, falling back to the modelRouter `responseHandler`, then the document's `toJSON`.
|
|
280
|
+
|
|
281
|
+
Scope changes (a doc moves owner/tenant) are handled at write time: `syncPlugin` stamps `_syncPrevStream`, and the change-stream watcher emits a tombstone delta to the previous stream plus a create delta to the new one.
|
|
282
|
+
|
|
283
|
+
## Write-path restrictions
|
|
284
|
+
|
|
285
|
+
`syncPlugin` stamps `_syncSeq` on: `save`, `insertMany`, `updateOne`, `findOneAndUpdate`, `replaceOne`, `findOneAndReplace`. These paths **throw** on sync-registered models:
|
|
286
|
+
|
|
287
|
+
- `updateMany`, `deleteMany` — multi-document writes cannot stamp per-document seqs. Loop per document instead.
|
|
288
|
+
- `deleteOne` (query and document forms), `findOneAndDelete` — hard deletes are invisible to tombstone catch-up. Use soft delete (`doc.deleted = true; await doc.save()`).
|
|
289
|
+
- `Model.bulkWrite` **bypasses Mongoose middleware entirely**, so the plugin cannot guard it from the schema. `registerSync` instead replaces the static on synced models with one that throws, so the restriction is enforced rather than merely documented. Loop per document instead.
|
|
290
|
+
|
|
291
|
+
Sequencing guarantees: validation failures never consume a seq (the claim happens post-validation); the claim joins the caller's session when one is present, so caller-managed transactions get counter+write atomicity. A rare write failure after a claim burns a seq, which clients treat as a benign gap.
|
|
292
|
+
|
|
293
|
+
## Sync protocol
|
|
294
|
+
|
|
295
|
+
### HTTP (mounted by `SyncApp`, all authenticated)
|
|
296
|
+
|
|
297
|
+
| Endpoint | Purpose | Auth |
|
|
298
|
+
|---|---|---|
|
|
299
|
+
| `GET /sync/snapshot?collection=&cursor=&limit=` | Bootstrap + catch-up. Returns `{entities: [{id, data, seq, deleted}], cursor, hasMore}`. `cursor=0` = full snapshot (legacy docs without `_syncSeq` arrive in the first page with seq 0). Default page 100, max 100. | Model `list` permissions + server-enforced scope filter |
|
|
300
|
+
| `POST /sync/mutate` | HTTP fallback for outbox replay (same handler as the socket channel). Body: `{mutationId, collection, operation, id?, data?, baseVersion?}`. Returns `{ack}` or `{nack}` with status 409 (conflict), 403 (unauthorized), 422 (validation), 429 (rate_limited, carries `retryAfterMs`), 500 (error). | modelRouter create/update/delete write path |
|
|
301
|
+
| `POST /sync/mutate/batch` | HTTP fallback for batched outbox replay. Body: `{mutations: SyncMutateRequest[]}` (max 100; intra-batch duplicate `mutationId`s rejected up front). Returns `{results: ({type:"ack",ack}\|{type:"nack",nack})[]}` — applied strictly in array order, stopping at the first non-ack (a shorter `results` array than the request means everything after it was never attempted). | modelRouter create/update/delete write path, per mutation |
|
|
302
|
+
| `GET /sync/key` | Caller's per-user key material for the server key provider (32 random bytes, base64; created on first call). | Own key only |
|
|
303
|
+
|
|
304
|
+
### Socket events (on the `RealtimeApp` Socket.io server)
|
|
305
|
+
|
|
306
|
+
| Event | Direction | Payload |
|
|
307
|
+
|---|---|---|
|
|
308
|
+
| `sync:subscribe` / `sync:unsubscribe` | client → server | `{collections: string[]}` — server resolves the user's streams from scope config (+ `getUserScopes`) and joins `sync:{stream}` rooms |
|
|
309
|
+
| `sync:subscribed` | server → client | `{collection, streams}` |
|
|
310
|
+
| `sync:error` | server → client | `{collection, message}` — per-collection subscribe failure (unknown collection, permission denied, missing resolver, cap exceeded) |
|
|
311
|
+
| `sync:delta` | server → client | `{collection, id, method, data?, seq, stream, deleted?}` — emitted by the change-stream watcher |
|
|
312
|
+
| `sync:mutate` | client → server | `{mutationId, collection, operation, id?, data?, baseVersion?}` (+ optional Socket.io ack callback) |
|
|
313
|
+
| `sync:ack` | server → client | `{mutationId, id, seq}` |
|
|
314
|
+
| `sync:nack` | server → client | `{mutationId, code: "conflict"\|"unauthorized"\|"validation"\|"error"\|"rate_limited", serverDoc?, serverSeq?, message?, retryAfterMs?}` — `rate_limited` (with `retryAfterMs`, the remaining window in ms) is never terminal: the client requeues and retries with unlimited backoff, exactly like a transport failure. |
|
|
315
|
+
| `sync:mutateBatch` | client → server | `{mutations: SyncMutateRequest[]}` (Socket.io ack callback carries `{results}`, same contract as the HTTP batch route) — a server with no handler for this event never invokes the ack callback, which the client treats as "batching unsupported" after a short grace timeout and falls back to single `sync:mutate` sends. |
|
|
316
|
+
|
|
317
|
+
Limits: 50 collection subscriptions per socket; 100 `sync:mutate` per second per socket, shared with `sync:mutateBatch` (each mutation in a batch counts individually against the same window); batches capped at 100 mutations.
|
|
318
|
+
|
|
319
|
+
### Conflicts and idempotency
|
|
320
|
+
|
|
321
|
+
The client sends `baseVersion` = the `_syncSeq` it last saw for the doc; a mismatch with the current `_syncSeq` yields a `conflict` nack carrying the canonical server doc + seq. The conflict lands in the local `_conflicts` table and surfaces through `useConflicts()`; resolve with `useServer` (accept the server doc) or `keepMine` (re-enqueue with a fresh baseVersion).
|
|
322
|
+
|
|
323
|
+
`useServer` writes a **tombstone** rather than the server payload when the server side of the conflict is a deletion — either the nack set `serverDeleted`, or it carried no server document at a non-zero `serverSeq` (deleted, hard-deleted, or moved out of this client's scope). Without that, accepting the server side would leave a live local row holding `null` data that lists and renders forever. A conflict with no server document at seq **0** is the opposite case — "server state unknown", the shape startup recovery writes for a conflicted outbox row whose nack was never seen — and never deletes local data. Symmetrically, when the server does still have the document, `useServer` resurrects a local tombstone (a delete that lost the conflict), so accepting the server side always leaves the local row matching it.
|
|
324
|
+
|
|
325
|
+
Every mutation is idempotent: the handler atomically claims a `SyncMutation` ledger row (unique `mutationId`) before applying, so a re-sent mutation (lost ack, socket retry racing the HTTP fallback) reads back the recorded outcome instead of double-applying.
|
|
326
|
+
|
|
327
|
+
### Rejected mutations and entity repair
|
|
328
|
+
|
|
329
|
+
A mutation the server rejects terminally (a `validation` nack, or an `error` nack that exhausts its retry budget) leaves optimistic local data the server never accepted. Since the entity's `seq` never moves in that case, snapshot reconcile has nothing to send and would skip it forever, so the terminal path instead:
|
|
330
|
+
|
|
331
|
+
1. marks the entity in `_needsRepair`,
|
|
332
|
+
2. releases its `pendingMutationId` (a failed mutation never replays, and leaving the lock set would block every future delta for that entity),
|
|
333
|
+
3. fetches canonical server state for it (`POST /sync/entities`) and overwrites the local row.
|
|
334
|
+
|
|
335
|
+
The resulting semantics: a rejected **update** converges back to the server's document. A rejected **create** has no server state to converge to — the repair fetch returns nothing, the mark is cleared (so later reconciles do not re-fetch it forever), and the phantom row is removed by the unknown-stream purge, which deletes rows with no stream provenance and no pending mutation. If the repair fetch itself fails (offline, 5xx), the mark stays and the next reconcile retries it.
|
|
336
|
+
|
|
337
|
+
`start()` also sweeps entities whose `pendingMutationId` names a mutation with **no `_outbox` row at all** (pruned, wiped, or lost to a partially-persisted store) and clears the lock. Such a row is otherwise frozen for good: the delta applier skips it for pending protection and repair refuses to overwrite it, so nothing else could ever release it.
|
|
338
|
+
|
|
339
|
+
## Encryption at rest (web)
|
|
340
|
+
|
|
341
|
+
Web persistence is **encrypted by default**: the store content is AES-256-GCM encrypted via Web Crypto before it touches IndexedDB. Key management is a pluggable `KeyProvider`:
|
|
342
|
+
|
|
343
|
+
- `createServerKeyProvider({appName, fetchKeyMaterial})` (**the default**: `createSyncDb` wires it automatically to `GET /sync/key` through its authenticated HTTP channel): fetches per-user key material, derives a non-extractable AES-256-GCM key via HKDF-SHA256 (salt = `{appName}:{userId}`), and caches the derived CryptoKey in IndexedDB so offline cold starts still decrypt. Server rotation of key material makes decryption fail — the client wipes local data, re-stamps the schema version, and runs a full re-bootstrap by default (always preceded by a `console.warn`); pass `onDecryptFailure` in `createSyncDb`'s config to override that default (e.g. prompt the user before wiping) instead.
|
|
344
|
+
- `createLocalKeyProvider()`: a random non-extractable CryptoKey generated on-device and cached in IndexedDB. No server dependency and no server-side copy of the key — strictly stronger for the at-rest case, at the cost of no server-driven rotation/revocation.
|
|
345
|
+
|
|
346
|
+
A storage **read** error (IndexedDB itself throwing — unavailable, blocked, or corrupted) is a distinct failure mode from "no data yet" or "undecryptable data": the client leaves the persisted blob untouched (no autosave-over) and surfaces `persistence: "error"` on `SyncStatus` instead of wiping. When `globalThis.indexedDB` is unavailable entirely (private-browsing modes that disable it, a locked-down embedded webview), the web persister factory falls back to in-memory persistence for the session (warns once) and reports `persistence: "memory"`.
|
|
347
|
+
|
|
348
|
+
```typescript
|
|
349
|
+
import {createLocalKeyProvider} from "@terreno/syncdb";
|
|
350
|
+
|
|
351
|
+
// Default: server-derived key, wired automatically — nothing to configure.
|
|
352
|
+
const syncDb = createSyncDb({name: "myapp", collections, authProvider, baseUrl});
|
|
353
|
+
|
|
354
|
+
// Opt out of the server-side key copy with a device-local key:
|
|
355
|
+
const localSyncDb = createSyncDb({
|
|
356
|
+
name: "myapp",
|
|
357
|
+
collections,
|
|
358
|
+
authProvider,
|
|
359
|
+
baseUrl,
|
|
360
|
+
keyProvider: createLocalKeyProvider(),
|
|
361
|
+
});
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
**Threat model (stated explicitly):** the web encryption defends against **at-rest disk inspection of IndexedDB** (stolen/imaged device, backup scraping) and against a **stale store being readable after user switch** (per-user keys + wipe-on-user-change). It does **not** defend against XSS or any code executing on the origin — a non-extractable CryptoKey can still be *used* to decrypt in place — and with the server key provider the server can reconstruct any user's key (that is the trade for rotation/revocation; choose the local key provider where that is unacceptable). Server-side data is protected by MongoDB/infra controls, not this layer.
|
|
365
|
+
|
|
366
|
+
Native relies on the OS app sandbox: the expo-sqlite store is plaintext by design.
|
|
367
|
+
|
|
368
|
+
## Local store layout
|
|
369
|
+
|
|
370
|
+
One TinyBase `MergeableStore` per `{app, userId}` (wiped and re-bootstrapped on user change, or on a schema-version mismatch — see below):
|
|
371
|
+
|
|
372
|
+
```
|
|
373
|
+
tables:
|
|
374
|
+
{collection} → rowId = doc _id; cells: data (JSON string), seq, deleted, deletedAt,
|
|
375
|
+
pendingMutationId
|
|
376
|
+
_outbox → rowId = mutationId; cells: collection, operation, entityId, args (JSON),
|
|
377
|
+
baseVersion?, status (queued|inFlight|acked|conflicted|failed),
|
|
378
|
+
attemptCount, userId, createdAt, enqueueOrder
|
|
379
|
+
_cursors → rowId = stream; cells: seq, updatedAt, snapshotSeq, bootstrapped
|
|
380
|
+
_conflicts → rowId = mutationId; cells: collection, entityId, localData, serverData,
|
|
381
|
+
serverSeq, serverDeleted, dismissed
|
|
382
|
+
values: schemaVersion, lastUserId, outboxMaxEnqueueOrder
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
The outbox replays FIFO over the socket (HTTP fallback while disconnected), with per-user isolation: queued mutations record `userId` and replay skips on mismatch.
|
|
386
|
+
|
|
387
|
+
A stream's `_cursors` row tracks two independent progress marks. `seq` is the highest seq applied locally and is advanced by both snapshot pages and live deltas; `snapshotSeq` is how far the snapshot endpoint has actually been paged, and only bootstrap advances it. An unfinished bootstrap resumes from `snapshotSeq`, never from `seq`: a live delta at the stream head can overtake `seq` while bootstrap is still on page 3 of 40, and resuming from `seq` would leave every seq in between permanently unreachable (no later reconcile would ask for it again). Once a snapshot pass reaches the head the stream is marked `bootstrapped` and catch-up resumes from `seq`, since deltas carry their own data.
|
|
388
|
+
|
|
389
|
+
### Schema versioning
|
|
390
|
+
|
|
391
|
+
`SYNC_SCHEMA_VERSION` (`storage/schema.ts`) is stamped into the store's `schemaVersion` value on every `start()`. If a persisted store's stamped version doesn't match the running client's, the client treats it as a schema migration (not an auth event): wipe all local data, re-stamp the current version, and run a full snapshot re-bootstrap before `start()` resolves. Bump `SYNC_SCHEMA_VERSION` only when a table/cell shape change isn't safely backward-compatible (a new cell with a schema default, for example, does not need a bump).
|
|
392
|
+
|
|
393
|
+
### Client-side tombstone compaction
|
|
394
|
+
|
|
395
|
+
Deleted entities are kept locally as tombstones (`deleted: true`) with a `deletedAt` timestamp stamped the moment the tombstone is first applied (via a mutation, a delta, or a snapshot page). After each successful `reconcile()`, tombstones older than `tombstoneRetentionMs` (`createSyncDb` config, default 90 days) are deleted outright. Keep this in sync with the server's own tombstone retention (compaction script in `@terreno/api`) — compacting locally before the server's retention window elapses risks a client permanently missing a delete it hasn't converged on yet. Set `tombstoneRetentionMs: 0` to disable.
|
|
396
|
+
|
|
397
|
+
### Why MergeableStore (and the Yjs door)
|
|
398
|
+
|
|
399
|
+
`MergeableStore` is TinyBase's per-cell LWW CRDT (hybrid logical clocks) with a different on-disk format from the plain `Store`. Adopting it from day one avoids a per-device data migration later, and keeps the door open to a Yjs CRDT backend for collaborative structures (rich text) through the same persister/transport abstractions — without implementing Yjs now. The cost is roughly 2× storage overhead for the CRDT metadata, accepted for that readiness.
|
|
400
|
+
|
|
401
|
+
## Gap handling
|
|
402
|
+
|
|
403
|
+
Stream seqs are **not** contiguous from any one client's perspective — permission-filtered deltas legitimately skip numbers, and a failed write can burn a seq. Convergence therefore never depends on a gap proof:
|
|
404
|
+
|
|
405
|
+
- A **seq jump** in an incoming delta is treated as a *hint*: it triggers an HTTP reconcile (snapshot catch-up from the stream cursor), rate-limited to once per 30s per stream (`seqJumpReconcileMinIntervalMs`).
|
|
406
|
+
- Every **reconnect** triggers a reconcile plus an outbox replay.
|
|
407
|
+
- A **periodic reconcile** (default every 5 minutes, `reconcileIntervalMs`; 0 disables) guarantees convergence even for deltas missed with no observable jump.
|
|
408
|
+
|
|
409
|
+
Catch-up is a plain indexed query (`_syncSeq > cursor`, tombstones included), safe under concurrent writes because a doc's seq only ever increases.
|
|
410
|
+
|
|
411
|
+
## Known limitations
|
|
412
|
+
|
|
413
|
+
- **Synced models need a String `_id`** (or clients must mint ObjectId-format ids): offline clients generate entity ids (UUIDs) locally and the mutation channel writes them through as `_id`. A default ObjectId `_id` would cast-fail every client-side create. Declare `_id: {type: String, ...}` on synced schemas.
|
|
414
|
+
- **Multi-tab web**: two tabs of the same user share one IndexedDB blob; concurrent persister saves are last-writer-wins at the blob level and can drop the other tab's queued outbox rows. Single-writer coordination (Web Locks) is not implemented yet — avoid relying on offline writes from multiple simultaneous tabs.
|
|
415
|
+
- **`Model.bulkWrite` is unavailable on synced models**: it skips Mongoose middleware, so it can never stamp seqs. `registerSync` replaces the static with one that throws — bulk updates to a synced collection have to loop per document.
|
|
416
|
+
- **Native plaintext by design**: no SQLCipher; the OS sandbox is deemed sufficient.
|
|
417
|
+
- **Whole-store persistence**: each save serializes and (on web) encrypts the full store — cost scales with store size, not change size. Bound it by scoping which collections sync; saves are debounced.
|
|
418
|
+
- **`realtime` + `sync` coexistence**: a model may enable both (distinct events, `sync` vs `sync:delta`, so clients never double-apply), at the cost of double emission work. Treat `realtime` as deprecated for a model once `sync` is on.
|
|
419
|
+
- **Seq counter write amplification**: every synced write does an atomic `$inc` on a per-stream counter doc. Acceptable at current scale; Redis-based counters are the documented upgrade path.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AuthProvider } from "../types";
|
|
2
|
+
import type { BetterAuthClientLike } from "./types";
|
|
3
|
+
/** Default polling cadence when the client exposes no session subscription. */
|
|
4
|
+
export declare const DEFAULT_AUTH_POLL_INTERVAL_MS = 5000;
|
|
5
|
+
export interface BetterAuthAdapterOptions {
|
|
6
|
+
/** Polling cadence for the fallback watcher (default {@link DEFAULT_AUTH_POLL_INTERVAL_MS}). */
|
|
7
|
+
pollIntervalMs?: number;
|
|
8
|
+
/** Interval scheduler, injectable for deterministic tests (default global setInterval). */
|
|
9
|
+
setIntervalFn?: (handler: () => void, ms: number) => unknown;
|
|
10
|
+
/** Interval canceller matching `setIntervalFn` (default global clearInterval). */
|
|
11
|
+
clearIntervalFn?: (handle: unknown) => void;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Adapt a Better Auth client to syncdb's {@link AuthProvider} contract.
|
|
15
|
+
* Tokens/user ids are read per call via `getSession()` (never cached, so
|
|
16
|
+
* Better Auth session refresh is picked up transparently); auth changes are
|
|
17
|
+
* delivered through the client's nanostore session atom when available, with
|
|
18
|
+
* an injectable polling fallback otherwise. All read errors degrade to null —
|
|
19
|
+
* a broken auth client behaves like "signed out", never a crash.
|
|
20
|
+
*/
|
|
21
|
+
export declare const betterAuthAdapter: (authClient: BetterAuthClientLike, options?: BetterAuthAdapterOptions) => AuthProvider;
|
|
22
|
+
//# sourceMappingURL=betterAuthAdapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"betterAuthAdapter.d.ts","sourceRoot":"","sources":["../../src/auth/betterAuthAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,UAAU,CAAC;AAC3C,OAAO,KAAK,EAAC,oBAAoB,EAA4B,MAAM,SAAS,CAAC;AAE7E,+EAA+E;AAC/E,eAAO,MAAM,6BAA6B,OAAQ,CAAC;AAEnD,MAAM,WAAW,wBAAwB;IACvC,gGAAgG;IAChG,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,2FAA2F;IAC3F,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC;IAC7D,kFAAkF;IAClF,eAAe,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;CAC7C;AAiBD;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAC5B,YAAY,oBAAoB,EAChC,UAAS,wBAA6B,KACrC,YA4KF,CAAC"}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/** Default polling cadence when the client exposes no session subscription. */
|
|
2
|
+
export const DEFAULT_AUTH_POLL_INTERVAL_MS = 5000;
|
|
3
|
+
/**
|
|
4
|
+
* Unwrap `getSession()` results: Better Auth returns a `{data}` envelope, some
|
|
5
|
+
* wrappers return the payload directly, and signed-out states are null-ish.
|
|
6
|
+
*/
|
|
7
|
+
const unwrapSession = (result) => {
|
|
8
|
+
if (!result || typeof result !== "object") {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
if ("data" in result) {
|
|
12
|
+
const data = result.data;
|
|
13
|
+
return data && typeof data === "object" ? data : null;
|
|
14
|
+
}
|
|
15
|
+
return result;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Adapt a Better Auth client to syncdb's {@link AuthProvider} contract.
|
|
19
|
+
* Tokens/user ids are read per call via `getSession()` (never cached, so
|
|
20
|
+
* Better Auth session refresh is picked up transparently); auth changes are
|
|
21
|
+
* delivered through the client's nanostore session atom when available, with
|
|
22
|
+
* an injectable polling fallback otherwise. All read errors degrade to null —
|
|
23
|
+
* a broken auth client behaves like "signed out", never a crash.
|
|
24
|
+
*/
|
|
25
|
+
export const betterAuthAdapter = (authClient, options = {}) => {
|
|
26
|
+
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_AUTH_POLL_INTERVAL_MS;
|
|
27
|
+
const setIntervalFn = options.setIntervalFn ??
|
|
28
|
+
((handler, ms) => setInterval(handler, ms));
|
|
29
|
+
const clearIntervalFn = options.clearIntervalFn ??
|
|
30
|
+
((handle) => clearInterval(handle));
|
|
31
|
+
/**
|
|
32
|
+
* Read the session, distinguishing "read failed" from "signed out". Both surface as
|
|
33
|
+
* a null session, but only the latter is an identity change — see
|
|
34
|
+
* {@link classifyEmission}.
|
|
35
|
+
*/
|
|
36
|
+
const readSessionResult = async () => {
|
|
37
|
+
try {
|
|
38
|
+
return { ok: true, session: unwrapSession(await authClient.getSession()) };
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return { ok: false, session: null };
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const readSession = async () => {
|
|
45
|
+
return (await readSessionResult()).session;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* One-shot silent refresh consumed by the client's A4 auth-pause pipeline:
|
|
49
|
+
* re-fetch the session (Better Auth clients transparently refresh/renew the
|
|
50
|
+
* underlying token on `getSession()` when the client library supports it)
|
|
51
|
+
* and report whether a usable token now exists. Never throws — a failed
|
|
52
|
+
* refresh just means the pause surfaces to the app as usual.
|
|
53
|
+
*/
|
|
54
|
+
const refresh = async () => {
|
|
55
|
+
const session = await readSession();
|
|
56
|
+
return Boolean(session?.session?.token);
|
|
57
|
+
};
|
|
58
|
+
const getToken = async () => {
|
|
59
|
+
const session = await readSession();
|
|
60
|
+
return session?.session?.token ?? null;
|
|
61
|
+
};
|
|
62
|
+
const getUserId = async () => {
|
|
63
|
+
const session = await readSession();
|
|
64
|
+
return session?.user?.id ?? null;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Identity snapshot used by the polling fallback to detect auth changes. Returns null
|
|
68
|
+
* when the read itself failed, so a transient network error is never sampled as a
|
|
69
|
+
* signed-out identity (the same phantom-logout hazard {@link classifyEmission} guards).
|
|
70
|
+
*/
|
|
71
|
+
const readAuthKey = async () => {
|
|
72
|
+
const { ok, session } = await readSessionResult();
|
|
73
|
+
if (!ok) {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
return `${session?.user?.id ?? ""}|${session?.session?.token ?? ""}`;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Classify a session-atom emission for the subscribe path:
|
|
80
|
+
* - "pending": an in-flight fetch state (`isPending: true`) or a FAILED read
|
|
81
|
+
* (`error` set) — never a change;
|
|
82
|
+
* - `{key}`: a parseable session envelope reduced to its identity (userId|token);
|
|
83
|
+
* - null: an opaque value the adapter cannot interpret.
|
|
84
|
+
*
|
|
85
|
+
* A failed read is deliberately indistinguishable from "pending" here. Better Auth
|
|
86
|
+
* emits `{data: null, error}` when a get-session fetch fails, which is shaped exactly
|
|
87
|
+
* like a signed-out session — forwarding it would report a PHANTOM logout, and the
|
|
88
|
+
* client's logout path clears its current-user pointer, breaking local-first writes
|
|
89
|
+
* (`mutate()` throws) until the next real auth event. A transient network failure is a
|
|
90
|
+
* recoverable state, not a sign-out (INV-2), so the identity is left unchanged and the
|
|
91
|
+
* next successful emission decides.
|
|
92
|
+
*/
|
|
93
|
+
const classifyEmission = (value) => {
|
|
94
|
+
if (!value || typeof value !== "object") {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
const emission = value;
|
|
98
|
+
if (emission.isPending === true) {
|
|
99
|
+
return "pending";
|
|
100
|
+
}
|
|
101
|
+
if (emission.error) {
|
|
102
|
+
return "pending";
|
|
103
|
+
}
|
|
104
|
+
let payload = null;
|
|
105
|
+
if ("data" in emission) {
|
|
106
|
+
payload =
|
|
107
|
+
emission.data && typeof emission.data === "object"
|
|
108
|
+
? emission.data
|
|
109
|
+
: null;
|
|
110
|
+
}
|
|
111
|
+
else if ("user" in emission || "session" in emission) {
|
|
112
|
+
payload = emission;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
return { key: `${payload?.user?.id ?? ""}|${payload?.session?.token ?? ""}` };
|
|
118
|
+
};
|
|
119
|
+
const onAuthChange = (callback) => {
|
|
120
|
+
const subscribe = authClient.useSession?.subscribe;
|
|
121
|
+
if (typeof subscribe === "function") {
|
|
122
|
+
// Dedupe by session identity: Better Auth's session atom re-emits on EVERY
|
|
123
|
+
// get-session fetch (each settles with a fresh object), including fetches this
|
|
124
|
+
// adapter's own getToken/getUserId trigger. Forwarding every emission creates a
|
|
125
|
+
// feedback loop (auth change → getUserId → getSession → atom emission → auth
|
|
126
|
+
// change → ...), so only a genuine identity change (login/logout/user switch/
|
|
127
|
+
// token rotation) may fire the callback. In-flight (`isPending`) states are
|
|
128
|
+
// skipped; opaque values the adapter cannot parse are forwarded as before.
|
|
129
|
+
let lastKey;
|
|
130
|
+
const unsubscribe = subscribe((value) => {
|
|
131
|
+
const parsed = classifyEmission(value);
|
|
132
|
+
if (parsed === "pending") {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (parsed === null) {
|
|
136
|
+
callback();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (parsed.key === lastKey) {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
lastKey = parsed.key;
|
|
143
|
+
callback();
|
|
144
|
+
});
|
|
145
|
+
return typeof unsubscribe === "function" ? unsubscribe : () => { };
|
|
146
|
+
}
|
|
147
|
+
// Polling fallback: sample the session identity and fire on change. The
|
|
148
|
+
// first sample only establishes the baseline so subscribing never emits a
|
|
149
|
+
// spurious change for the already-current session.
|
|
150
|
+
let disposed = false;
|
|
151
|
+
let lastKey;
|
|
152
|
+
void readAuthKey().then((key) => {
|
|
153
|
+
if (!disposed && lastKey === undefined && key !== null) {
|
|
154
|
+
lastKey = key;
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
const handle = setIntervalFn(() => {
|
|
158
|
+
void readAuthKey().then((key) => {
|
|
159
|
+
if (disposed || key === null) {
|
|
160
|
+
// Failed read: hold the last known identity rather than sampling it as
|
|
161
|
+
// signed out.
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (lastKey === undefined) {
|
|
165
|
+
lastKey = key;
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (key !== lastKey) {
|
|
169
|
+
lastKey = key;
|
|
170
|
+
callback();
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
}, pollIntervalMs);
|
|
174
|
+
return () => {
|
|
175
|
+
disposed = true;
|
|
176
|
+
clearIntervalFn(handle);
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
return { getToken, getUserId, onAuthChange, refresh };
|
|
180
|
+
};
|
|
181
|
+
//# sourceMappingURL=betterAuthAdapter.js.map
|