@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
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React hooks over the SyncDb client.
|
|
3
|
+
*
|
|
4
|
+
* Reactivity is wired directly onto the raw TinyBase MergeableStore via
|
|
5
|
+
* `addRowListener`/`addTableListener` + `useSyncExternalStore` rather than
|
|
6
|
+
* `tinybase/ui-react`: ui-react hooks return raw rows/tables while these hooks
|
|
7
|
+
* return the decoded entity shapes (the `data` cell is JSON-encoded), and
|
|
8
|
+
* binding listeners ourselves keeps the React surface down to a single `react`
|
|
9
|
+
* peer dependency. No DOM APIs are used, so everything here is React Native
|
|
10
|
+
* (and RNW) compatible.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {useCallback, useRef, useSyncExternalStore} from "react";
|
|
14
|
+
|
|
15
|
+
import type {SyncDebugEvent, SyncDebugLog, SyncDebugStats} from "../debug/debugLog";
|
|
16
|
+
import {listConflicts} from "../mutations/conflicts";
|
|
17
|
+
import {CONFLICTS_TABLE, CURSORS_TABLE, OUTBOX_TABLE} from "../storage/types";
|
|
18
|
+
import type {ConflictResolutionStrategy, SyncConflict, SyncStatus} from "../types";
|
|
19
|
+
import {useSyncDbClient} from "./provider";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* `useSyncExternalStore` wrapper that recomputes the selected value only when the
|
|
23
|
+
* underlying store actually changes, giving selectors returning fresh
|
|
24
|
+
* objects/arrays a stable identity across unrelated renders without ever causing
|
|
25
|
+
* render loops.
|
|
26
|
+
*
|
|
27
|
+
* React calls `getSnapshot` on EVERY render (not only when the store changes) to
|
|
28
|
+
* check for tearing. The previous implementation re-ran `select()` and then
|
|
29
|
+
* `JSON.stringify`'d the entire result on every one of those calls — O(n) work
|
|
30
|
+
* (decode + filter + sort + serialize the whole collection) on every keystroke
|
|
31
|
+
* or unrelated parent re-render, which dominates once a collection grows to
|
|
32
|
+
* thousands of rows. Instead we bump a monotonic revision only when a change is
|
|
33
|
+
* routed through our subscribe wrapper, and cache the computed value against
|
|
34
|
+
* that revision (and the selector identity, so a changed collection/id
|
|
35
|
+
* recomputes immediately rather than returning a stale snapshot). Unrelated
|
|
36
|
+
* re-renders then return the cached value in O(1) and never serialize.
|
|
37
|
+
*/
|
|
38
|
+
const useCachedExternalStore = <T>(
|
|
39
|
+
subscribe: (onChange: () => void) => () => void,
|
|
40
|
+
select: () => T,
|
|
41
|
+
/**
|
|
42
|
+
* Optional structural equality over consecutive selections. When provided and
|
|
43
|
+
* a real store change produces an equal value, the PREVIOUS reference is kept
|
|
44
|
+
* so downstream consumers do not re-render. This is what lets `useEntityIds`
|
|
45
|
+
* stay referentially stable across field-only updates (which change a row's
|
|
46
|
+
* data but not the id membership/order), so toggling one entity re-renders
|
|
47
|
+
* only that entity's own subscribers, never the list container.
|
|
48
|
+
*/
|
|
49
|
+
areEqual?: (previous: T, next: T) => boolean
|
|
50
|
+
): T => {
|
|
51
|
+
const revisionRef = useRef(0);
|
|
52
|
+
const cacheRef = useRef<{revision: number; select: () => T; value: T} | null>(null);
|
|
53
|
+
|
|
54
|
+
const wrappedSubscribe = useCallback(
|
|
55
|
+
(onChange: () => void): (() => void) =>
|
|
56
|
+
subscribe(() => {
|
|
57
|
+
revisionRef.current += 1;
|
|
58
|
+
onChange();
|
|
59
|
+
}),
|
|
60
|
+
[subscribe]
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
const getSnapshot = useCallback((): T => {
|
|
64
|
+
const revision = revisionRef.current;
|
|
65
|
+
const cached = cacheRef.current;
|
|
66
|
+
if (cached && cached.select === select && cached.revision === revision) {
|
|
67
|
+
// Neither the store nor the selector changed since the last computation →
|
|
68
|
+
// reuse in O(1) (the common case: unrelated re-renders such as a keystroke
|
|
69
|
+
// in a sibling input).
|
|
70
|
+
return cached.value;
|
|
71
|
+
}
|
|
72
|
+
// Either the store changed or the selector did (a new collection/id, or
|
|
73
|
+
// changed query options — see useQuery). Recompute, but keep the previous
|
|
74
|
+
// reference when an equality check says the result is unchanged (e.g. a
|
|
75
|
+
// field update that did not alter id membership/order), which is also what
|
|
76
|
+
// keeps `useSyncExternalStore` from re-rendering on every recomputation.
|
|
77
|
+
const next = select();
|
|
78
|
+
if (cached && areEqual?.(cached.value, next)) {
|
|
79
|
+
cacheRef.current = {revision, select, value: cached.value};
|
|
80
|
+
return cached.value;
|
|
81
|
+
}
|
|
82
|
+
cacheRef.current = {revision, select, value: next};
|
|
83
|
+
return next;
|
|
84
|
+
}, [select, areEqual]);
|
|
85
|
+
|
|
86
|
+
return useSyncExternalStore(wrappedSubscribe, getSnapshot, getSnapshot);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** Referential-stability helper: true when two id lists are element-wise equal. */
|
|
90
|
+
const idsEqual = (previous: string[], next: string[]): boolean => {
|
|
91
|
+
if (previous === next) {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
if (previous.length !== next.length) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
for (let index = 0; index < previous.length; index += 1) {
|
|
98
|
+
if (previous[index] !== next[index]) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return true;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
export interface UseEntityResult<TData> {
|
|
106
|
+
/** Decoded entity payload, or undefined when the entity does not exist locally. */
|
|
107
|
+
data: TData | undefined;
|
|
108
|
+
/** Soft-delete tombstone flag. */
|
|
109
|
+
deleted: boolean;
|
|
110
|
+
/** Highest server seq applied to the entity (0 = local-only). */
|
|
111
|
+
seq: number;
|
|
112
|
+
/** True while an outbox mutation is protecting this entity's optimistic state. */
|
|
113
|
+
isPending: boolean;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Subscribe to a single entity; re-renders when that row changes. */
|
|
117
|
+
export const useEntity = <TData = Record<string, unknown>>(
|
|
118
|
+
collection: string,
|
|
119
|
+
id: string
|
|
120
|
+
): UseEntityResult<TData> => {
|
|
121
|
+
const client = useSyncDbClient();
|
|
122
|
+
|
|
123
|
+
const subscribe = useCallback(
|
|
124
|
+
(onChange: () => void): (() => void) => {
|
|
125
|
+
const listenerId = client.store.raw.addRowListener(collection, id, onChange);
|
|
126
|
+
return () => {
|
|
127
|
+
client.store.raw.delListener(listenerId);
|
|
128
|
+
};
|
|
129
|
+
},
|
|
130
|
+
[client, collection, id]
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
const select = useCallback((): UseEntityResult<TData> => {
|
|
134
|
+
const entity = client.store.getEntity<TData>({collection, id});
|
|
135
|
+
if (!entity) {
|
|
136
|
+
return {data: undefined, deleted: false, isPending: false, seq: 0};
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
data: entity.data ?? undefined,
|
|
140
|
+
deleted: entity.deleted,
|
|
141
|
+
isPending: entity.pendingMutationId !== undefined,
|
|
142
|
+
seq: entity.seq,
|
|
143
|
+
};
|
|
144
|
+
}, [client, collection, id]);
|
|
145
|
+
|
|
146
|
+
return useCachedExternalStore(subscribe, select);
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
export interface UseQueryOptions<TData> {
|
|
150
|
+
/** Keep only entities whose decoded data passes the predicate (runs in JS). */
|
|
151
|
+
filter?: (data: TData) => boolean;
|
|
152
|
+
/** Sort comparator over decoded data (runs in JS on a copy). */
|
|
153
|
+
sort?: (a: TData, b: TData) => number;
|
|
154
|
+
/** Include soft-deleted (tombstoned) entities; excluded by default. */
|
|
155
|
+
includeDeleted?: boolean;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Subscribe to a collection; returns the entities' decoded data and re-renders
|
|
160
|
+
* on any table change. Tombstones are excluded unless `includeDeleted` is set;
|
|
161
|
+
* filter and sort run in JS.
|
|
162
|
+
*
|
|
163
|
+
* `filter`/`sort`/`includeDeleted` are part of the selection identity (compared
|
|
164
|
+
* by reference), so a state-driven filter change is reflected on the very next
|
|
165
|
+
* render without waiting for a store write. The flip side is that a filter/sort
|
|
166
|
+
* passed as a fresh inline closure every render invalidates the snapshot cache
|
|
167
|
+
* every render — wrap them in `useCallback` (or hoist them) when the collection
|
|
168
|
+
* is large enough for the decode/filter/sort pass to matter.
|
|
169
|
+
*/
|
|
170
|
+
export const useQuery = <TData = Record<string, unknown>>(
|
|
171
|
+
collection: string,
|
|
172
|
+
options?: UseQueryOptions<TData>
|
|
173
|
+
): TData[] => {
|
|
174
|
+
const client = useSyncDbClient();
|
|
175
|
+
const {filter, includeDeleted, sort} = options ?? {};
|
|
176
|
+
|
|
177
|
+
const subscribe = useCallback(
|
|
178
|
+
(onChange: () => void): (() => void) => {
|
|
179
|
+
const listenerId = client.store.raw.addTableListener(collection, onChange);
|
|
180
|
+
return () => {
|
|
181
|
+
client.store.raw.delListener(listenerId);
|
|
182
|
+
};
|
|
183
|
+
},
|
|
184
|
+
[client, collection]
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
const select = useCallback((): TData[] => {
|
|
188
|
+
const entities = client.store.listEntities<TData>({collection, includeDeleted});
|
|
189
|
+
// E4: a corrupt/legacy row decodes to `data: null` (store.ts's decodeData
|
|
190
|
+
// swallows JSON.parse failures and returns null rather than throwing) —
|
|
191
|
+
// skip it here rather than letting it crash list consumers that assume
|
|
192
|
+
// every row's data matches TData (e.g. destructuring a field off it).
|
|
193
|
+
let results = entities.filter((entity) => entity.data !== null).map((entity) => entity.data);
|
|
194
|
+
if (filter) {
|
|
195
|
+
results = results.filter(filter);
|
|
196
|
+
}
|
|
197
|
+
if (sort) {
|
|
198
|
+
results = [...results].sort(sort);
|
|
199
|
+
}
|
|
200
|
+
return results;
|
|
201
|
+
}, [client, collection, filter, includeDeleted, sort]);
|
|
202
|
+
|
|
203
|
+
return useCachedExternalStore(subscribe, select);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Subscribe to a collection but return only the (ordered) entity ids, with a
|
|
208
|
+
* referentially STABLE array that changes identity only when the id membership
|
|
209
|
+
* or order actually changes — not when a field of an existing row changes.
|
|
210
|
+
*
|
|
211
|
+
* Pair this with per-row `useEntity(collection, id)` to build large lists that
|
|
212
|
+
* stay fast without virtualization: rendering `ids.map(id => <Row id={id} />)`
|
|
213
|
+
* means a field update (e.g. toggling one row) re-renders ONLY that row's
|
|
214
|
+
* `useEntity` subscriber, and the list container re-renders only when rows are
|
|
215
|
+
* added/removed/reordered. `filter`/`sort` run in JS over the decoded data and,
|
|
216
|
+
* as in `useQuery`, are part of the selection identity — a changed filter is
|
|
217
|
+
* reflected on the next render, and memoizing inline callbacks keeps the
|
|
218
|
+
* recomputation to store changes only. Either way the returned array keeps its
|
|
219
|
+
* identity whenever the resulting ids are unchanged.
|
|
220
|
+
*/
|
|
221
|
+
export const useEntityIds = <TData = Record<string, unknown>>(
|
|
222
|
+
collection: string,
|
|
223
|
+
options?: UseQueryOptions<TData>
|
|
224
|
+
): string[] => {
|
|
225
|
+
const client = useSyncDbClient();
|
|
226
|
+
const {filter, includeDeleted, sort} = options ?? {};
|
|
227
|
+
|
|
228
|
+
const subscribe = useCallback(
|
|
229
|
+
(onChange: () => void): (() => void) => {
|
|
230
|
+
const listenerId = client.store.raw.addTableListener(collection, onChange);
|
|
231
|
+
return () => {
|
|
232
|
+
client.store.raw.delListener(listenerId);
|
|
233
|
+
};
|
|
234
|
+
},
|
|
235
|
+
[client, collection]
|
|
236
|
+
);
|
|
237
|
+
|
|
238
|
+
const select = useCallback((): string[] => {
|
|
239
|
+
const entities = client.store.listEntities<TData>({collection, includeDeleted});
|
|
240
|
+
let results = entities.filter((entity) => entity.data !== null);
|
|
241
|
+
if (filter) {
|
|
242
|
+
results = results.filter((entity) => filter(entity.data));
|
|
243
|
+
}
|
|
244
|
+
if (sort) {
|
|
245
|
+
results = [...results].sort((a, b) => sort(a.data, b.data));
|
|
246
|
+
}
|
|
247
|
+
return results.map((entity) => entity.id);
|
|
248
|
+
}, [client, collection, filter, includeDeleted, sort]);
|
|
249
|
+
|
|
250
|
+
return useCachedExternalStore(subscribe, select, idsEqual);
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
export interface UseMutateResult {
|
|
254
|
+
/** Optimistically create an entity; returns the generated ids. */
|
|
255
|
+
create: (args: {data: Record<string, unknown>}) => {mutationId: string; id: string};
|
|
256
|
+
/** Optimistically merge fields into an existing entity. */
|
|
257
|
+
update: (args: {id: string; data: Record<string, unknown>}) => {mutationId: string; id: string};
|
|
258
|
+
/** Optimistically soft-delete an entity. */
|
|
259
|
+
remove: (args: {id: string}) => {mutationId: string; id: string};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Collection-scoped mutation helpers wrapping `client.mutate`: each applies
|
|
264
|
+
* locally, enqueues a durable outbox mutation, and kicks off replay.
|
|
265
|
+
*/
|
|
266
|
+
export const useMutate = (collection: string): UseMutateResult => {
|
|
267
|
+
const client = useSyncDbClient();
|
|
268
|
+
|
|
269
|
+
const create = useCallback(
|
|
270
|
+
(args: {data: Record<string, unknown>}): {mutationId: string; id: string} =>
|
|
271
|
+
client.mutate({collection, data: args.data, operation: "create"}),
|
|
272
|
+
[client, collection]
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
const update = useCallback(
|
|
276
|
+
(args: {id: string; data: Record<string, unknown>}): {mutationId: string; id: string} =>
|
|
277
|
+
client.mutate({collection, data: args.data, id: args.id, operation: "update"}),
|
|
278
|
+
[client, collection]
|
|
279
|
+
);
|
|
280
|
+
|
|
281
|
+
const remove = useCallback(
|
|
282
|
+
(args: {id: string}): {mutationId: string; id: string} =>
|
|
283
|
+
client.mutate({collection, id: args.id, operation: "delete"}),
|
|
284
|
+
[client, collection]
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
return {create, remove, update};
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Aggregate sync status; re-renders when any status input changes. Store-backed
|
|
292
|
+
* inputs (queued outbox rows, conflicts, stream cursors) are observed through
|
|
293
|
+
* table listeners; connectivity and syncing activity arrive through the
|
|
294
|
+
* client's `onStatusChange` passthrough.
|
|
295
|
+
*/
|
|
296
|
+
export const useSyncStatus = (): SyncStatus => {
|
|
297
|
+
const client = useSyncDbClient();
|
|
298
|
+
|
|
299
|
+
const subscribe = useCallback(
|
|
300
|
+
(onChange: () => void): (() => void) => {
|
|
301
|
+
const unsubStatus = client.onStatusChange(onChange);
|
|
302
|
+
const outboxListener = client.store.raw.addTableListener(OUTBOX_TABLE, onChange);
|
|
303
|
+
const conflictsListener = client.store.raw.addTableListener(CONFLICTS_TABLE, onChange);
|
|
304
|
+
const cursorsListener = client.store.raw.addTableListener(CURSORS_TABLE, onChange);
|
|
305
|
+
return () => {
|
|
306
|
+
unsubStatus();
|
|
307
|
+
client.store.raw.delListener(outboxListener);
|
|
308
|
+
client.store.raw.delListener(conflictsListener);
|
|
309
|
+
client.store.raw.delListener(cursorsListener);
|
|
310
|
+
};
|
|
311
|
+
},
|
|
312
|
+
[client]
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
const select = useCallback((): SyncStatus => client.getSyncStatus(), [client]);
|
|
316
|
+
|
|
317
|
+
return useCachedExternalStore(subscribe, select);
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
export interface UseConflictsResult {
|
|
321
|
+
/** Unresolved conflicts (dismissed rows excluded). */
|
|
322
|
+
conflicts: SyncConflict[];
|
|
323
|
+
/** Resolve a conflict with `useServer` or `keepMine`. */
|
|
324
|
+
resolve: (args: {mutationId: string; strategy: ConflictResolutionStrategy}) => void;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Subscribe to unresolved conflicts and expose the client's resolver. */
|
|
328
|
+
export const useConflicts = (): UseConflictsResult => {
|
|
329
|
+
const client = useSyncDbClient();
|
|
330
|
+
|
|
331
|
+
const subscribe = useCallback(
|
|
332
|
+
(onChange: () => void): (() => void) => {
|
|
333
|
+
const listenerId = client.store.raw.addTableListener(CONFLICTS_TABLE, onChange);
|
|
334
|
+
return () => {
|
|
335
|
+
client.store.raw.delListener(listenerId);
|
|
336
|
+
};
|
|
337
|
+
},
|
|
338
|
+
[client]
|
|
339
|
+
);
|
|
340
|
+
|
|
341
|
+
const select = useCallback((): SyncConflict[] => listConflicts({store: client.store}), [client]);
|
|
342
|
+
|
|
343
|
+
const conflicts = useCachedExternalStore(subscribe, select);
|
|
344
|
+
|
|
345
|
+
const resolve = useCallback(
|
|
346
|
+
(args: {mutationId: string; strategy: ConflictResolutionStrategy}): void => {
|
|
347
|
+
client.resolveConflict(args);
|
|
348
|
+
},
|
|
349
|
+
[client]
|
|
350
|
+
);
|
|
351
|
+
|
|
352
|
+
return {conflicts, resolve};
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
export interface UseSyncDebugLogResult {
|
|
356
|
+
/** True when the client was created with `debug` enabled. */
|
|
357
|
+
enabled: boolean;
|
|
358
|
+
/** Recorded events, oldest → newest (empty when disabled). */
|
|
359
|
+
events: SyncDebugEvent[];
|
|
360
|
+
/** Aggregate counters (undefined when disabled). */
|
|
361
|
+
stats: SyncDebugStats | undefined;
|
|
362
|
+
/** The underlying log, for `snapshot()`/`clear()` (undefined when disabled). */
|
|
363
|
+
log: SyncDebugLog | undefined;
|
|
364
|
+
/** Drop all retained events and reset `stats` to describe the now-empty log (a no-op when disabled). */
|
|
365
|
+
clear: () => void;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const EMPTY_EVENTS: SyncDebugEvent[] = [];
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Subscribe to the client's debug event log (see `createSyncDb({debug: true})`).
|
|
372
|
+
*
|
|
373
|
+
* Reactivity is driven by the log's monotonic revision through
|
|
374
|
+
* `useSyncExternalStore`, so a burst of events triggers at most one render per
|
|
375
|
+
* commit. `events` is read fresh from the ring buffer on each render (O(capacity),
|
|
376
|
+
* capacity defaults to 500) — cheap enough for a live debugger and stable when
|
|
377
|
+
* nothing changed because the revision is unchanged.
|
|
378
|
+
*/
|
|
379
|
+
export const useSyncDebugLog = (): UseSyncDebugLogResult => {
|
|
380
|
+
const client = useSyncDbClient();
|
|
381
|
+
const log = client.debug;
|
|
382
|
+
|
|
383
|
+
const subscribe = useCallback(
|
|
384
|
+
(onChange: () => void): (() => void) => {
|
|
385
|
+
if (!log) {
|
|
386
|
+
return () => {};
|
|
387
|
+
}
|
|
388
|
+
return log.subscribe(onChange);
|
|
389
|
+
},
|
|
390
|
+
[log]
|
|
391
|
+
);
|
|
392
|
+
|
|
393
|
+
const getRevision = useCallback((): number => log?.getRevision() ?? 0, [log]);
|
|
394
|
+
|
|
395
|
+
// The revision changes on every record/clear; reading it re-renders the hook.
|
|
396
|
+
useSyncExternalStore(subscribe, getRevision, getRevision);
|
|
397
|
+
|
|
398
|
+
const clear = useCallback((): void => {
|
|
399
|
+
log?.clear();
|
|
400
|
+
}, [log]);
|
|
401
|
+
|
|
402
|
+
return {
|
|
403
|
+
clear,
|
|
404
|
+
enabled: Boolean(log),
|
|
405
|
+
events: log ? log.getEvents() : EMPTY_EVENTS,
|
|
406
|
+
log,
|
|
407
|
+
stats: log?.getStats(),
|
|
408
|
+
};
|
|
409
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React bindings for @terreno/syncdb.
|
|
3
|
+
*
|
|
4
|
+
* Published as the `@terreno/syncdb/react` subpath (see package.json
|
|
5
|
+
* "exports") and deliberately NOT re-exported from the package's main index:
|
|
6
|
+
* `react` is an optional peer dependency, and keeping these modules off the
|
|
7
|
+
* main entry means non-React (node/backend) consumers never load React.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export * from "./hooks";
|
|
11
|
+
export * from "./provider";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import React, {createContext, useContext} from "react";
|
|
2
|
+
|
|
3
|
+
import type {SyncDb} from "../client";
|
|
4
|
+
|
|
5
|
+
const SyncDbContext = createContext<SyncDb | null>(null);
|
|
6
|
+
|
|
7
|
+
export interface SyncDbProviderProps {
|
|
8
|
+
client: SyncDb;
|
|
9
|
+
children: React.ReactNode;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Provides a SyncDb client to descendant hooks (`useEntity`, `useQuery`, etc.). */
|
|
13
|
+
export const SyncDbProvider: React.FC<SyncDbProviderProps> = ({client, children}) => {
|
|
14
|
+
return <SyncDbContext.Provider value={client}>{children}</SyncDbContext.Provider>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** Access the SyncDb client from context; throws when no provider is mounted. */
|
|
18
|
+
export const useSyncDbClient = (): SyncDb => {
|
|
19
|
+
const client = useContext(SyncDbContext);
|
|
20
|
+
if (!client) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
"useSyncDbClient must be used within a <SyncDbProvider client={...}>. " +
|
|
23
|
+
"Wrap your app (or the subtree using syncdb hooks) in SyncDbProvider."
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
return client;
|
|
27
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import "fake-indexeddb/auto";
|
|
2
|
+
|
|
3
|
+
import {describe, expect, it} from "bun:test";
|
|
4
|
+
|
|
5
|
+
import {deleteIdbDatabase, idbDelete, idbGet, idbSet} from "./idb";
|
|
6
|
+
|
|
7
|
+
let dbCounter = 0;
|
|
8
|
+
const uniqueDbName = (): string => `idb-test-${Date.now()}-${dbCounter++}`;
|
|
9
|
+
|
|
10
|
+
const withoutIndexedDb = async (run: () => Promise<void>): Promise<void> => {
|
|
11
|
+
const original = globalThis.indexedDB;
|
|
12
|
+
// biome-ignore lint/suspicious/noExplicitAny: deliberately unsetting a global for the failure-path test
|
|
13
|
+
(globalThis as any).indexedDB = undefined;
|
|
14
|
+
try {
|
|
15
|
+
await run();
|
|
16
|
+
} finally {
|
|
17
|
+
// biome-ignore lint/suspicious/noExplicitAny: restoring the global
|
|
18
|
+
(globalThis as any).indexedDB = original;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
describe("idbSet / idbGet", () => {
|
|
23
|
+
it("round-trips structured-cloneable values", async () => {
|
|
24
|
+
const databaseName = uniqueDbName();
|
|
25
|
+
await idbSet({databaseName, key: "blob", value: new Uint8Array([7, 8, 9])});
|
|
26
|
+
const value = await idbGet<Uint8Array>({databaseName, key: "blob"});
|
|
27
|
+
expect(value).toBeInstanceOf(Uint8Array);
|
|
28
|
+
expect(Array.from(value as Uint8Array)).toEqual([7, 8, 9]);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("returns undefined for a key that was never written", async () => {
|
|
32
|
+
expect(await idbGet({databaseName: uniqueDbName(), key: "missing"})).toBeUndefined();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("overwrites an existing key", async () => {
|
|
36
|
+
const databaseName = uniqueDbName();
|
|
37
|
+
await idbSet({databaseName, key: "k", value: "first"});
|
|
38
|
+
await idbSet({databaseName, key: "k", value: "second"});
|
|
39
|
+
expect(await idbGet<string>({databaseName, key: "k"})).toBe("second");
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe("idbDelete", () => {
|
|
44
|
+
it("removes a single key", async () => {
|
|
45
|
+
const databaseName = uniqueDbName();
|
|
46
|
+
await idbSet({databaseName, key: "k", value: "v"});
|
|
47
|
+
await idbDelete({databaseName, key: "k"});
|
|
48
|
+
expect(await idbGet({databaseName, key: "k"})).toBeUndefined();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("is a no-op for an absent key", async () => {
|
|
52
|
+
const databaseName = uniqueDbName();
|
|
53
|
+
await idbDelete({databaseName, key: "never-written"});
|
|
54
|
+
expect(await idbGet({databaseName, key: "never-written"})).toBeUndefined();
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe("deleteIdbDatabase", () => {
|
|
59
|
+
it("removes every record in the database", async () => {
|
|
60
|
+
const databaseName = uniqueDbName();
|
|
61
|
+
await idbSet({databaseName, key: "k", value: "v"});
|
|
62
|
+
await deleteIdbDatabase({databaseName});
|
|
63
|
+
expect(await idbGet({databaseName, key: "k"})).toBeUndefined();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("resolves when the deletion is blocked by an open connection", async () => {
|
|
67
|
+
const databaseName = uniqueDbName();
|
|
68
|
+
await idbSet({databaseName, key: "k", value: "v"});
|
|
69
|
+
// Hold a connection open (and ignore versionchange) so the delete blocks.
|
|
70
|
+
const connection = await new Promise<IDBDatabase>((resolve, reject) => {
|
|
71
|
+
const request = indexedDB.open(databaseName, 1);
|
|
72
|
+
request.onsuccess = (): void => resolve(request.result);
|
|
73
|
+
request.onerror = (): void => reject(request.error);
|
|
74
|
+
});
|
|
75
|
+
await deleteIdbDatabase({databaseName});
|
|
76
|
+
connection.close();
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe("open failures", () => {
|
|
81
|
+
it("rejects when the database exists at a newer version", async () => {
|
|
82
|
+
const databaseName = uniqueDbName();
|
|
83
|
+
await new Promise<void>((resolve, reject) => {
|
|
84
|
+
const request = indexedDB.open(databaseName, 2);
|
|
85
|
+
request.onupgradeneeded = (): void => {
|
|
86
|
+
request.result.createObjectStore("kv");
|
|
87
|
+
};
|
|
88
|
+
request.onsuccess = (): void => {
|
|
89
|
+
request.result.close();
|
|
90
|
+
resolve();
|
|
91
|
+
};
|
|
92
|
+
request.onerror = (): void => reject(request.error);
|
|
93
|
+
});
|
|
94
|
+
// idb helpers always open version 1; an existing v2 database must fail
|
|
95
|
+
// loudly instead of silently clobbering it.
|
|
96
|
+
expect(idbGet({databaseName, key: "k"})).rejects.toThrow();
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe("without IndexedDB available", () => {
|
|
101
|
+
it("idbGet rejects with a clear error", async () => {
|
|
102
|
+
await withoutIndexedDb(async () => {
|
|
103
|
+
expect(idbGet({databaseName: "x", key: "k"})).rejects.toThrow(
|
|
104
|
+
"IndexedDB is unavailable in this environment"
|
|
105
|
+
);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("deleteIdbDatabase rejects with a clear error", async () => {
|
|
110
|
+
await withoutIndexedDb(async () => {
|
|
111
|
+
expect(deleteIdbDatabase({databaseName: "x"})).rejects.toThrow(
|
|
112
|
+
"IndexedDB is unavailable in this environment"
|
|
113
|
+
);
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
});
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal promisified IndexedDB key-value helpers shared by the encrypted web
|
|
3
|
+
* persister, the key providers, and the wipe helper. Each operation opens the
|
|
4
|
+
* database, runs a single transaction, and closes the connection so that
|
|
5
|
+
* `deleteIdbDatabase` is never blocked by a lingering handle.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const DEFAULT_OBJECT_STORE = "kv";
|
|
9
|
+
|
|
10
|
+
const getIndexedDb = (): IDBFactory => {
|
|
11
|
+
const idb = globalThis.indexedDB;
|
|
12
|
+
if (!idb) {
|
|
13
|
+
throw new Error("IndexedDB is unavailable in this environment");
|
|
14
|
+
}
|
|
15
|
+
return idb;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const openKvDatabase = ({databaseName}: {databaseName: string}): Promise<IDBDatabase> =>
|
|
19
|
+
new Promise((resolve, reject) => {
|
|
20
|
+
const request = getIndexedDb().open(databaseName, 1);
|
|
21
|
+
request.onupgradeneeded = (): void => {
|
|
22
|
+
if (!request.result.objectStoreNames.contains(DEFAULT_OBJECT_STORE)) {
|
|
23
|
+
request.result.createObjectStore(DEFAULT_OBJECT_STORE);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
request.onsuccess = (): void => resolve(request.result);
|
|
27
|
+
request.onerror = (): void =>
|
|
28
|
+
reject(request.error ?? new Error(`Failed to open IndexedDB database "${databaseName}"`));
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const runTransaction = async <T>({
|
|
32
|
+
databaseName,
|
|
33
|
+
mode,
|
|
34
|
+
operation,
|
|
35
|
+
}: {
|
|
36
|
+
databaseName: string;
|
|
37
|
+
mode: IDBTransactionMode;
|
|
38
|
+
operation: (store: IDBObjectStore) => IDBRequest<T>;
|
|
39
|
+
}): Promise<T> => {
|
|
40
|
+
const db = await openKvDatabase({databaseName});
|
|
41
|
+
try {
|
|
42
|
+
return await new Promise<T>((resolve, reject) => {
|
|
43
|
+
const transaction = db.transaction(DEFAULT_OBJECT_STORE, mode);
|
|
44
|
+
const request = operation(transaction.objectStore(DEFAULT_OBJECT_STORE));
|
|
45
|
+
const fail = (): void =>
|
|
46
|
+
reject(transaction.error ?? new Error("IndexedDB transaction failed"));
|
|
47
|
+
transaction.oncomplete = (): void => resolve(request.result);
|
|
48
|
+
transaction.onabort = fail;
|
|
49
|
+
transaction.onerror = fail;
|
|
50
|
+
});
|
|
51
|
+
} finally {
|
|
52
|
+
db.close();
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** Read a value; `undefined` when the key has never been written. */
|
|
57
|
+
export const idbGet = async <T>({
|
|
58
|
+
databaseName,
|
|
59
|
+
key,
|
|
60
|
+
}: {
|
|
61
|
+
databaseName: string;
|
|
62
|
+
key: string;
|
|
63
|
+
}): Promise<T | undefined> =>
|
|
64
|
+
(await runTransaction<unknown>({
|
|
65
|
+
databaseName,
|
|
66
|
+
mode: "readonly",
|
|
67
|
+
operation: (store) => store.get(key),
|
|
68
|
+
})) as T | undefined;
|
|
69
|
+
|
|
70
|
+
/** Write a value (structured-cloneable, e.g. Uint8Array or CryptoKey). */
|
|
71
|
+
export const idbSet = async ({
|
|
72
|
+
databaseName,
|
|
73
|
+
key,
|
|
74
|
+
value,
|
|
75
|
+
}: {
|
|
76
|
+
databaseName: string;
|
|
77
|
+
key: string;
|
|
78
|
+
value: unknown;
|
|
79
|
+
}): Promise<void> => {
|
|
80
|
+
await runTransaction({
|
|
81
|
+
databaseName,
|
|
82
|
+
mode: "readwrite",
|
|
83
|
+
operation: (store) => store.put(value, key),
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** Delete a single key (no-op when absent). */
|
|
88
|
+
export const idbDelete = async ({
|
|
89
|
+
databaseName,
|
|
90
|
+
key,
|
|
91
|
+
}: {
|
|
92
|
+
databaseName: string;
|
|
93
|
+
key: string;
|
|
94
|
+
}): Promise<void> => {
|
|
95
|
+
await runTransaction({
|
|
96
|
+
databaseName,
|
|
97
|
+
mode: "readwrite",
|
|
98
|
+
operation: (store) => store.delete(key),
|
|
99
|
+
});
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** Delete an entire IndexedDB database (used by the wipe helper). */
|
|
103
|
+
export const deleteIdbDatabase = ({databaseName}: {databaseName: string}): Promise<void> =>
|
|
104
|
+
new Promise((resolve, reject) => {
|
|
105
|
+
const request = getIndexedDb().deleteDatabase(databaseName);
|
|
106
|
+
request.onsuccess = (): void => resolve();
|
|
107
|
+
// Blocked means another open connection defers the deletion; it completes
|
|
108
|
+
// once that connection closes, so treat it as success rather than hanging.
|
|
109
|
+
request.onblocked = (): void => resolve();
|
|
110
|
+
request.onerror = (): void =>
|
|
111
|
+
reject(request.error ?? new Error(`Failed to delete IndexedDB database "${databaseName}"`));
|
|
112
|
+
});
|