@koolbase/react-native 9.2.0 → 10.0.1
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 +1348 -0
- package/README.md +403 -568
- package/dist/{auth-storage.d.ts → cjs/auth-storage.d.ts} +1 -1
- package/dist/cjs/index.d.ts +19 -0
- package/dist/cjs/index.js +125 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/platform.d.ts +2 -0
- package/dist/cjs/platform.js +43 -0
- package/dist/esm/auth-storage.d.ts +26 -0
- package/dist/esm/auth-storage.js +100 -0
- package/dist/esm/index.d.ts +19 -0
- package/dist/esm/index.js +106 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/platform.d.ts +2 -0
- package/dist/esm/platform.js +37 -0
- package/package.json +30 -30
- package/dist/analytics.d.ts +0 -24
- package/dist/analytics.js +0 -114
- package/dist/apple-auth.d.ts +0 -22
- package/dist/apple-auth.js +0 -74
- package/dist/auth-errors.d.ts +0 -117
- package/dist/auth-errors.js +0 -250
- package/dist/auth.d.ts +0 -213
- package/dist/auth.js +0 -810
- package/dist/cache-store.d.ts +0 -50
- package/dist/cache-store.js +0 -197
- package/dist/code-push.d.ts +0 -59
- package/dist/code-push.js +0 -255
- package/dist/conflict.d.ts +0 -80
- package/dist/conflict.js +0 -84
- package/dist/database-errors.d.ts +0 -101
- package/dist/database-errors.js +0 -200
- package/dist/database.d.ts +0 -298
- package/dist/database.js +0 -852
- package/dist/device-id.d.ts +0 -1
- package/dist/device-id.js +0 -60
- package/dist/device-metadata.d.ts +0 -36
- package/dist/device-metadata.js +0 -102
- package/dist/errors.d.ts +0 -64
- package/dist/errors.js +0 -85
- package/dist/flags.d.ts +0 -15
- package/dist/flags.js +0 -76
- package/dist/function-errors.d.ts +0 -51
- package/dist/function-errors.js +0 -103
- package/dist/functions.d.ts +0 -15
- package/dist/functions.js +0 -83
- package/dist/index.d.ts +0 -49
- package/dist/index.js +0 -204
- package/dist/logic-engine.d.ts +0 -17
- package/dist/logic-engine.js +0 -193
- package/dist/messaging.d.ts +0 -13
- package/dist/messaging.js +0 -36
- package/dist/offline-state.d.ts +0 -97
- package/dist/offline-state.js +0 -200
- package/dist/pending-write.d.ts +0 -47
- package/dist/pending-write.js +0 -22
- package/dist/realtime.d.ts +0 -44
- package/dist/realtime.js +0 -195
- package/dist/record.d.ts +0 -2
- package/dist/record.js +0 -23
- package/dist/storage-errors.d.ts +0 -163
- package/dist/storage-errors.js +0 -253
- package/dist/storage.d.ts +0 -198
- package/dist/storage.js +0 -451
- package/dist/sync-engine.d.ts +0 -30
- package/dist/sync-engine.js +0 -290
- package/dist/types.d.ts +0 -487
- package/dist/types.js +0 -40
- /package/dist/{auth-storage.js → cjs/auth-storage.js} +0 -0
package/dist/offline-state.d.ts
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
export declare function recordKey(userId: string, collection: string, recordId: string): string;
|
|
2
|
-
/** A write waiting to be sent. */
|
|
3
|
-
export interface QueuedWrite {
|
|
4
|
-
id: string;
|
|
5
|
-
operation: 'insert' | 'update' | 'delete';
|
|
6
|
-
collection: string;
|
|
7
|
-
recordId?: string;
|
|
8
|
-
data?: Record<string, unknown>;
|
|
9
|
-
/**
|
|
10
|
-
* The record as the client last saw it, for update and delete.
|
|
11
|
-
*
|
|
12
|
-
* Copied in at enqueue time rather than looked up at replay: the record cache
|
|
13
|
-
* can be evicted or invalidated in between, and a write whose baseline
|
|
14
|
-
* depends on something else surviving is not durable. From here on the write
|
|
15
|
-
* is self-contained.
|
|
16
|
-
*/
|
|
17
|
-
baseline?: Record<string, unknown>;
|
|
18
|
-
/** The revision that baseline carried, sent so the server can refuse atomically. */
|
|
19
|
-
baseRevision?: number;
|
|
20
|
-
retries: number;
|
|
21
|
-
enqueuedAt: string;
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Why a write is waiting for a decision.
|
|
25
|
-
*
|
|
26
|
-
* Kept distinct because they are different situations and an app showing them
|
|
27
|
-
* to someone should say different things. One means two people changed the same
|
|
28
|
-
* thing; the other means we never knew what the change was based on, so there is
|
|
29
|
-
* nothing to compare it against.
|
|
30
|
-
*/
|
|
31
|
-
export type ConflictReason =
|
|
32
|
-
/** The record moved between the change being made and the queue reaching it. */
|
|
33
|
-
'concurrent_modification'
|
|
34
|
-
/**
|
|
35
|
-
* Queued by a version of this SDK that did not record what the change was
|
|
36
|
-
* composed against. It cannot be replayed safely — there is nothing to check
|
|
37
|
-
* it against — so it waits rather than overwriting whatever is there now.
|
|
38
|
-
*/
|
|
39
|
-
| 'baseline_unavailable'
|
|
40
|
-
/**
|
|
41
|
-
* The server refused the write for a reason retrying cannot change — the data
|
|
42
|
-
* no longer satisfies the collection's rules, the record is gone, the caller
|
|
43
|
-
* is not permitted, a unique value is taken.
|
|
44
|
-
*
|
|
45
|
-
* Held rather than retried or dropped. Retrying sends identical bytes to
|
|
46
|
-
* identical rules; dropping loses a change the user believes is saved. Neither
|
|
47
|
-
* tells them anything.
|
|
48
|
-
*/
|
|
49
|
-
| 'rejected';
|
|
50
|
-
/** A write the server would not apply, held until someone decides. */
|
|
51
|
-
export interface QueuedConflict {
|
|
52
|
-
reason: ConflictReason;
|
|
53
|
-
id: string;
|
|
54
|
-
operation: 'insert' | 'update' | 'delete';
|
|
55
|
-
collection: string;
|
|
56
|
-
recordId: string;
|
|
57
|
-
local?: Record<string, unknown>;
|
|
58
|
-
baseline?: Record<string, unknown>;
|
|
59
|
-
server?: Record<string, unknown>;
|
|
60
|
-
baseRevision?: number;
|
|
61
|
-
serverRevision?: number;
|
|
62
|
-
/** What the server said, when it refused for a terminal reason. */
|
|
63
|
-
message?: string;
|
|
64
|
-
createdAt: string;
|
|
65
|
-
}
|
|
66
|
-
export interface OfflineState {
|
|
67
|
-
pending: QueuedWrite[];
|
|
68
|
-
conflicts: QueuedConflict[];
|
|
69
|
-
}
|
|
70
|
-
export declare class OfflineStateTooLargeError extends Error {
|
|
71
|
-
constructor(bytes: number);
|
|
72
|
-
}
|
|
73
|
-
export declare function readOfflineState(userId: string): Promise<OfflineState>;
|
|
74
|
-
/**
|
|
75
|
-
* Reads, mutates, and writes the state under the user's lock.
|
|
76
|
-
*
|
|
77
|
-
* Every mutation goes through here. A caller that reads and writes separately
|
|
78
|
-
* reintroduces the race this exists to prevent.
|
|
79
|
-
*/
|
|
80
|
-
export declare function mutateOfflineState(userId: string, mutate: (state: OfflineState) => void): Promise<void>;
|
|
81
|
-
/** Adds a write to the queue, under the user's lock. */
|
|
82
|
-
export declare function queueWrite(userId: string, write: Omit<QueuedWrite, 'retries' | 'enqueuedAt'>): Promise<void>;
|
|
83
|
-
/**
|
|
84
|
-
* Moves writes queued by an earlier version into the current state.
|
|
85
|
-
*
|
|
86
|
-
* Runs once, before any replay, and never contacts the network. Migration that
|
|
87
|
-
* depended on connectivity would give the same input two different outcomes
|
|
88
|
-
* depending on whether the device happened to be online at startup — which is
|
|
89
|
-
* how a bug becomes unreproducible.
|
|
90
|
-
*
|
|
91
|
-
* Inserts carry everything they need and simply move across. Updates and
|
|
92
|
-
* deletes do not: they were queued before baselines were recorded, so replaying
|
|
93
|
-
* one would apply it blindly and overwrite whatever changed in the meantime.
|
|
94
|
-
* They are preserved as waiting for a decision instead — the change is not lost,
|
|
95
|
-
* and nothing is written on a guess.
|
|
96
|
-
*/
|
|
97
|
-
export declare function migrateLegacyQueue(userId: string): Promise<void>;
|
package/dist/offline-state.js
DELETED
|
@@ -1,200 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.OfflineStateTooLargeError = void 0;
|
|
7
|
-
exports.recordKey = recordKey;
|
|
8
|
-
exports.readOfflineState = readOfflineState;
|
|
9
|
-
exports.mutateOfflineState = mutateOfflineState;
|
|
10
|
-
exports.queueWrite = queueWrite;
|
|
11
|
-
exports.migrateLegacyQueue = migrateLegacyQueue;
|
|
12
|
-
const async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage"));
|
|
13
|
-
/**
|
|
14
|
-
* The offline system's correctness-critical state: writes waiting to be sent,
|
|
15
|
-
* and writes the server refused because the record moved underneath them.
|
|
16
|
-
*
|
|
17
|
-
* Both live under one key so moving between them is a single write. A conflict
|
|
18
|
-
* recorded without removing the pending write would replay and be refused
|
|
19
|
-
* forever; a pending write removed without recording the conflict would lose a
|
|
20
|
-
* change the user believes is saved. Two keys admit both outcomes.
|
|
21
|
-
*
|
|
22
|
-
* Records are cached separately, per record. Putting them here would let a
|
|
23
|
-
* growing cache push this value past a storage ceiling and make the queue
|
|
24
|
-
* unreadable — losing the correctness-critical state to something incidental.
|
|
25
|
-
*/
|
|
26
|
-
const VERSION = 'v1';
|
|
27
|
-
function stateKey(userId) {
|
|
28
|
-
return `koolbase:${VERSION}:${userId}:offline-state`;
|
|
29
|
-
}
|
|
30
|
-
function recordKey(userId, collection, recordId) {
|
|
31
|
-
return `koolbase:${VERSION}:${userId}:record:${collection}:${recordId}`;
|
|
32
|
-
}
|
|
33
|
-
const EMPTY = { pending: [], conflicts: [] };
|
|
34
|
-
/**
|
|
35
|
-
* A conservative ceiling, below the lowest per-value limit any supported
|
|
36
|
-
* AsyncStorage implementation imposes.
|
|
37
|
-
*
|
|
38
|
-
* Not a claim about a platform maximum — a boundary that leaves headroom for
|
|
39
|
-
* rewriting and migration. A queue that cannot be written is a queue that
|
|
40
|
-
* silently stops accepting work, so the limit is enforced with an error rather
|
|
41
|
-
* than discovered.
|
|
42
|
-
*/
|
|
43
|
-
const MAX_STATE_BYTES = 1000000;
|
|
44
|
-
class OfflineStateTooLargeError extends Error {
|
|
45
|
-
constructor(bytes) {
|
|
46
|
-
super(`Offline state is ${bytes} bytes, above the ${MAX_STATE_BYTES} byte limit. ` +
|
|
47
|
-
'Sync or resolve what is queued before making more offline changes.');
|
|
48
|
-
this.name = 'OfflineStateTooLargeError';
|
|
49
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
exports.OfflineStateTooLargeError = OfflineStateTooLargeError;
|
|
53
|
-
/**
|
|
54
|
-
* Serialises access per user.
|
|
55
|
-
*
|
|
56
|
-
* A single setItem is one storage operation, but read-modify-write is not: two
|
|
57
|
-
* callers can both read, both modify, and the second write silently discards
|
|
58
|
-
* the first. Two components queueing a write in the same tick is enough. The
|
|
59
|
-
* lock is in-process — one JavaScript runtime is the assumption every React
|
|
60
|
-
* Native app satisfies, and the SDK does not promise more.
|
|
61
|
-
*/
|
|
62
|
-
/** UTF-8 byte length, without depending on TextEncoder being present. */
|
|
63
|
-
function byteLength(s) {
|
|
64
|
-
if (typeof TextEncoder !== 'undefined') {
|
|
65
|
-
return new TextEncoder().encode(s).length;
|
|
66
|
-
}
|
|
67
|
-
let bytes = 0;
|
|
68
|
-
for (let i = 0; i < s.length; i++) {
|
|
69
|
-
const c = s.codePointAt(i);
|
|
70
|
-
if (c > 0xffff)
|
|
71
|
-
i++; // surrogate pair, counted once
|
|
72
|
-
bytes += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
|
|
73
|
-
}
|
|
74
|
-
return bytes;
|
|
75
|
-
}
|
|
76
|
-
const locks = new Map();
|
|
77
|
-
async function withLock(userId, fn) {
|
|
78
|
-
const previous = locks.get(userId) ?? Promise.resolve();
|
|
79
|
-
let release = () => { };
|
|
80
|
-
const next = new Promise((resolve) => { release = resolve; });
|
|
81
|
-
locks.set(userId, previous.then(() => next));
|
|
82
|
-
await previous;
|
|
83
|
-
try {
|
|
84
|
-
return await fn();
|
|
85
|
-
}
|
|
86
|
-
finally {
|
|
87
|
-
release();
|
|
88
|
-
if (locks.get(userId) === next)
|
|
89
|
-
locks.delete(userId);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
async function readOfflineState(userId) {
|
|
93
|
-
try {
|
|
94
|
-
const raw = await async_storage_1.default.getItem(stateKey(userId));
|
|
95
|
-
if (!raw)
|
|
96
|
-
return { ...EMPTY, pending: [], conflicts: [] };
|
|
97
|
-
const parsed = JSON.parse(raw);
|
|
98
|
-
return { pending: parsed.pending ?? [], conflicts: parsed.conflicts ?? [] };
|
|
99
|
-
}
|
|
100
|
-
catch {
|
|
101
|
-
// Unreadable state is treated as empty rather than throwing: an app that
|
|
102
|
-
// cannot start is worse than one that has lost a queue it could not read
|
|
103
|
-
// anyway. The write path's size guard is what keeps this from happening.
|
|
104
|
-
return { pending: [], conflicts: [] };
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Reads, mutates, and writes the state under the user's lock.
|
|
109
|
-
*
|
|
110
|
-
* Every mutation goes through here. A caller that reads and writes separately
|
|
111
|
-
* reintroduces the race this exists to prevent.
|
|
112
|
-
*/
|
|
113
|
-
async function mutateOfflineState(userId, mutate) {
|
|
114
|
-
await withLock(userId, async () => {
|
|
115
|
-
const state = await readOfflineState(userId);
|
|
116
|
-
mutate(state);
|
|
117
|
-
const serialised = JSON.stringify(state);
|
|
118
|
-
// Bytes, not characters. String length undercounts anything outside ASCII —
|
|
119
|
-
// an accented name, any non-Latin script — so a limit measured in
|
|
120
|
-
// characters permits more than it claims, which is the wrong direction for
|
|
121
|
-
// a safety boundary. TextEncoder is not guaranteed in every React Native
|
|
122
|
-
// runtime, so fall back to a byte count computed directly.
|
|
123
|
-
const bytes = byteLength(serialised);
|
|
124
|
-
if (bytes > MAX_STATE_BYTES) {
|
|
125
|
-
throw new OfflineStateTooLargeError(bytes);
|
|
126
|
-
}
|
|
127
|
-
await async_storage_1.default.setItem(stateKey(userId), serialised);
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
/** Adds a write to the queue, under the user's lock. */
|
|
131
|
-
async function queueWrite(userId, write) {
|
|
132
|
-
await mutateOfflineState(userId, (state) => {
|
|
133
|
-
state.pending.push({
|
|
134
|
-
...write,
|
|
135
|
-
retries: 0,
|
|
136
|
-
enqueuedAt: new Date().toISOString(),
|
|
137
|
-
});
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
const LEGACY_QUEUE_VERSION = 'v1';
|
|
141
|
-
function legacyQueueKey(userId) {
|
|
142
|
-
return `koolbase:${LEGACY_QUEUE_VERSION}:${userId}:write_queue`;
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* Moves writes queued by an earlier version into the current state.
|
|
146
|
-
*
|
|
147
|
-
* Runs once, before any replay, and never contacts the network. Migration that
|
|
148
|
-
* depended on connectivity would give the same input two different outcomes
|
|
149
|
-
* depending on whether the device happened to be online at startup — which is
|
|
150
|
-
* how a bug becomes unreproducible.
|
|
151
|
-
*
|
|
152
|
-
* Inserts carry everything they need and simply move across. Updates and
|
|
153
|
-
* deletes do not: they were queued before baselines were recorded, so replaying
|
|
154
|
-
* one would apply it blindly and overwrite whatever changed in the meantime.
|
|
155
|
-
* They are preserved as waiting for a decision instead — the change is not lost,
|
|
156
|
-
* and nothing is written on a guess.
|
|
157
|
-
*/
|
|
158
|
-
async function migrateLegacyQueue(userId) {
|
|
159
|
-
const raw = await async_storage_1.default.getItem(legacyQueueKey(userId));
|
|
160
|
-
if (!raw)
|
|
161
|
-
return;
|
|
162
|
-
let legacy = [];
|
|
163
|
-
try {
|
|
164
|
-
legacy = JSON.parse(raw);
|
|
165
|
-
}
|
|
166
|
-
catch {
|
|
167
|
-
// Unreadable: nothing recoverable, and leaving the key would retry forever.
|
|
168
|
-
await async_storage_1.default.removeItem(legacyQueueKey(userId));
|
|
169
|
-
return;
|
|
170
|
-
}
|
|
171
|
-
await mutateOfflineState(userId, (state) => {
|
|
172
|
-
for (const w of legacy) {
|
|
173
|
-
const operation = w.type;
|
|
174
|
-
if (operation === 'insert') {
|
|
175
|
-
state.pending.push({
|
|
176
|
-
id: w.id,
|
|
177
|
-
operation: 'insert',
|
|
178
|
-
collection: w.collection,
|
|
179
|
-
recordId: w.recordId,
|
|
180
|
-
data: w.data,
|
|
181
|
-
retries: w.retries ?? 0,
|
|
182
|
-
enqueuedAt: w.createdAt ?? new Date().toISOString(),
|
|
183
|
-
});
|
|
184
|
-
continue;
|
|
185
|
-
}
|
|
186
|
-
if (!w.recordId)
|
|
187
|
-
continue;
|
|
188
|
-
state.conflicts.push({
|
|
189
|
-
id: w.id,
|
|
190
|
-
reason: 'baseline_unavailable',
|
|
191
|
-
operation,
|
|
192
|
-
collection: w.collection ?? '',
|
|
193
|
-
recordId: w.recordId,
|
|
194
|
-
local: w.data,
|
|
195
|
-
createdAt: w.createdAt ?? new Date().toISOString(),
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
});
|
|
199
|
-
await async_storage_1.default.removeItem(legacyQueueKey(userId));
|
|
200
|
-
}
|
package/dist/pending-write.d.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { QueuedWrite } from './offline-state';
|
|
2
|
-
/**
|
|
3
|
-
* A change made offline, waiting to be sent.
|
|
4
|
-
*
|
|
5
|
-
* The counterpart to KoolbaseConflict, one step earlier in the lifecycle: a
|
|
6
|
-
* conflict is a write the server refused; a pending write is one the server has
|
|
7
|
-
* not seen yet. Both are durable state an app should surface — a queue nobody
|
|
8
|
-
* can see accumulates invisibly, and the changes it holds feel saved to the
|
|
9
|
-
* user while existing only on this device.
|
|
10
|
-
*
|
|
11
|
-
* The case that makes this API matter: logout. Queues are per-user and survive
|
|
12
|
-
* logout by design, so a user signing out with pending writes walks away
|
|
13
|
-
* believing their edits saved — and they sync whenever that user next logs in
|
|
14
|
-
* on this device, which may be never. Warn before logout:
|
|
15
|
-
*
|
|
16
|
-
* ```ts
|
|
17
|
-
* const pending = await Koolbase.db.pendingWrites();
|
|
18
|
-
* if (pending.length > 0) {
|
|
19
|
-
* // "You have 3 unsynced changes. Sync now, or they wait until you
|
|
20
|
-
* // next sign in on this device."
|
|
21
|
-
* }
|
|
22
|
-
* ```
|
|
23
|
-
*
|
|
24
|
-
* This is a snapshot, not a live handle — re-read after a sync. Per-user:
|
|
25
|
-
* another account's queue on this device is not visible here.
|
|
26
|
-
*/
|
|
27
|
-
export interface PendingWrite {
|
|
28
|
-
id: string;
|
|
29
|
-
operation: 'insert' | 'update' | 'delete';
|
|
30
|
-
collection: string;
|
|
31
|
-
/** Absent for an insert the server has not yet assigned. */
|
|
32
|
-
recordId?: string;
|
|
33
|
-
/** What the user changed. Absent for a delete. */
|
|
34
|
-
data?: Record<string, unknown>;
|
|
35
|
-
enqueuedAt: string;
|
|
36
|
-
/** Failed send attempts so far. A count, not a policy — nothing drops it. */
|
|
37
|
-
attempts: number;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Maps the stored write to its public shape, field by field.
|
|
41
|
-
*
|
|
42
|
-
* Deliberately not a spread: the stored write carries baseline and baseRevision
|
|
43
|
-
* — replay mechanics, not contract. A spread would leak whatever the storage
|
|
44
|
-
* shape grows next; naming each field means new internals stay internal until
|
|
45
|
-
* someone chooses otherwise.
|
|
46
|
-
*/
|
|
47
|
-
export declare function toPendingWrite(w: QueuedWrite): PendingWrite;
|
package/dist/pending-write.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.toPendingWrite = toPendingWrite;
|
|
4
|
-
/**
|
|
5
|
-
* Maps the stored write to its public shape, field by field.
|
|
6
|
-
*
|
|
7
|
-
* Deliberately not a spread: the stored write carries baseline and baseRevision
|
|
8
|
-
* — replay mechanics, not contract. A spread would leak whatever the storage
|
|
9
|
-
* shape grows next; naming each field means new internals stay internal until
|
|
10
|
-
* someone chooses otherwise.
|
|
11
|
-
*/
|
|
12
|
-
function toPendingWrite(w) {
|
|
13
|
-
return {
|
|
14
|
-
id: w.id,
|
|
15
|
-
operation: w.operation,
|
|
16
|
-
collection: w.collection,
|
|
17
|
-
recordId: w.recordId,
|
|
18
|
-
data: w.data,
|
|
19
|
-
enqueuedAt: w.enqueuedAt,
|
|
20
|
-
attempts: w.retries,
|
|
21
|
-
};
|
|
22
|
-
}
|
package/dist/realtime.d.ts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { KoolbaseConfig, RealtimeCallback } from './types';
|
|
2
|
-
type TokenProvider = () => Promise<string | null>;
|
|
3
|
-
export declare class KoolbaseRealtime {
|
|
4
|
-
private config;
|
|
5
|
-
private getToken;
|
|
6
|
-
private ws;
|
|
7
|
-
private projectId;
|
|
8
|
-
private listeners;
|
|
9
|
-
private reconnectAttempts;
|
|
10
|
-
private reconnectTimer;
|
|
11
|
-
private connecting;
|
|
12
|
-
/**
|
|
13
|
-
* Identifies whose cache a seen record belongs in.
|
|
14
|
-
*
|
|
15
|
-
* The record cache is keyed by user, so without this a watched record would
|
|
16
|
-
* be filed under the wrong key — or under 'anonymous', which is worse than
|
|
17
|
-
* not caching at all: a baseline stored where it will never be read.
|
|
18
|
-
*/
|
|
19
|
-
private getUserId?;
|
|
20
|
-
constructor(config: KoolbaseConfig, getToken: TokenProvider, getUserId?: () => string | null);
|
|
21
|
-
/** Files a record seen over the socket, if we know whose it is. */
|
|
22
|
-
private cacheSeenRecord;
|
|
23
|
-
private forgetSeenRecord;
|
|
24
|
-
subscribe(collection: string, callback: RealtimeCallback): () => void;
|
|
25
|
-
private connect;
|
|
26
|
-
private sendSubscribe;
|
|
27
|
-
private sendUnsubscribe;
|
|
28
|
-
/**
|
|
29
|
-
* Reconnects with backoff, rather than every three seconds forever.
|
|
30
|
-
*
|
|
31
|
-
* A fixed interval is fine while a connection is merely interrupted and
|
|
32
|
-
* costly when it is not: a device with no network, a wrong URL, or a session
|
|
33
|
-
* the server will not accept retried indefinitely, draining battery and data
|
|
34
|
-
* the user cannot see or stop.
|
|
35
|
-
*
|
|
36
|
-
* Doubling from three seconds to a minute keeps a brief interruption
|
|
37
|
-
* recovering quickly while a lasting one settles into an interval that costs
|
|
38
|
-
* almost nothing. The counter resets when a connection opens, so a flaky link
|
|
39
|
-
* does not accumulate delay.
|
|
40
|
-
*/
|
|
41
|
-
private scheduleReconnect;
|
|
42
|
-
disconnect(): void;
|
|
43
|
-
}
|
|
44
|
-
export {};
|
package/dist/realtime.js
DELETED
|
@@ -1,195 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.KoolbaseRealtime = void 0;
|
|
4
|
-
const cache_store_1 = require("./cache-store");
|
|
5
|
-
const record_1 = require("./record");
|
|
6
|
-
const EVENT_TYPE_MAP = {
|
|
7
|
-
'db.record.created': 'created',
|
|
8
|
-
'db.record.updated': 'updated',
|
|
9
|
-
'db.record.deleted': 'deleted',
|
|
10
|
-
};
|
|
11
|
-
function projectIdFromToken(token) {
|
|
12
|
-
try {
|
|
13
|
-
const part = token.split('.')[1];
|
|
14
|
-
if (!part)
|
|
15
|
-
return null;
|
|
16
|
-
const b64 = part.replace(/-/g, '+').replace(/_/g, '/');
|
|
17
|
-
const g = globalThis;
|
|
18
|
-
let json;
|
|
19
|
-
if (typeof g.atob === 'function') {
|
|
20
|
-
const bin = g.atob(b64);
|
|
21
|
-
json = decodeURIComponent(bin.split('').map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join(''));
|
|
22
|
-
}
|
|
23
|
-
else if (g.Buffer) {
|
|
24
|
-
json = g.Buffer.from(b64, 'base64').toString('utf8');
|
|
25
|
-
}
|
|
26
|
-
else {
|
|
27
|
-
return null;
|
|
28
|
-
}
|
|
29
|
-
return JSON.parse(json).project_id ?? null;
|
|
30
|
-
}
|
|
31
|
-
catch {
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
class KoolbaseRealtime {
|
|
36
|
-
constructor(config, getToken, getUserId) {
|
|
37
|
-
this.ws = null;
|
|
38
|
-
this.projectId = null;
|
|
39
|
-
this.listeners = new Map();
|
|
40
|
-
this.reconnectAttempts = 0;
|
|
41
|
-
this.reconnectTimer = null;
|
|
42
|
-
this.connecting = false;
|
|
43
|
-
this.config = config;
|
|
44
|
-
this.getToken = getToken;
|
|
45
|
-
this.getUserId = getUserId;
|
|
46
|
-
}
|
|
47
|
-
/** Files a record seen over the socket, if we know whose it is. */
|
|
48
|
-
async cacheSeenRecord(collection, record) {
|
|
49
|
-
const userId = this.getUserId?.();
|
|
50
|
-
if (!userId)
|
|
51
|
-
return;
|
|
52
|
-
await (0, cache_store_1.cacheRecord)(userId, collection, record.id, record.data, record.revision);
|
|
53
|
-
}
|
|
54
|
-
async forgetSeenRecord(recordId) {
|
|
55
|
-
const userId = this.getUserId?.();
|
|
56
|
-
if (!userId)
|
|
57
|
-
return;
|
|
58
|
-
await (0, cache_store_1.removeCachedRecord)(userId, recordId);
|
|
59
|
-
}
|
|
60
|
-
subscribe(collection, callback) {
|
|
61
|
-
if (!this.listeners.has(collection))
|
|
62
|
-
this.listeners.set(collection, []);
|
|
63
|
-
this.listeners.get(collection).push(callback);
|
|
64
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
65
|
-
this.sendSubscribe(collection);
|
|
66
|
-
}
|
|
67
|
-
else {
|
|
68
|
-
void this.connect();
|
|
69
|
-
}
|
|
70
|
-
return () => {
|
|
71
|
-
const callbacks = this.listeners.get(collection) ?? [];
|
|
72
|
-
const i = callbacks.indexOf(callback);
|
|
73
|
-
if (i > -1)
|
|
74
|
-
callbacks.splice(i, 1);
|
|
75
|
-
if (callbacks.length === 0) {
|
|
76
|
-
this.listeners.delete(collection);
|
|
77
|
-
this.sendUnsubscribe(collection);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
async connect() {
|
|
82
|
-
if (this.connecting)
|
|
83
|
-
return;
|
|
84
|
-
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING))
|
|
85
|
-
return;
|
|
86
|
-
const token = await this.getToken();
|
|
87
|
-
if (!token) {
|
|
88
|
-
this.scheduleReconnect(); // sign-in may be in flight
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
this.projectId = projectIdFromToken(token);
|
|
92
|
-
this.connecting = true;
|
|
93
|
-
const wsUrl = this.config.baseUrl.replace('https://', 'wss://').replace('http://', 'ws://');
|
|
94
|
-
const ws = new WebSocket(`${wsUrl}/v1/realtime/ws?token=${encodeURIComponent(token)}`);
|
|
95
|
-
this.ws = ws;
|
|
96
|
-
ws.onopen = () => {
|
|
97
|
-
this.connecting = false;
|
|
98
|
-
// A connection that opened is the only proof the endpoint and the
|
|
99
|
-
// credentials are usable, so the backoff resets here rather than on a
|
|
100
|
-
// close — a flaky link should not accumulate delay.
|
|
101
|
-
this.reconnectAttempts = 0;
|
|
102
|
-
for (const collection of this.listeners.keys())
|
|
103
|
-
this.sendSubscribe(collection); // (re)subscribe all
|
|
104
|
-
};
|
|
105
|
-
ws.onmessage = (event) => {
|
|
106
|
-
let raw;
|
|
107
|
-
try {
|
|
108
|
-
raw = JSON.parse(event.data);
|
|
109
|
-
}
|
|
110
|
-
catch {
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
const mapped = EVENT_TYPE_MAP[raw?.type];
|
|
114
|
-
if (!mapped)
|
|
115
|
-
return; // ignore subscribed / unsubscribed / error / unknown
|
|
116
|
-
const payload = raw.payload;
|
|
117
|
-
if (!payload || !payload.collection)
|
|
118
|
-
return;
|
|
119
|
-
let msg;
|
|
120
|
-
if (mapped === 'deleted') {
|
|
121
|
-
msg = { type: 'deleted', collection: payload.collection, recordId: payload.record_id };
|
|
122
|
-
// Gone for everyone, so the cached copy is no longer a baseline for
|
|
123
|
-
// anything. An edit composed against it would be refused at replay
|
|
124
|
-
// regardless; removing it makes that a local refusal rather than a
|
|
125
|
-
// round trip.
|
|
126
|
-
void this.forgetSeenRecord(payload.record_id);
|
|
127
|
-
}
|
|
128
|
-
else if (payload.record) {
|
|
129
|
-
const record = (0, record_1.recordFromWire)(payload.record);
|
|
130
|
-
msg = { type: mapped, collection: payload.collection, record };
|
|
131
|
-
// A record seen over the socket is as freshly seen as one fetched, and
|
|
132
|
-
// a client watching a collection would otherwise hold a stale baseline
|
|
133
|
-
// while looking at the change. Writes already queued are unaffected:
|
|
134
|
-
// their baseline was copied in when they were made, so this cannot move
|
|
135
|
-
// ground beneath them.
|
|
136
|
-
void this.cacheSeenRecord(payload.collection, record);
|
|
137
|
-
}
|
|
138
|
-
else {
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
(this.listeners.get(payload.collection) ?? []).forEach((cb) => cb(msg));
|
|
142
|
-
};
|
|
143
|
-
ws.onclose = () => {
|
|
144
|
-
this.connecting = false;
|
|
145
|
-
if (this.ws === ws)
|
|
146
|
-
this.ws = null;
|
|
147
|
-
this.scheduleReconnect();
|
|
148
|
-
};
|
|
149
|
-
ws.onerror = () => { };
|
|
150
|
-
}
|
|
151
|
-
sendSubscribe(collection) {
|
|
152
|
-
if (!this.projectId || !this.ws || this.ws.readyState !== WebSocket.OPEN)
|
|
153
|
-
return;
|
|
154
|
-
this.ws.send(JSON.stringify({ action: 'subscribe', project_id: this.projectId, collection }));
|
|
155
|
-
}
|
|
156
|
-
sendUnsubscribe(collection) {
|
|
157
|
-
if (!this.projectId || !this.ws || this.ws.readyState !== WebSocket.OPEN)
|
|
158
|
-
return;
|
|
159
|
-
this.ws.send(JSON.stringify({ action: 'unsubscribe', project_id: this.projectId, collection }));
|
|
160
|
-
}
|
|
161
|
-
/**
|
|
162
|
-
* Reconnects with backoff, rather than every three seconds forever.
|
|
163
|
-
*
|
|
164
|
-
* A fixed interval is fine while a connection is merely interrupted and
|
|
165
|
-
* costly when it is not: a device with no network, a wrong URL, or a session
|
|
166
|
-
* the server will not accept retried indefinitely, draining battery and data
|
|
167
|
-
* the user cannot see or stop.
|
|
168
|
-
*
|
|
169
|
-
* Doubling from three seconds to a minute keeps a brief interruption
|
|
170
|
-
* recovering quickly while a lasting one settles into an interval that costs
|
|
171
|
-
* almost nothing. The counter resets when a connection opens, so a flaky link
|
|
172
|
-
* does not accumulate delay.
|
|
173
|
-
*/
|
|
174
|
-
scheduleReconnect() {
|
|
175
|
-
if (this.listeners.size === 0 || this.reconnectTimer)
|
|
176
|
-
return;
|
|
177
|
-
const delay = Math.min(3000 * Math.pow(2, this.reconnectAttempts), 60000);
|
|
178
|
-
this.reconnectAttempts += 1;
|
|
179
|
-
this.reconnectTimer = setTimeout(() => {
|
|
180
|
-
this.reconnectTimer = null;
|
|
181
|
-
void this.connect();
|
|
182
|
-
}, delay);
|
|
183
|
-
}
|
|
184
|
-
disconnect() {
|
|
185
|
-
if (this.reconnectTimer) {
|
|
186
|
-
clearTimeout(this.reconnectTimer);
|
|
187
|
-
this.reconnectTimer = null;
|
|
188
|
-
}
|
|
189
|
-
this.ws?.close();
|
|
190
|
-
this.ws = null;
|
|
191
|
-
this.projectId = null;
|
|
192
|
-
this.listeners.clear();
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
exports.KoolbaseRealtime = KoolbaseRealtime;
|
package/dist/record.d.ts
DELETED
package/dist/record.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.recordFromWire = recordFromWire;
|
|
4
|
-
// Converts the flat public wire shape into a KoolbaseRecord.
|
|
5
|
-
// Server sends: { $id, $createdAt, $updatedAt, $collection, $createdBy?, ...fields }
|
|
6
|
-
function recordFromWire(raw) {
|
|
7
|
-
const data = {};
|
|
8
|
-
for (const key of Object.keys(raw)) {
|
|
9
|
-
if (!key.startsWith('$'))
|
|
10
|
-
data[key] = raw[key];
|
|
11
|
-
}
|
|
12
|
-
return {
|
|
13
|
-
id: raw['$id'],
|
|
14
|
-
collection: raw['$collection'],
|
|
15
|
-
createdBy: raw['$createdBy'],
|
|
16
|
-
data,
|
|
17
|
-
createdAt: raw['$createdAt'],
|
|
18
|
-
updatedAt: raw['$updatedAt'],
|
|
19
|
-
revision: typeof raw['$revision'] === 'number'
|
|
20
|
-
? raw['$revision']
|
|
21
|
-
: undefined,
|
|
22
|
-
};
|
|
23
|
-
}
|