@bayonai/offline 0.1.1 → 0.3.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/CHANGELOG.md +21 -0
- package/README.md +82 -1
- package/dist/browserCoordination.d.ts +23 -0
- package/dist/browserCoordination.js +57 -0
- package/dist/browserRecovery.d.ts +34 -0
- package/dist/browserRecovery.js +172 -0
- package/dist/idbDriver.d.ts +4 -0
- package/dist/idbDriver.js +24 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/pendingWrites.d.ts +64 -1
- package/dist/pendingWrites.js +112 -3
- package/dist/readCache.d.ts +19 -1
- package/dist/readCache.js +48 -3
- package/dist-cjs/browserCoordination.js +60 -0
- package/dist-cjs/browserRecovery.js +176 -0
- package/dist-cjs/idbDriver.js +24 -0
- package/dist-cjs/index.js +2 -0
- package/dist-cjs/pendingWrites.js +115 -3
- package/dist-cjs/readCache.js +49 -3
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 - 2026-08-31
|
|
4
|
+
|
|
5
|
+
- Added optional `BroadcastChannel` wake-ups and `navigator.locks` replay
|
|
6
|
+
leases so browser tabs can avoid concurrent recovery attempts while retaining
|
|
7
|
+
a safe local fallback where either API is unavailable.
|
|
8
|
+
- Added `summarizePendingWrites` for framework-neutral pending/syncing/failed
|
|
9
|
+
counts without exposing any product UI policy.
|
|
10
|
+
- Added opt-in `pruneReadCache`, which deletes only valid read-cache envelopes
|
|
11
|
+
older than a host-supplied retention age. Pending writes are never pruned.
|
|
12
|
+
|
|
13
|
+
## 0.2.0 - 2026-08-31
|
|
14
|
+
|
|
15
|
+
- Added forced-fresh, per-key single-flight `readThroughCache` loads so a
|
|
16
|
+
post-mutation read cannot reuse or restore an earlier cached response.
|
|
17
|
+
- Added generic write-or-queue and chronological, scoped batch replay helpers.
|
|
18
|
+
- Added local pending-store subscriptions and a framework-free browser recovery
|
|
19
|
+
controller with silent startup/focus/reconnect/new-write replay plus bounded
|
|
20
|
+
exponential retry.
|
|
21
|
+
- Documented the IndexedDB database/store-version topology constraint for host
|
|
22
|
+
applications that initialize more than one object store.
|
|
23
|
+
|
|
3
24
|
## 0.1.1 - 2026-08-10
|
|
4
25
|
|
|
5
26
|
- Added unique pending-write snapshot identities and atomic conditional
|
package/README.md
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# @bayonai/offline
|
|
2
2
|
|
|
3
|
-
Reusable offline read-cache
|
|
3
|
+
Reusable offline read-cache, pending-write, and silent browser-recovery
|
|
4
|
+
primitives.
|
|
4
5
|
|
|
5
6
|
This package owns generic browser and memory storage behavior. Host apps own
|
|
6
7
|
their domain records, remote APIs, cache prefixes, database names, and sync
|
|
@@ -23,6 +24,7 @@ import {
|
|
|
23
24
|
createBrowserReadCache,
|
|
24
25
|
createReadCacheKey,
|
|
25
26
|
loadReadCacheResource,
|
|
27
|
+
pruneReadCache,
|
|
26
28
|
} from "@bayonai/offline";
|
|
27
29
|
|
|
28
30
|
const cache = createBrowserReadCache({
|
|
@@ -48,6 +50,21 @@ const projects = await loadReadCacheResource({
|
|
|
48
50
|
});
|
|
49
51
|
```
|
|
50
52
|
|
|
53
|
+
After a successful write, use `readThroughCache({ forceFresh: true })` when
|
|
54
|
+
the next read must be server-confirmed rather than a pre-write cached or
|
|
55
|
+
in-flight response. Concurrent ordinary reads for the same cache/key share one
|
|
56
|
+
fresh load; a forced-fresh read starts a new load after invalidating the key.
|
|
57
|
+
|
|
58
|
+
Read-cache retention is deliberately opt-in. It removes only valid cache
|
|
59
|
+
envelopes older than the chosen lifetime; it never affects pending writes.
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
const removed = await pruneReadCache({
|
|
63
|
+
cache,
|
|
64
|
+
maxAgeMs: 7 * 24 * 60 * 60_000,
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
51
68
|
## Pending Writes
|
|
52
69
|
|
|
53
70
|
```ts
|
|
@@ -81,6 +98,65 @@ await syncPendingWrite({
|
|
|
81
98
|
});
|
|
82
99
|
```
|
|
83
100
|
|
|
101
|
+
For a browser application that wants durable, silent recovery, mount the
|
|
102
|
+
headless controller once for the active account or workspace:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import {
|
|
106
|
+
createBrowserPendingWriteRecovery,
|
|
107
|
+
createBrowserPendingWriteRecoveryCoordination,
|
|
108
|
+
runPendingWrite,
|
|
109
|
+
summarizePendingWrites,
|
|
110
|
+
} from "@bayonai/offline";
|
|
111
|
+
|
|
112
|
+
const coordination = createBrowserPendingWriteRecoveryCoordination({
|
|
113
|
+
// Scope names must be stable per user/workspace and unique to this app.
|
|
114
|
+
channelName: `my-app:pending-recovery:${currentUser.id}`,
|
|
115
|
+
leaseName: `my-app:pending-recovery:${currentUser.id}`,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const recovery = createBrowserPendingWriteRecovery({
|
|
119
|
+
coordination,
|
|
120
|
+
scopeKey: currentUser.id,
|
|
121
|
+
select: (record) => record.payload.userId === currentUser.id,
|
|
122
|
+
store,
|
|
123
|
+
sync: (mutation) => replayMutation(mutation),
|
|
124
|
+
onError: (error) => console.error("Pending replay failed", { error }),
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
recovery.start(); // silent initial, focus, online, and local-set recovery
|
|
128
|
+
|
|
129
|
+
const result = await runPendingWrite({
|
|
130
|
+
isOnline: () => navigator.onLine,
|
|
131
|
+
write: () => saveRemotely(),
|
|
132
|
+
shouldQueue: isRetryableNetworkError,
|
|
133
|
+
enqueue: () => store.set(createPendingMutation()),
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// On unmount or account change:
|
|
137
|
+
recovery.stop();
|
|
138
|
+
coordination.close();
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The controller never creates product UI. It preserves failed writes locally,
|
|
142
|
+
retries remaining selected writes with bounded exponential backoff, and exposes
|
|
143
|
+
only `onResult`/`onError` callbacks for host diagnostics or telemetry. Stores
|
|
144
|
+
also expose a local-instance `subscribe` API; it is not a cross-tab delivery
|
|
145
|
+
mechanism.
|
|
146
|
+
|
|
147
|
+
When coordination is supplied, a queued write wakes peer tabs through
|
|
148
|
+
`BroadcastChannel`, and each recovery attempt acquires a non-blocking
|
|
149
|
+
`navigator.locks` lease when supported. Browsers without either API recover in
|
|
150
|
+
the current tab as before. Remote write handlers must remain idempotent because
|
|
151
|
+
leases do not cover other devices or every browser failure mode.
|
|
152
|
+
|
|
153
|
+
Use generic record summaries when an app needs to render its own status:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const summary = summarizePendingWrites(await store.list());
|
|
157
|
+
// { pendingCount, syncingCount, failedCount, totalCount }
|
|
158
|
+
```
|
|
159
|
+
|
|
84
160
|
Each call to `set` assigns a unique `snapshotId`. Sync status updates and
|
|
85
161
|
successful cleanup compare that identity inside a single storage transaction,
|
|
86
162
|
so a newer local write cannot be overwritten or deleted by an older sync.
|
|
@@ -115,6 +191,11 @@ Host apps are also responsible for:
|
|
|
115
191
|
- Deciding when to clear browser storage, such as on sign-out.
|
|
116
192
|
- Providing remote read and write functions.
|
|
117
193
|
|
|
194
|
+
Use a separate IndexedDB database for independently initialized stores unless
|
|
195
|
+
the host coordinates a database-version upgrade that creates every required
|
|
196
|
+
object store. IndexedDB cannot add a missing store when an existing database is
|
|
197
|
+
opened at the same version.
|
|
198
|
+
|
|
118
199
|
## Package Scripts
|
|
119
200
|
|
|
120
201
|
```bash
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export type BrowserRecoveryMessageChannel = {
|
|
2
|
+
addEventListener: (type: "message", listener: () => void) => void;
|
|
3
|
+
close: () => void;
|
|
4
|
+
postMessage: (message: "pending-write-recovery") => void;
|
|
5
|
+
removeEventListener: (type: "message", listener: () => void) => void;
|
|
6
|
+
};
|
|
7
|
+
export type BrowserRecoveryLockManager = {
|
|
8
|
+
request: <T>(name: string, options: {
|
|
9
|
+
ifAvailable: true;
|
|
10
|
+
}, callback: (lock: unknown | null) => Promise<T | null>) => Promise<T | null>;
|
|
11
|
+
};
|
|
12
|
+
export type BrowserPendingWriteRecoveryCoordination = {
|
|
13
|
+
close: () => void;
|
|
14
|
+
notify: () => void;
|
|
15
|
+
runExclusive: <T>(attempt: () => Promise<T>) => Promise<T | null>;
|
|
16
|
+
subscribe: (listener: () => void) => () => void;
|
|
17
|
+
};
|
|
18
|
+
export declare function createBrowserPendingWriteRecoveryCoordination({ channelName, leaseName, channel, locks, }: {
|
|
19
|
+
channel?: BrowserRecoveryMessageChannel | null;
|
|
20
|
+
channelName: string;
|
|
21
|
+
leaseName: string;
|
|
22
|
+
locks?: BrowserRecoveryLockManager | null;
|
|
23
|
+
}): BrowserPendingWriteRecoveryCoordination;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export function createBrowserPendingWriteRecoveryCoordination({ channelName, leaseName, channel = createDefaultChannel(channelName), locks = readDefaultLockManager(), }) {
|
|
2
|
+
const listeners = new Set();
|
|
3
|
+
const handleMessage = () => {
|
|
4
|
+
for (const listener of listeners) {
|
|
5
|
+
try {
|
|
6
|
+
listener();
|
|
7
|
+
}
|
|
8
|
+
catch (error) {
|
|
9
|
+
console.error("[Bayon offline] Cross-tab recovery listener failed.", {
|
|
10
|
+
channelName,
|
|
11
|
+
error,
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
channel?.addEventListener("message", handleMessage);
|
|
17
|
+
return {
|
|
18
|
+
close() {
|
|
19
|
+
channel?.removeEventListener("message", handleMessage);
|
|
20
|
+
channel?.close();
|
|
21
|
+
listeners.clear();
|
|
22
|
+
},
|
|
23
|
+
notify() {
|
|
24
|
+
try {
|
|
25
|
+
channel?.postMessage("pending-write-recovery");
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
console.error("[Bayon offline] Unable to wake cross-tab recovery.", {
|
|
29
|
+
channelName,
|
|
30
|
+
error,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
async runExclusive(attempt) {
|
|
35
|
+
if (!locks) {
|
|
36
|
+
return attempt();
|
|
37
|
+
}
|
|
38
|
+
return locks.request(leaseName, { ifAvailable: true }, (lock) => lock ? attempt() : Promise.resolve(null));
|
|
39
|
+
},
|
|
40
|
+
subscribe(listener) {
|
|
41
|
+
listeners.add(listener);
|
|
42
|
+
return () => listeners.delete(listener);
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function createDefaultChannel(name) {
|
|
47
|
+
if (typeof BroadcastChannel === "undefined") {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return new BroadcastChannel(name);
|
|
51
|
+
}
|
|
52
|
+
function readDefaultLockManager() {
|
|
53
|
+
if (typeof navigator === "undefined") {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
return navigator.locks ?? null;
|
|
57
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type PendingWriteRecord, type PendingWriteStore, type PendingWriteSync, type SyncPendingWritesResult } from "./pendingWrites";
|
|
2
|
+
import type { BrowserPendingWriteRecoveryCoordination } from "./browserCoordination";
|
|
3
|
+
export declare const initialPendingWriteRetryDelayMs = 2000;
|
|
4
|
+
export declare const maxPendingWriteRetryDelayMs = 60000;
|
|
5
|
+
export type BrowserPendingWriteRecoveryEnvironment = {
|
|
6
|
+
addEventListener: (type: "focus" | "offline" | "online", listener: () => void) => void;
|
|
7
|
+
clearTimeout: (timer: ReturnType<typeof setTimeout>) => void;
|
|
8
|
+
isOnline: () => boolean;
|
|
9
|
+
removeEventListener: (type: "focus" | "offline" | "online", listener: () => void) => void;
|
|
10
|
+
setTimeout: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
|
|
11
|
+
};
|
|
12
|
+
export type BrowserPendingWriteRecovery<Payload> = {
|
|
13
|
+
/** Signals that a caller has persisted a record outside the store subscription. */
|
|
14
|
+
notifyQueued: () => void;
|
|
15
|
+
/** Runs one immediate, silent recovery attempt when the browser is online. */
|
|
16
|
+
recoverNow: () => Promise<SyncPendingWritesResult | null>;
|
|
17
|
+
start: () => void;
|
|
18
|
+
stop: () => void;
|
|
19
|
+
};
|
|
20
|
+
export declare function createBrowserPendingWriteRecovery<Payload>({ environment, coordination, initialRetryDelayMs, maxRetryDelayMs, onError, onResult, scopeKey, select, store, sync, }: {
|
|
21
|
+
/** Optional BroadcastChannel/Web Locks coordination supplied by the package factory. */
|
|
22
|
+
coordination?: BrowserPendingWriteRecoveryCoordination;
|
|
23
|
+
environment?: BrowserPendingWriteRecoveryEnvironment;
|
|
24
|
+
initialRetryDelayMs?: number;
|
|
25
|
+
maxRetryDelayMs?: number;
|
|
26
|
+
/** Diagnostic callback only. Recovery never renders or presents product UI. */
|
|
27
|
+
onError?: (error: unknown) => void;
|
|
28
|
+
/** Diagnostic callback only. Recovery never renders or presents product UI. */
|
|
29
|
+
onResult?: (result: SyncPendingWritesResult) => void;
|
|
30
|
+
scopeKey?: string;
|
|
31
|
+
select?: (record: PendingWriteRecord<Payload>) => boolean;
|
|
32
|
+
store: PendingWriteStore<Payload>;
|
|
33
|
+
sync: PendingWriteSync<Payload>;
|
|
34
|
+
}): BrowserPendingWriteRecovery<Payload>;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { syncPendingWrites, } from "./pendingWrites.js";
|
|
2
|
+
export const initialPendingWriteRetryDelayMs = 2_000;
|
|
3
|
+
export const maxPendingWriteRetryDelayMs = 60_000;
|
|
4
|
+
export function createBrowserPendingWriteRecovery({ environment = createDefaultBrowserRecoveryEnvironment(), coordination, initialRetryDelayMs = initialPendingWriteRetryDelayMs, maxRetryDelayMs = maxPendingWriteRetryDelayMs, onError, onResult, scopeKey = "all", select = () => true, store, sync, }) {
|
|
5
|
+
let active = false;
|
|
6
|
+
let retryDelayMs = Math.max(0, initialRetryDelayMs);
|
|
7
|
+
let retryTimer;
|
|
8
|
+
let recoveryPromise;
|
|
9
|
+
let immediateRecoveryRequested = false;
|
|
10
|
+
let unsubscribePeerWakeups;
|
|
11
|
+
let unsubscribe;
|
|
12
|
+
function clearRetryTimer() {
|
|
13
|
+
if (retryTimer) {
|
|
14
|
+
environment.clearTimeout(retryTimer);
|
|
15
|
+
}
|
|
16
|
+
retryTimer = undefined;
|
|
17
|
+
}
|
|
18
|
+
function emitResult(result) {
|
|
19
|
+
try {
|
|
20
|
+
onResult?.(result);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
console.error("[Bayon offline] Pending-write recovery result listener failed.", {
|
|
24
|
+
error,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function emitError(error) {
|
|
29
|
+
console.error("[Bayon offline] Pending-write recovery failed.", {
|
|
30
|
+
error,
|
|
31
|
+
scopeKey,
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
onError?.(error);
|
|
35
|
+
}
|
|
36
|
+
catch (callbackError) {
|
|
37
|
+
console.error("[Bayon offline] Pending-write recovery error listener failed.", {
|
|
38
|
+
callbackError,
|
|
39
|
+
scopeKey,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function scheduleRetry() {
|
|
44
|
+
if (!active || !environment.isOnline() || retryTimer) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
retryTimer = environment.setTimeout(() => {
|
|
48
|
+
retryTimer = undefined;
|
|
49
|
+
void recoverNow();
|
|
50
|
+
}, retryDelayMs);
|
|
51
|
+
retryDelayMs = Math.min(Math.max(initialRetryDelayMs, retryDelayMs * 2), Math.max(initialRetryDelayMs, maxRetryDelayMs));
|
|
52
|
+
}
|
|
53
|
+
function recoverNow() {
|
|
54
|
+
if (!environment.isOnline()) {
|
|
55
|
+
clearRetryTimer();
|
|
56
|
+
return Promise.resolve(null);
|
|
57
|
+
}
|
|
58
|
+
if (recoveryPromise) {
|
|
59
|
+
return recoveryPromise;
|
|
60
|
+
}
|
|
61
|
+
const attempt = (async () => {
|
|
62
|
+
try {
|
|
63
|
+
const run = () => syncPendingWrites({
|
|
64
|
+
scopeKey,
|
|
65
|
+
select,
|
|
66
|
+
store,
|
|
67
|
+
sync,
|
|
68
|
+
});
|
|
69
|
+
const result = coordination
|
|
70
|
+
? await coordination.runExclusive(run)
|
|
71
|
+
: await run();
|
|
72
|
+
if (!result) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
emitResult(result);
|
|
76
|
+
if (result.remaining > 0) {
|
|
77
|
+
scheduleRetry();
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
retryDelayMs = Math.max(0, initialRetryDelayMs);
|
|
81
|
+
}
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
emitError(error);
|
|
86
|
+
scheduleRetry();
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
})();
|
|
90
|
+
recoveryPromise = attempt.finally(() => {
|
|
91
|
+
recoveryPromise = undefined;
|
|
92
|
+
if (active && immediateRecoveryRequested) {
|
|
93
|
+
immediateRecoveryRequested = false;
|
|
94
|
+
triggerImmediateRecovery();
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
return recoveryPromise;
|
|
98
|
+
}
|
|
99
|
+
function triggerImmediateRecovery() {
|
|
100
|
+
if (!active) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
immediateRecoveryRequested ||= Boolean(recoveryPromise);
|
|
104
|
+
clearRetryTimer();
|
|
105
|
+
retryDelayMs = Math.max(0, initialRetryDelayMs);
|
|
106
|
+
void recoverNow();
|
|
107
|
+
}
|
|
108
|
+
function handleOffline() {
|
|
109
|
+
clearRetryTimer();
|
|
110
|
+
}
|
|
111
|
+
function handleStoreChange(change) {
|
|
112
|
+
if (change.type === "set") {
|
|
113
|
+
coordination?.notify();
|
|
114
|
+
triggerImmediateRecovery();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
notifyQueued() {
|
|
119
|
+
coordination?.notify();
|
|
120
|
+
triggerImmediateRecovery();
|
|
121
|
+
},
|
|
122
|
+
recoverNow,
|
|
123
|
+
start() {
|
|
124
|
+
if (active) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
active = true;
|
|
128
|
+
unsubscribe = store.subscribe(handleStoreChange);
|
|
129
|
+
unsubscribePeerWakeups = coordination?.subscribe(triggerImmediateRecovery);
|
|
130
|
+
environment.addEventListener("focus", triggerImmediateRecovery);
|
|
131
|
+
environment.addEventListener("online", triggerImmediateRecovery);
|
|
132
|
+
environment.addEventListener("offline", handleOffline);
|
|
133
|
+
if (environment.isOnline()) {
|
|
134
|
+
triggerImmediateRecovery();
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
stop() {
|
|
138
|
+
if (!active) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
active = false;
|
|
142
|
+
clearRetryTimer();
|
|
143
|
+
unsubscribe?.();
|
|
144
|
+
unsubscribe = undefined;
|
|
145
|
+
unsubscribePeerWakeups?.();
|
|
146
|
+
unsubscribePeerWakeups = undefined;
|
|
147
|
+
environment.removeEventListener("focus", triggerImmediateRecovery);
|
|
148
|
+
environment.removeEventListener("online", triggerImmediateRecovery);
|
|
149
|
+
environment.removeEventListener("offline", handleOffline);
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function createDefaultBrowserRecoveryEnvironment() {
|
|
154
|
+
const target = typeof window === "undefined" ? null : window;
|
|
155
|
+
return {
|
|
156
|
+
addEventListener(type, listener) {
|
|
157
|
+
target?.addEventListener(type, listener);
|
|
158
|
+
},
|
|
159
|
+
clearTimeout(timer) {
|
|
160
|
+
globalThis.clearTimeout(timer);
|
|
161
|
+
},
|
|
162
|
+
isOnline() {
|
|
163
|
+
return typeof navigator !== "undefined" && navigator.onLine;
|
|
164
|
+
},
|
|
165
|
+
removeEventListener(type, listener) {
|
|
166
|
+
target?.removeEventListener(type, listener);
|
|
167
|
+
},
|
|
168
|
+
setTimeout(callback, delayMs) {
|
|
169
|
+
return globalThis.setTimeout(callback, delayMs);
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
package/dist/idbDriver.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ export type BrowserKeyValueDriver = {
|
|
|
5
5
|
deleteIf: (key: string, predicate: KeyValuePredicate) => Promise<boolean>;
|
|
6
6
|
get: (key: string) => Promise<unknown | null>;
|
|
7
7
|
list: () => Promise<unknown[]>;
|
|
8
|
+
listEntries: () => Promise<Array<{
|
|
9
|
+
key: string;
|
|
10
|
+
value: unknown;
|
|
11
|
+
}>>;
|
|
8
12
|
set: (key: string, value: unknown) => Promise<void>;
|
|
9
13
|
setIf: (key: string, value: unknown, predicate: KeyValuePredicate) => Promise<boolean>;
|
|
10
14
|
};
|
package/dist/idbDriver.js
CHANGED
|
@@ -87,6 +87,30 @@ export function createIdbKeyValueDriver({ databaseName, databaseVersion = 1, ind
|
|
|
87
87
|
timeoutMs: operationTimeoutMs,
|
|
88
88
|
});
|
|
89
89
|
},
|
|
90
|
+
async listEntries() {
|
|
91
|
+
return runBrowserStorageOperation({
|
|
92
|
+
fallback: [],
|
|
93
|
+
operationName: "list object-store entries",
|
|
94
|
+
operation: async () => {
|
|
95
|
+
const database = await databasePromise;
|
|
96
|
+
// Keys and values must come from one transaction. Separate database
|
|
97
|
+
// reads could pair a key from one cross-tab storage state with a
|
|
98
|
+
// value from another, causing retention code to delete the wrong key.
|
|
99
|
+
const transaction = database.transaction(storeName, "readonly");
|
|
100
|
+
const objectStore = transaction.objectStore(storeName);
|
|
101
|
+
const [keys, values] = await Promise.all([
|
|
102
|
+
objectStore.getAllKeys(),
|
|
103
|
+
objectStore.getAll(),
|
|
104
|
+
]);
|
|
105
|
+
await transaction.done;
|
|
106
|
+
return keys.map((key, index) => ({
|
|
107
|
+
key: String(key),
|
|
108
|
+
value: values[index],
|
|
109
|
+
}));
|
|
110
|
+
},
|
|
111
|
+
timeoutMs: operationTimeoutMs,
|
|
112
|
+
});
|
|
113
|
+
},
|
|
90
114
|
async set(key, value) {
|
|
91
115
|
await runBrowserStorageOperation({
|
|
92
116
|
fallback: undefined,
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/pendingWrites.d.ts
CHANGED
|
@@ -25,6 +25,19 @@ export type PendingWriteDriver = {
|
|
|
25
25
|
setIf: (key: string, value: unknown, predicate: PendingWritePredicate) => Promise<boolean>;
|
|
26
26
|
};
|
|
27
27
|
export type PendingWritePredicate = (value: unknown | null) => boolean;
|
|
28
|
+
export type PendingWriteStoreChange<Payload = unknown> = {
|
|
29
|
+
record: PendingWriteRecord<Payload>;
|
|
30
|
+
type: "set";
|
|
31
|
+
} | {
|
|
32
|
+
id: string;
|
|
33
|
+
type: "clear";
|
|
34
|
+
} | {
|
|
35
|
+
type: "clearAll";
|
|
36
|
+
} | {
|
|
37
|
+
record: PendingWriteRecord<Payload>;
|
|
38
|
+
type: "replace";
|
|
39
|
+
};
|
|
40
|
+
export type PendingWriteStoreChangeListener<Payload = unknown> = (change: PendingWriteStoreChange<Payload>) => void;
|
|
28
41
|
export type PendingWriteStore<Payload = unknown> = {
|
|
29
42
|
clear: (id: string) => Promise<void>;
|
|
30
43
|
clearAll: () => Promise<void>;
|
|
@@ -34,6 +47,11 @@ export type PendingWriteStore<Payload = unknown> = {
|
|
|
34
47
|
list: () => Promise<Array<PendingWriteRecord<Payload>>>;
|
|
35
48
|
replaceIfSnapshotId: (id: string, snapshotId: string, record: PendingWriteRecord<Payload>) => Promise<boolean>;
|
|
36
49
|
set: (record: PendingWriteRecordInput<Payload>) => Promise<PendingWriteRecord<Payload>>;
|
|
50
|
+
/**
|
|
51
|
+
* Observes changes made through this in-memory store instance. It deliberately
|
|
52
|
+
* does not claim cross-tab/process delivery.
|
|
53
|
+
*/
|
|
54
|
+
subscribe: (listener: PendingWriteStoreChangeListener<Payload>) => () => void;
|
|
37
55
|
};
|
|
38
56
|
export type PendingWriteStoreOptions<Payload = unknown> = {
|
|
39
57
|
keyPrefix: string;
|
|
@@ -60,6 +78,29 @@ export type SyncPendingWriteResult = {
|
|
|
60
78
|
error: string;
|
|
61
79
|
status: "failed";
|
|
62
80
|
};
|
|
81
|
+
export type SyncPendingWritesResult = {
|
|
82
|
+
attempted: number;
|
|
83
|
+
failed: number;
|
|
84
|
+
idle: number;
|
|
85
|
+
/** Records still selected after this attempt, including newer superseding writes. */
|
|
86
|
+
remaining: number;
|
|
87
|
+
superseded: number;
|
|
88
|
+
synced: number;
|
|
89
|
+
};
|
|
90
|
+
export type PendingWriteSync<Payload> = (payload: Payload) => Promise<unknown>;
|
|
91
|
+
export type RunPendingWriteResult<TResult, TQueued> = {
|
|
92
|
+
result: TResult;
|
|
93
|
+
status: "synced";
|
|
94
|
+
} | {
|
|
95
|
+
queued: TQueued;
|
|
96
|
+
status: "queued";
|
|
97
|
+
};
|
|
98
|
+
export type PendingWriteSummary = {
|
|
99
|
+
failedCount: number;
|
|
100
|
+
pendingCount: number;
|
|
101
|
+
syncingCount: number;
|
|
102
|
+
totalCount: number;
|
|
103
|
+
};
|
|
63
104
|
export declare function createPendingWriteStore<Payload = unknown>(driver: PendingWriteDriver, { keyPrefix, normalizeLegacyRecord, normalizePayload, schemaVersion, }: PendingWriteStoreOptions<Payload>): PendingWriteStore<Payload>;
|
|
64
105
|
export declare function createMemoryPendingWriteDriver(): PendingWriteDriver;
|
|
65
106
|
export declare function createBrowserPendingWriteDriver({ databaseName, databaseVersion, indexedDB, operationTimeoutMs, storeName, }: Omit<BrowserPendingWriteStoreOptions, "keyPrefix" | "normalizePayload" | "schemaVersion">): PendingWriteDriver | null;
|
|
@@ -69,5 +110,27 @@ export declare function createPendingWriteSnapshotId(): `${string}-${string}-${s
|
|
|
69
110
|
export declare function syncPendingWrite<Payload>({ id, store, sync, }: {
|
|
70
111
|
id: string;
|
|
71
112
|
store: PendingWriteStore<Payload>;
|
|
72
|
-
sync:
|
|
113
|
+
sync: PendingWriteSync<Payload>;
|
|
73
114
|
}): Promise<SyncPendingWriteResult>;
|
|
115
|
+
/**
|
|
116
|
+
* Replays selected writes oldest first and coalesces overlapping runs for the
|
|
117
|
+
* same store/scope. Callers own the selection predicate and idempotent remote
|
|
118
|
+
* mutation semantics.
|
|
119
|
+
*/
|
|
120
|
+
export declare function syncPendingWrites<Payload>({ scopeKey, select, store, sync, }: {
|
|
121
|
+
scopeKey?: string;
|
|
122
|
+
select?: (record: PendingWriteRecord<Payload>) => boolean;
|
|
123
|
+
store: PendingWriteStore<Payload>;
|
|
124
|
+
sync: PendingWriteSync<Payload>;
|
|
125
|
+
}): Promise<SyncPendingWritesResult>;
|
|
126
|
+
/**
|
|
127
|
+
* Attempts a remote write now and persists a caller-created durable fallback
|
|
128
|
+
* only when offline or when the supplied retry classifier accepts the error.
|
|
129
|
+
*/
|
|
130
|
+
export declare function runPendingWrite<TResult, TQueued>({ enqueue, isOnline, shouldQueue, write, }: {
|
|
131
|
+
enqueue: () => Promise<TQueued>;
|
|
132
|
+
isOnline: () => boolean;
|
|
133
|
+
shouldQueue: (error: unknown) => boolean;
|
|
134
|
+
write: () => Promise<TResult>;
|
|
135
|
+
}): Promise<RunPendingWriteResult<TResult, TQueued>>;
|
|
136
|
+
export declare function summarizePendingWrites<Payload>(records: Array<PendingWriteRecord<Payload>>): PendingWriteSummary;
|