@koolbase/core 10.0.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.
Files changed (104) hide show
  1. package/README.md +19 -0
  2. package/dist/cjs/analytics.d.ts +24 -0
  3. package/dist/cjs/analytics.js +110 -0
  4. package/dist/cjs/auth-errors.d.ts +117 -0
  5. package/dist/cjs/auth-errors.js +250 -0
  6. package/dist/cjs/auth.d.ts +213 -0
  7. package/dist/cjs/auth.js +813 -0
  8. package/dist/cjs/cache-store.d.ts +50 -0
  9. package/dist/cjs/cache-store.js +194 -0
  10. package/dist/cjs/conflict.d.ts +80 -0
  11. package/dist/cjs/conflict.js +84 -0
  12. package/dist/cjs/database-errors.d.ts +101 -0
  13. package/dist/cjs/database-errors.js +200 -0
  14. package/dist/cjs/database.d.ts +298 -0
  15. package/dist/cjs/database.js +852 -0
  16. package/dist/cjs/device-id.d.ts +1 -0
  17. package/dist/cjs/device-id.js +57 -0
  18. package/dist/cjs/device-metadata.d.ts +36 -0
  19. package/dist/cjs/device-metadata.js +94 -0
  20. package/dist/cjs/errors.d.ts +64 -0
  21. package/dist/cjs/errors.js +85 -0
  22. package/dist/cjs/flags.d.ts +15 -0
  23. package/dist/cjs/flags.js +76 -0
  24. package/dist/cjs/function-errors.d.ts +51 -0
  25. package/dist/cjs/function-errors.js +103 -0
  26. package/dist/cjs/functions.d.ts +15 -0
  27. package/dist/cjs/functions.js +83 -0
  28. package/dist/cjs/index.d.ts +22 -0
  29. package/dist/cjs/index.js +56 -0
  30. package/dist/cjs/messaging.d.ts +13 -0
  31. package/dist/cjs/messaging.js +36 -0
  32. package/dist/cjs/offline-state.d.ts +97 -0
  33. package/dist/cjs/offline-state.js +198 -0
  34. package/dist/cjs/package.json +3 -0
  35. package/dist/cjs/pending-write.d.ts +47 -0
  36. package/dist/cjs/pending-write.js +22 -0
  37. package/dist/cjs/platform.d.ts +51 -0
  38. package/dist/cjs/platform.js +41 -0
  39. package/dist/cjs/realtime.d.ts +44 -0
  40. package/dist/cjs/realtime.js +195 -0
  41. package/dist/cjs/record.d.ts +2 -0
  42. package/dist/cjs/record.js +23 -0
  43. package/dist/cjs/shared.d.ts +9 -0
  44. package/dist/cjs/shared.js +43 -0
  45. package/dist/cjs/storage-errors.d.ts +163 -0
  46. package/dist/cjs/storage-errors.js +253 -0
  47. package/dist/cjs/storage.d.ts +198 -0
  48. package/dist/cjs/storage.js +451 -0
  49. package/dist/cjs/sync-engine.d.ts +30 -0
  50. package/dist/cjs/sync-engine.js +286 -0
  51. package/dist/cjs/types.d.ts +487 -0
  52. package/dist/cjs/types.js +40 -0
  53. package/dist/esm/analytics.d.ts +24 -0
  54. package/dist/esm/analytics.js +106 -0
  55. package/dist/esm/auth-errors.d.ts +117 -0
  56. package/dist/esm/auth-errors.js +222 -0
  57. package/dist/esm/auth.d.ts +213 -0
  58. package/dist/esm/auth.js +809 -0
  59. package/dist/esm/cache-store.d.ts +50 -0
  60. package/dist/esm/cache-store.js +179 -0
  61. package/dist/esm/conflict.d.ts +80 -0
  62. package/dist/esm/conflict.js +80 -0
  63. package/dist/esm/database-errors.d.ts +101 -0
  64. package/dist/esm/database-errors.js +189 -0
  65. package/dist/esm/database.d.ts +298 -0
  66. package/dist/esm/database.js +848 -0
  67. package/dist/esm/device-id.d.ts +1 -0
  68. package/dist/esm/device-id.js +54 -0
  69. package/dist/esm/device-metadata.d.ts +36 -0
  70. package/dist/esm/device-metadata.js +90 -0
  71. package/dist/esm/errors.d.ts +64 -0
  72. package/dist/esm/errors.js +79 -0
  73. package/dist/esm/flags.d.ts +15 -0
  74. package/dist/esm/flags.js +72 -0
  75. package/dist/esm/function-errors.d.ts +51 -0
  76. package/dist/esm/function-errors.js +93 -0
  77. package/dist/esm/functions.d.ts +15 -0
  78. package/dist/esm/functions.js +79 -0
  79. package/dist/esm/index.d.ts +22 -0
  80. package/dist/esm/index.js +25 -0
  81. package/dist/esm/messaging.d.ts +13 -0
  82. package/dist/esm/messaging.js +32 -0
  83. package/dist/esm/offline-state.d.ts +97 -0
  84. package/dist/esm/offline-state.js +189 -0
  85. package/dist/esm/package.json +3 -0
  86. package/dist/esm/pending-write.d.ts +47 -0
  87. package/dist/esm/pending-write.js +19 -0
  88. package/dist/esm/platform.d.ts +51 -0
  89. package/dist/esm/platform.js +36 -0
  90. package/dist/esm/realtime.d.ts +44 -0
  91. package/dist/esm/realtime.js +191 -0
  92. package/dist/esm/record.d.ts +2 -0
  93. package/dist/esm/record.js +20 -0
  94. package/dist/esm/shared.d.ts +9 -0
  95. package/dist/esm/shared.js +39 -0
  96. package/dist/esm/storage-errors.d.ts +163 -0
  97. package/dist/esm/storage-errors.js +239 -0
  98. package/dist/esm/storage.d.ts +198 -0
  99. package/dist/esm/storage.js +447 -0
  100. package/dist/esm/sync-engine.d.ts +30 -0
  101. package/dist/esm/sync-engine.js +282 -0
  102. package/dist/esm/types.d.ts +487 -0
  103. package/dist/esm/types.js +37 -0
  104. package/package.json +45 -0
@@ -0,0 +1,286 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SyncEngine = void 0;
4
+ const offline_state_js_1 = require("./offline-state.js");
5
+ const errors_js_1 = require("./errors.js");
6
+ const platform_js_1 = require("./platform.js");
7
+ const cache_store_js_1 = require("./cache-store.js");
8
+ /**
9
+ * Internal signal that the server refused a write because the record moved.
10
+ *
11
+ * Not exported: a conflict during replay becomes durable state rather than
12
+ * reaching a caller, since nobody is waiting on a write made hours ago.
13
+ */
14
+ /**
15
+ * Whether the server's answer can change on a later attempt.
16
+ *
17
+ * Terminal means the same request would meet the same decision: the data does
18
+ * not satisfy the collection's rules, the record is gone, the caller is not
19
+ * permitted, a unique value is taken. Retrying spends attempts to learn what is
20
+ * already known.
21
+ *
22
+ * 403 is terminal even though a role change could later permit it. A queue that
23
+ * holds writes indefinitely against a maybe is how a retry loop becomes
24
+ * invisible — surfacing it lets an app retry deliberately if roles change.
25
+ */
26
+ function isTerminal(status) {
27
+ return status === 400 || status === 403 || status === 404 || status === 409;
28
+ }
29
+ /** Raised when the server refused for a reason retrying cannot change. */
30
+ class TerminalRejection extends Error {
31
+ constructor(message, status) {
32
+ super(message);
33
+ this.status = status;
34
+ Object.setPrototypeOf(this, new.target.prototype);
35
+ }
36
+ }
37
+ class RevisionMismatch extends Error {
38
+ constructor(serverRecord, serverRevision) {
39
+ super('revision mismatch');
40
+ this.serverRecord = serverRecord;
41
+ this.serverRevision = serverRevision;
42
+ Object.setPrototypeOf(this, new.target.prototype);
43
+ }
44
+ }
45
+ class SyncEngine {
46
+ constructor(config, getUserId, getToken, onSyncComplete, onSessionExpired) {
47
+ this.isSyncing = false;
48
+ this.config = config;
49
+ this.getUserId = getUserId;
50
+ this.getToken = getToken;
51
+ this.onSyncComplete = onSyncComplete;
52
+ this.onSessionExpired = onSessionExpired;
53
+ }
54
+ start() {
55
+ this.unsubscribe = (0, platform_js_1.getPlatform)().network.onChange(online => {
56
+ if (online)
57
+ this.flush();
58
+ });
59
+ }
60
+ stop() {
61
+ this.unsubscribe?.();
62
+ }
63
+ async flush() {
64
+ if (this.isSyncing)
65
+ return;
66
+ const userId = this.getUserId();
67
+ if (!userId)
68
+ return;
69
+ this.isSyncing = true;
70
+ try {
71
+ // Before anything is sent. Writes queued by an earlier version sit under a
72
+ // different key, and a migration that ran after replay — or depended on
73
+ // being online — would give the same input different outcomes. It clears
74
+ // the old key when done, so later calls find nothing and return.
75
+ await (0, offline_state_js_1.migrateLegacyQueue)(userId);
76
+ const { pending } = await (0, offline_state_js_1.readOfflineState)(userId);
77
+ if (pending.length === 0)
78
+ return;
79
+ // Records whose chain stopped this pass. Writes queued after a conflicted
80
+ // one were composed against the state it would have produced, so applying
81
+ // them now would write against a state their baseline never described.
82
+ const blocked = new Set();
83
+ for (const queued of pending) {
84
+ if (queued.recordId && blocked.has(queued.recordId))
85
+ continue;
86
+ // Read fresh. The list was taken at the start of the pass, so a write
87
+ // behind one that has already landed still carries the revision it was
88
+ // queued with — and would replay against a revision its predecessor has
89
+ // since superseded, conflicting for a reason the user never caused.
90
+ const state = await (0, offline_state_js_1.readOfflineState)(userId);
91
+ const write = state.pending.find((w) => w.id === queued.id);
92
+ if (!write)
93
+ continue;
94
+ try {
95
+ const revision = await this.executeWrite(write);
96
+ // The replayed write just changed the server; the cache must stop
97
+ // testifying to the old world. Mirrors the online paths — a replayed
98
+ // delete evicts the record, and every replayed write invalidates the
99
+ // collection's cached queries, so the next query reconverges instead
100
+ // of serving a ghost.
101
+ if (write.operation === 'delete' && write.recordId) {
102
+ await (0, cache_store_js_1.removeCachedRecord)(userId, write.recordId);
103
+ }
104
+ await (0, cache_store_js_1.invalidateCache)(userId, write.collection);
105
+ await (0, offline_state_js_1.mutateOfflineState)(userId, (s) => {
106
+ s.pending = s.pending.filter((w) => w.id !== write.id);
107
+ // Anything behind this for the same record was composed against its
108
+ // result, and now knows the revision that result carries.
109
+ if (revision !== undefined && write.recordId) {
110
+ for (const w of s.pending) {
111
+ if (w.recordId === write.recordId)
112
+ w.baseRevision = revision;
113
+ }
114
+ }
115
+ });
116
+ }
117
+ catch (e) {
118
+ if (e instanceof errors_js_1.KoolbaseUnauthenticatedError) {
119
+ // The session is gone, so nothing else in the queue can succeed.
120
+ // Stopping beats spending a retry on every remaining write against
121
+ // a token the server has already refused; the queue is intact and
122
+ // replays after login.
123
+ await this.onSessionExpired?.();
124
+ return;
125
+ }
126
+ if (e instanceof RevisionMismatch) {
127
+ // Not a failure to retry — retrying cannot help. It becomes durable
128
+ // unresolved state, in one write so it can be in neither place nor
129
+ // both.
130
+ await (0, offline_state_js_1.mutateOfflineState)(userId, (s) => {
131
+ s.pending = s.pending.filter((w) => w.id !== write.id);
132
+ s.conflicts.push({
133
+ id: write.id,
134
+ // The record moved between the change being made and the queue
135
+ // reaching it — distinct from a write that never had a baseline
136
+ // to compare against at all.
137
+ reason: 'concurrent_modification',
138
+ operation: write.operation,
139
+ collection: write.collection,
140
+ recordId: write.recordId,
141
+ local: write.data,
142
+ baseline: write.baseline,
143
+ server: e.serverRecord,
144
+ baseRevision: write.baseRevision,
145
+ serverRevision: e.serverRevision,
146
+ createdAt: new Date().toISOString(),
147
+ });
148
+ });
149
+ if (write.recordId)
150
+ blocked.add(write.recordId);
151
+ continue;
152
+ }
153
+ if (e instanceof TerminalRejection) {
154
+ // The server made a decision that will not change on a later
155
+ // attempt. Retrying spends attempts to learn what is already known;
156
+ // dropping loses a change the user believes is saved. It waits,
157
+ // with what the server said, so someone can act on it.
158
+ await (0, offline_state_js_1.mutateOfflineState)(userId, (s) => {
159
+ s.pending = s.pending.filter((w) => w.id !== write.id);
160
+ s.conflicts.push({
161
+ id: write.id,
162
+ reason: 'rejected',
163
+ operation: write.operation,
164
+ collection: write.collection,
165
+ recordId: write.recordId ?? '',
166
+ local: write.data,
167
+ baseline: write.baseline,
168
+ baseRevision: write.baseRevision,
169
+ message: e.message,
170
+ createdAt: new Date().toISOString(),
171
+ });
172
+ });
173
+ // A terminally rejected insert leaves an optimistic record behind
174
+ // — cached at enqueue for a record the server refused to create.
175
+ // Left alone it is a phantom: it renders as saved, and an offline
176
+ // edit against it queues a write to a record that does not exist.
177
+ // Evict it, and invalidate the collection so cached queries stop
178
+ // serving it. The conflict above keeps the user's data and the
179
+ // server's verdict; the cache stops testifying to a fiction.
180
+ // MUTATION: phantom eviction removed
181
+ if (write.recordId)
182
+ blocked.add(write.recordId);
183
+ continue;
184
+ }
185
+ // Retryable: the network, a 5xx, a rate limit. The count is kept so a
186
+ // caller can see a write that keeps failing, but nothing drops it —
187
+ // a write discarded after three attempts is discarded silently, and
188
+ // the user is never told.
189
+ await (0, offline_state_js_1.mutateOfflineState)(userId, (s) => {
190
+ const w = s.pending.find((x) => x.id === write.id);
191
+ if (w)
192
+ w.retries += 1;
193
+ });
194
+ }
195
+ }
196
+ this.onSyncComplete?.();
197
+ }
198
+ finally {
199
+ this.isSyncing = false;
200
+ }
201
+ }
202
+ /**
203
+ * Sends one queued write, returning the revision the record now carries.
204
+ *
205
+ * The revision matters to whatever is queued behind this for the same record:
206
+ * those were composed against this one's result and cannot know its revision
207
+ * until the server assigns it.
208
+ */
209
+ async executeWrite(write) {
210
+ const token = await this.getToken();
211
+ const headers = {
212
+ 'Content-Type': 'application/json',
213
+ 'x-api-key': this.config.publicKey,
214
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
215
+ };
216
+ const url = write.operation === 'insert'
217
+ ? `${this.config.baseUrl}/v1/sdk/db/insert`
218
+ : `${this.config.baseUrl}/v1/sdk/db/records/${write.recordId}`;
219
+ let res;
220
+ if (write.operation === 'insert') {
221
+ res = await fetch(url, {
222
+ method: 'POST',
223
+ headers,
224
+ // The write's own id: generated at enqueue, identical on every retry.
225
+ // Without it, an insert whose response was lost duplicated on replay —
226
+ // the server had no way to recognise the repeat.
227
+ body: JSON.stringify({
228
+ collection: write.collection,
229
+ data: write.data,
230
+ idempotency_key: write.id,
231
+ }),
232
+ });
233
+ }
234
+ else if (write.operation === 'update') {
235
+ res = await fetch(url, {
236
+ method: 'PATCH',
237
+ headers,
238
+ // The revision the change was composed against. The server applies it
239
+ // only if the record still carries that revision, so nothing can land
240
+ // between the client deciding the write is safe and the server applying
241
+ // it — which matters here most of all, since hours may have passed.
242
+ body: JSON.stringify({
243
+ data: write.data,
244
+ ...(write.baseRevision !== undefined
245
+ ? { expected_revision: write.baseRevision }
246
+ : {}),
247
+ }),
248
+ });
249
+ }
250
+ else {
251
+ const q = write.baseRevision !== undefined
252
+ ? `?expected_revision=${write.baseRevision}`
253
+ : '';
254
+ res = await fetch(`${url}${q}`, { method: 'DELETE', headers });
255
+ }
256
+ if (res.status === 401)
257
+ throw new errors_js_1.KoolbaseUnauthenticatedError('unauthorized');
258
+ if (res.status === 409) {
259
+ const body = await res.json().catch(() => ({}));
260
+ if (body?.code === 'revision_mismatch') {
261
+ throw new RevisionMismatch(body?.details?.record, body?.details?.current_revision);
262
+ }
263
+ }
264
+ if (!res.ok && res.status !== 204) {
265
+ const body = await res.json().catch(() => ({}));
266
+ const message = body?.error ?? `${write.operation} failed`;
267
+ // A 404 on a delete means the record is already gone, which is what the
268
+ // write was asking for. Satisfied, not failed.
269
+ if (res.status === 404 && write.operation === 'delete')
270
+ return undefined;
271
+ if (isTerminal(res.status))
272
+ throw new TerminalRejection(message, res.status);
273
+ throw new Error(`${write.operation} sync failed: ${res.status}`);
274
+ }
275
+ const text = await res.text().catch(() => '');
276
+ if (!text)
277
+ return undefined;
278
+ try {
279
+ return JSON.parse(text)?.$revision;
280
+ }
281
+ catch {
282
+ return undefined;
283
+ }
284
+ }
285
+ }
286
+ exports.SyncEngine = SyncEngine;