@classic-homes/offline-core 0.2.0 → 0.3.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/dist/cache/index.d.ts +25 -0
- package/dist/cache/index.js +1 -1
- package/dist/{chunk-JPXEFKZO.js → chunk-SLDAYKRY.js} +96 -13
- package/dist/{chunk-34PR6T4B.js → chunk-YTJQYSHR.js} +196 -39
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/sync/index.d.ts +61 -12
- package/dist/sync/index.js +1 -1
- package/package.json +1 -1
package/dist/cache/index.d.ts
CHANGED
|
@@ -124,6 +124,8 @@ declare class CacheService {
|
|
|
124
124
|
private readonly adapter;
|
|
125
125
|
private stats;
|
|
126
126
|
private inFlightFetches;
|
|
127
|
+
private pendingWrites;
|
|
128
|
+
private generation;
|
|
127
129
|
private readonly inFlightTimeout;
|
|
128
130
|
private readonly maxInFlight;
|
|
129
131
|
private readonly maxEntries;
|
|
@@ -144,6 +146,22 @@ declare class CacheService {
|
|
|
144
146
|
* Set a cached value
|
|
145
147
|
*/
|
|
146
148
|
set<T>(key: string, value: T, options?: CacheOptions): Promise<void>;
|
|
149
|
+
/**
|
|
150
|
+
* Register a pending write for `key` (see {@link WriteTicket}).
|
|
151
|
+
*/
|
|
152
|
+
private openTicket;
|
|
153
|
+
private isLive;
|
|
154
|
+
/**
|
|
155
|
+
* Cancel the pending writes `matches` selects, and forget their in-flight
|
|
156
|
+
* fetches so later reads start their own.
|
|
157
|
+
*/
|
|
158
|
+
private cancelPending;
|
|
159
|
+
/**
|
|
160
|
+
* Store a value, unless `ticket` is cancelled before the write is issued.
|
|
161
|
+
* A cancellation that lands while the write is in progress deletes the
|
|
162
|
+
* entry again: invalidated data must not survive the invalidation.
|
|
163
|
+
*/
|
|
164
|
+
private write;
|
|
147
165
|
/**
|
|
148
166
|
* Sizes of this cache's entries, read from storage the first time
|
|
149
167
|
*/
|
|
@@ -166,6 +184,7 @@ declare class CacheService {
|
|
|
166
184
|
* Get cached value or fetch and cache it
|
|
167
185
|
*/
|
|
168
186
|
getOrSet<T>(key: string, fetcher: () => Promise<T>, options?: GetOrSetOptions): Promise<T>;
|
|
187
|
+
private getOrFetch;
|
|
169
188
|
/**
|
|
170
189
|
* Fetch and cache a value (with deduplication)
|
|
171
190
|
*/
|
|
@@ -178,6 +197,12 @@ declare class CacheService {
|
|
|
178
197
|
* Invalidate a cached value
|
|
179
198
|
*/
|
|
180
199
|
invalidate(key: string): Promise<void>;
|
|
200
|
+
/**
|
|
201
|
+
* Delete one entry from storage (eviction and invalidate). Unlike
|
|
202
|
+
* invalidate() it leaves pending writes alone: eviction makes room, it
|
|
203
|
+
* does not declare the data stale.
|
|
204
|
+
*/
|
|
205
|
+
private removeEntry;
|
|
181
206
|
/**
|
|
182
207
|
* Invalidate all entries with a specific tag
|
|
183
208
|
*/
|
package/dist/cache/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-
|
|
1
|
+
export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-SLDAYKRY.js';
|
|
2
2
|
import '../chunk-4KL3GDYP.js';
|
|
3
3
|
import '../chunk-R2IP2AA5.js';
|
|
4
4
|
import '../chunk-UL7MZBSF.js';
|
|
@@ -38,6 +38,10 @@ var CacheService = class {
|
|
|
38
38
|
};
|
|
39
39
|
// Track in-flight fetches to avoid duplicate requests
|
|
40
40
|
this.inFlightFetches = /* @__PURE__ */ new Map();
|
|
41
|
+
// Writes that have not stored their value yet, and the generation that
|
|
42
|
+
// invalidateAll() bumps. Invalidation cancels the tickets it covers.
|
|
43
|
+
this.pendingWrites = /* @__PURE__ */ new Set();
|
|
44
|
+
this.generation = 0;
|
|
41
45
|
// Track access order for LRU eviction (key -> last access timestamp)
|
|
42
46
|
this.accessOrder = /* @__PURE__ */ new Map();
|
|
43
47
|
// Approximate size of each of this cache's entries (key -> bytes), loaded
|
|
@@ -102,6 +106,48 @@ var CacheService = class {
|
|
|
102
106
|
* Set a cached value
|
|
103
107
|
*/
|
|
104
108
|
async set(key, value, options = {}) {
|
|
109
|
+
const ticket = this.openTicket(key, options.tags);
|
|
110
|
+
try {
|
|
111
|
+
await this.write(key, value, options, ticket);
|
|
112
|
+
} finally {
|
|
113
|
+
this.pendingWrites.delete(ticket);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Register a pending write for `key` (see {@link WriteTicket}).
|
|
118
|
+
*/
|
|
119
|
+
openTicket(key, tags) {
|
|
120
|
+
const ticket = {
|
|
121
|
+
key,
|
|
122
|
+
tags: tags ? [...tags] : [],
|
|
123
|
+
generation: this.generation,
|
|
124
|
+
cancelled: false
|
|
125
|
+
};
|
|
126
|
+
this.pendingWrites.add(ticket);
|
|
127
|
+
return ticket;
|
|
128
|
+
}
|
|
129
|
+
isLive(ticket) {
|
|
130
|
+
return !ticket.cancelled && ticket.generation === this.generation;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Cancel the pending writes `matches` selects, and forget their in-flight
|
|
134
|
+
* fetches so later reads start their own.
|
|
135
|
+
*/
|
|
136
|
+
cancelPending(matches) {
|
|
137
|
+
for (const ticket of this.pendingWrites) {
|
|
138
|
+
if (matches(ticket)) ticket.cancelled = true;
|
|
139
|
+
}
|
|
140
|
+
for (const [key, entry] of this.inFlightFetches) {
|
|
141
|
+
if (entry.ticket.cancelled) this.inFlightFetches.delete(key);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Store a value, unless `ticket` is cancelled before the write is issued.
|
|
146
|
+
* A cancellation that lands while the write is in progress deletes the
|
|
147
|
+
* entry again: invalidated data must not survive the invalidation.
|
|
148
|
+
*/
|
|
149
|
+
async write(key, value, options, ticket) {
|
|
150
|
+
if (!this.isLive(ticket)) return;
|
|
105
151
|
const storageKey = getCacheKey(key);
|
|
106
152
|
const now = Date.now();
|
|
107
153
|
const ttl = options.ttl ?? DEFAULT_EXPIRATIONS.CACHE;
|
|
@@ -113,11 +159,16 @@ var CacheService = class {
|
|
|
113
159
|
};
|
|
114
160
|
const size = estimateSize(entry);
|
|
115
161
|
await this.enforceLimit(key, size);
|
|
162
|
+
if (!this.isLive(ticket)) return;
|
|
116
163
|
const staleTime = options.staleTime ?? ttl;
|
|
117
164
|
await this.adapter.storeJSON(storageKey, entry, {
|
|
118
165
|
tags: options.tags ? [...options.tags, "cache"] : ["cache"],
|
|
119
166
|
...ttl > 0 && { ttl: ttl + Math.max(0, staleTime) }
|
|
120
167
|
});
|
|
168
|
+
if (!this.isLive(ticket)) {
|
|
169
|
+
await this.adapter.deleteJSON(storageKey);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
121
172
|
this.accessOrder.set(key, now);
|
|
122
173
|
this.entrySizes?.set(key, size);
|
|
123
174
|
}
|
|
@@ -188,7 +239,7 @@ var CacheService = class {
|
|
|
188
239
|
async evictLRU(keys, count) {
|
|
189
240
|
const toEvict = this.sortByAccess(keys).slice(0, count);
|
|
190
241
|
for (const key of toEvict) {
|
|
191
|
-
await this.
|
|
242
|
+
await this.removeEntry(key);
|
|
192
243
|
this.accessOrder.delete(key);
|
|
193
244
|
}
|
|
194
245
|
}
|
|
@@ -196,6 +247,14 @@ var CacheService = class {
|
|
|
196
247
|
* Get cached value or fetch and cache it
|
|
197
248
|
*/
|
|
198
249
|
async getOrSet(key, fetcher, options = {}) {
|
|
250
|
+
const ticket = this.openTicket(key, options.tags);
|
|
251
|
+
try {
|
|
252
|
+
return await this.getOrFetch(key, fetcher, options, ticket);
|
|
253
|
+
} finally {
|
|
254
|
+
this.pendingWrites.delete(ticket);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async getOrFetch(key, fetcher, options, ticket) {
|
|
199
258
|
const {
|
|
200
259
|
ttl = DEFAULT_EXPIRATIONS.CACHE,
|
|
201
260
|
tags,
|
|
@@ -216,20 +275,27 @@ var CacheService = class {
|
|
|
216
275
|
const now = Date.now();
|
|
217
276
|
const age = now - entry.createdAt;
|
|
218
277
|
if (age < (entry.expiresAt !== null ? entry.expiresAt - entry.createdAt : 0) + staleThreshold) {
|
|
219
|
-
void this.revalidateInBackground(key, fetcher, { ttl, tags, staleTime });
|
|
278
|
+
void this.revalidateInBackground(key, fetcher, { ttl, tags, staleTime }, ticket);
|
|
220
279
|
return cached.value;
|
|
221
280
|
}
|
|
222
281
|
}
|
|
223
282
|
}
|
|
224
|
-
return this.fetchAndCache(
|
|
283
|
+
return this.fetchAndCache(
|
|
284
|
+
key,
|
|
285
|
+
fetcher,
|
|
286
|
+
{ ttl, tags, staleTime },
|
|
287
|
+
ticket,
|
|
288
|
+
onFetching,
|
|
289
|
+
onFetchComplete
|
|
290
|
+
);
|
|
225
291
|
}
|
|
226
292
|
/**
|
|
227
293
|
* Fetch and cache a value (with deduplication)
|
|
228
294
|
*/
|
|
229
|
-
async fetchAndCache(key, fetcher, options, onFetching, onFetchComplete) {
|
|
295
|
+
async fetchAndCache(key, fetcher, options, caller, onFetching, onFetchComplete) {
|
|
230
296
|
this.cleanupStaleInFlight();
|
|
231
297
|
const existing = this.inFlightFetches.get(key);
|
|
232
|
-
if (existing) {
|
|
298
|
+
if (existing && this.isLive(existing.ticket) && this.isLive(caller)) {
|
|
233
299
|
return existing.promise;
|
|
234
300
|
}
|
|
235
301
|
if (this.inFlightFetches.size >= this.maxInFlight) {
|
|
@@ -239,30 +305,35 @@ var CacheService = class {
|
|
|
239
305
|
}
|
|
240
306
|
}
|
|
241
307
|
onFetching?.();
|
|
308
|
+
const ticket = this.openTicket(key, options.tags);
|
|
309
|
+
ticket.generation = caller.generation;
|
|
310
|
+
ticket.cancelled = caller.cancelled;
|
|
311
|
+
let entry;
|
|
242
312
|
const fetchPromise = (async () => {
|
|
243
313
|
try {
|
|
244
314
|
const value = await fetcher();
|
|
245
|
-
await this.
|
|
315
|
+
await this.write(key, value, options, ticket);
|
|
246
316
|
onFetchComplete?.();
|
|
247
317
|
return value;
|
|
248
318
|
} catch (error) {
|
|
249
319
|
onFetchComplete?.(error);
|
|
250
320
|
throw error;
|
|
251
321
|
} finally {
|
|
252
|
-
this.
|
|
322
|
+
this.pendingWrites.delete(ticket);
|
|
323
|
+
if (this.inFlightFetches.get(key) === entry) this.inFlightFetches.delete(key);
|
|
253
324
|
}
|
|
254
325
|
})();
|
|
255
|
-
this.
|
|
256
|
-
promise: fetchPromise,
|
|
257
|
-
|
|
258
|
-
}
|
|
326
|
+
if (this.isLive(ticket)) {
|
|
327
|
+
entry = { promise: fetchPromise, startedAt: Date.now(), ticket };
|
|
328
|
+
this.inFlightFetches.set(key, entry);
|
|
329
|
+
}
|
|
259
330
|
return fetchPromise;
|
|
260
331
|
}
|
|
261
332
|
/**
|
|
262
333
|
* Revalidate cache in background
|
|
263
334
|
*/
|
|
264
|
-
async revalidateInBackground(key, fetcher, options) {
|
|
265
|
-
this.fetchAndCache(key, fetcher, options).catch((error) => {
|
|
335
|
+
async revalidateInBackground(key, fetcher, options, caller) {
|
|
336
|
+
this.fetchAndCache(key, fetcher, options, caller).catch((error) => {
|
|
266
337
|
console.warn(`Background revalidation failed for ${key}:`, error);
|
|
267
338
|
});
|
|
268
339
|
}
|
|
@@ -271,6 +342,15 @@ var CacheService = class {
|
|
|
271
342
|
*/
|
|
272
343
|
async invalidate(key) {
|
|
273
344
|
this.cleanupStaleInFlight();
|
|
345
|
+
this.cancelPending((ticket) => ticket.key === key);
|
|
346
|
+
await this.removeEntry(key);
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Delete one entry from storage (eviction and invalidate). Unlike
|
|
350
|
+
* invalidate() it leaves pending writes alone: eviction makes room, it
|
|
351
|
+
* does not declare the data stale.
|
|
352
|
+
*/
|
|
353
|
+
async removeEntry(key) {
|
|
274
354
|
const storageKey = getCacheKey(key);
|
|
275
355
|
await this.adapter.deleteJSON(storageKey);
|
|
276
356
|
this.accessOrder.delete(key);
|
|
@@ -281,6 +361,7 @@ var CacheService = class {
|
|
|
281
361
|
*/
|
|
282
362
|
async invalidateByTag(tag) {
|
|
283
363
|
this.cleanupStaleInFlight();
|
|
364
|
+
this.cancelPending((ticket) => ticket.tags.includes(tag) || tag === "cache");
|
|
284
365
|
this.entrySizes = null;
|
|
285
366
|
return this.adapter.deleteJSONByTag(tag);
|
|
286
367
|
}
|
|
@@ -289,6 +370,8 @@ var CacheService = class {
|
|
|
289
370
|
*/
|
|
290
371
|
async invalidateAll() {
|
|
291
372
|
this.cleanupStaleInFlight();
|
|
373
|
+
this.generation += 1;
|
|
374
|
+
this.cancelPending(() => true);
|
|
292
375
|
const count = await this.adapter.deleteJSONByTag("cache");
|
|
293
376
|
this.accessOrder.clear();
|
|
294
377
|
this.entrySizes = null;
|
|
@@ -169,10 +169,16 @@ function createConnectivityMonitor() {
|
|
|
169
169
|
// src/sync/queue.ts
|
|
170
170
|
var QUEUE_STORAGE_KEY = "sync-queue";
|
|
171
171
|
var MAX_RETRY_COUNT = 3;
|
|
172
|
+
var lastWriteByAdapter = /* @__PURE__ */ new WeakMap();
|
|
172
173
|
var SyncQueue = class {
|
|
173
174
|
constructor(adapter) {
|
|
174
175
|
this.adapter = adapter;
|
|
175
|
-
|
|
176
|
+
/** Write currently being performed by the adapter */
|
|
177
|
+
this.activeSave = null;
|
|
178
|
+
/** Write scheduled after `activeSave`, not started yet; later mutations join it */
|
|
179
|
+
this.queuedSave = null;
|
|
180
|
+
/** The latest write failed, so storage is behind the in-memory state */
|
|
181
|
+
this.unsaved = false;
|
|
176
182
|
this.state = {
|
|
177
183
|
pending: [],
|
|
178
184
|
processing: [],
|
|
@@ -184,6 +190,7 @@ var SyncQueue = class {
|
|
|
184
190
|
* Initialize the queue from storage
|
|
185
191
|
*/
|
|
186
192
|
async initialize() {
|
|
193
|
+
await lastWriteByAdapter.get(this.adapter)?.catch(() => void 0);
|
|
187
194
|
try {
|
|
188
195
|
const entry = await this.adapter.getJSON(QUEUE_STORAGE_KEY);
|
|
189
196
|
if (entry?.data) {
|
|
@@ -199,21 +206,35 @@ var SyncQueue = class {
|
|
|
199
206
|
}
|
|
200
207
|
}
|
|
201
208
|
/**
|
|
202
|
-
*
|
|
209
|
+
* Persist queue state. Resolves once the adapter has stored a snapshot that
|
|
210
|
+
* includes every mutation made before the call, and rejects if that write
|
|
211
|
+
* fails. Writes are serialised; calls made while a write is in flight share
|
|
212
|
+
* the next one, so bursts cost at most two writes.
|
|
203
213
|
*/
|
|
204
|
-
|
|
205
|
-
if (this.
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
214
|
+
save() {
|
|
215
|
+
if (this.queuedSave) return this.queuedSave;
|
|
216
|
+
const previous = this.activeSave;
|
|
217
|
+
const write = (previous ?? Promise.resolve()).catch(() => void 0).then(() => {
|
|
218
|
+
this.queuedSave = null;
|
|
219
|
+
this.activeSave = write;
|
|
220
|
+
return this.adapter.storeJSON(QUEUE_STORAGE_KEY, structuredClone(this.state), {
|
|
221
|
+
tags: ["sync-queue"]
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
this.queuedSave = write;
|
|
225
|
+
lastWriteByAdapter.set(this.adapter, write);
|
|
226
|
+
const settle = (failed) => {
|
|
227
|
+
if (this.activeSave === write) {
|
|
228
|
+
this.activeSave = null;
|
|
229
|
+
if (!this.queuedSave) this.unsaved = failed;
|
|
215
230
|
}
|
|
216
|
-
|
|
231
|
+
if (lastWriteByAdapter.get(this.adapter) === write) lastWriteByAdapter.delete(this.adapter);
|
|
232
|
+
};
|
|
233
|
+
write.then(
|
|
234
|
+
() => settle(false),
|
|
235
|
+
() => settle(true)
|
|
236
|
+
);
|
|
237
|
+
return write;
|
|
217
238
|
}
|
|
218
239
|
/**
|
|
219
240
|
* Queue a create operation
|
|
@@ -428,12 +449,16 @@ var SyncQueue = class {
|
|
|
428
449
|
await this.save();
|
|
429
450
|
}
|
|
430
451
|
/**
|
|
431
|
-
* Dispose the queue
|
|
452
|
+
* Dispose the queue, flushing any write still in flight (or retrying one
|
|
453
|
+
* that failed). The returned promise rejects if that write fails; callers
|
|
454
|
+
* that do not await it are unaffected (the rejection is marked handled), and
|
|
455
|
+
* a new queue on the same adapter still waits for the write before loading.
|
|
432
456
|
*/
|
|
433
457
|
dispose() {
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
458
|
+
const pending = this.queuedSave ?? this.activeSave ?? (this.unsaved ? this.save() : null);
|
|
459
|
+
const flushed = pending ? pending.then(() => void 0) : Promise.resolve();
|
|
460
|
+
flushed.catch(() => void 0);
|
|
461
|
+
return flushed;
|
|
437
462
|
}
|
|
438
463
|
};
|
|
439
464
|
function createSyncQueue(adapter) {
|
|
@@ -585,6 +610,12 @@ var CONFLICTS_STORAGE_KEY = "sync-conflicts";
|
|
|
585
610
|
var RETRY_BASE_DELAY_MS = 5e3;
|
|
586
611
|
var RETRY_MAX_DELAY_MS = 15 * 60 * 1e3;
|
|
587
612
|
var PENDING_STATUSES = ["pending-upload", "local-only"];
|
|
613
|
+
var SyncDisposedError = class extends Error {
|
|
614
|
+
constructor() {
|
|
615
|
+
super("Sync service disposed");
|
|
616
|
+
this.name = "SyncDisposedError";
|
|
617
|
+
}
|
|
618
|
+
};
|
|
588
619
|
function errorMessage(error) {
|
|
589
620
|
return error instanceof Error ? error.message : String(error);
|
|
590
621
|
}
|
|
@@ -604,6 +635,14 @@ var SyncService = class {
|
|
|
604
635
|
this.pendingDraftCount = 0;
|
|
605
636
|
/** Upload backoff per local draft ID */
|
|
606
637
|
this.uploadFailures = /* @__PURE__ */ new Map();
|
|
638
|
+
/**
|
|
639
|
+
* Aborted by dispose(). Passed to the remote adapter, raced against every
|
|
640
|
+
* remote call and checked after every await of a sync, so a disposed
|
|
641
|
+
* service writes nothing more and its sync lock is released promptly.
|
|
642
|
+
*/
|
|
643
|
+
this.lifetime = new AbortController();
|
|
644
|
+
/** Settles once the sync running under the lock (if any) has stopped */
|
|
645
|
+
this.activeSync = null;
|
|
607
646
|
this.syncAdapter = config.adapter;
|
|
608
647
|
this.config = {
|
|
609
648
|
syncIntervalMs: config.syncIntervalMs ?? DEFAULT_SYNC_INTERVAL,
|
|
@@ -633,6 +672,56 @@ var SyncService = class {
|
|
|
633
672
|
await this.loadConflicts();
|
|
634
673
|
await this.refreshPendingCount();
|
|
635
674
|
}
|
|
675
|
+
/** Whether dispose() has been called */
|
|
676
|
+
get isDisposed() {
|
|
677
|
+
return this.lifetime.signal.aborted;
|
|
678
|
+
}
|
|
679
|
+
/** Throw if disposed: called after every await of a sync. */
|
|
680
|
+
ensureActive() {
|
|
681
|
+
if (this.lifetime.signal.aborted) throw new SyncDisposedError();
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Run a remote adapter call with the service's AbortSignal, settling as
|
|
685
|
+
* soon as the service is disposed even if the adapter ignores the signal.
|
|
686
|
+
*/
|
|
687
|
+
remote(call) {
|
|
688
|
+
const signal = this.lifetime.signal;
|
|
689
|
+
if (signal.aborted) return Promise.reject(new SyncDisposedError());
|
|
690
|
+
return new Promise((resolve, reject) => {
|
|
691
|
+
const onAbort = () => reject(new SyncDisposedError());
|
|
692
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
693
|
+
let pending;
|
|
694
|
+
try {
|
|
695
|
+
pending = Promise.resolve(call(signal));
|
|
696
|
+
} catch (error) {
|
|
697
|
+
pending = Promise.reject(error);
|
|
698
|
+
}
|
|
699
|
+
pending.then(
|
|
700
|
+
(value) => {
|
|
701
|
+
signal.removeEventListener("abort", onAbort);
|
|
702
|
+
if (signal.aborted) reject(new SyncDisposedError());
|
|
703
|
+
else resolve(value);
|
|
704
|
+
},
|
|
705
|
+
(error) => {
|
|
706
|
+
signal.removeEventListener("abort", onAbort);
|
|
707
|
+
reject(signal.aborted ? new SyncDisposedError() : error);
|
|
708
|
+
}
|
|
709
|
+
);
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
/** Run `fn` under the shared sync lock, tracked so dispose() can await it. */
|
|
713
|
+
async locked(fn) {
|
|
714
|
+
const run = withSyncLock(fn);
|
|
715
|
+
this.activeSync = run.catch(() => {
|
|
716
|
+
});
|
|
717
|
+
try {
|
|
718
|
+
const result = await run;
|
|
719
|
+
if (this.isDisposed) return this.createErrorResult("Sync service disposed");
|
|
720
|
+
return result.acquired ? result.value : this.createErrorResult("Sync already in progress");
|
|
721
|
+
} finally {
|
|
722
|
+
this.activeSync = null;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
636
725
|
// ============================================
|
|
637
726
|
// Properties
|
|
638
727
|
// ============================================
|
|
@@ -693,6 +782,9 @@ var SyncService = class {
|
|
|
693
782
|
* Sync all drafts
|
|
694
783
|
*/
|
|
695
784
|
async syncAll() {
|
|
785
|
+
if (this.isDisposed) {
|
|
786
|
+
return this.createErrorResult("Sync service disposed");
|
|
787
|
+
}
|
|
696
788
|
if (this.isSyncing) {
|
|
697
789
|
return this.createErrorResult("Sync already in progress");
|
|
698
790
|
}
|
|
@@ -701,8 +793,7 @@ var SyncService = class {
|
|
|
701
793
|
}
|
|
702
794
|
this.isSyncing = true;
|
|
703
795
|
try {
|
|
704
|
-
|
|
705
|
-
return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
|
|
796
|
+
return await this.locked(() => this.runSyncAll());
|
|
706
797
|
} finally {
|
|
707
798
|
this.isSyncing = false;
|
|
708
799
|
}
|
|
@@ -712,6 +803,7 @@ var SyncService = class {
|
|
|
712
803
|
this.emit("sync:start", null);
|
|
713
804
|
try {
|
|
714
805
|
const result = await this.performSync();
|
|
806
|
+
this.ensureActive();
|
|
715
807
|
this.lastSyncResult = result;
|
|
716
808
|
if (result.conflicts.length > 0) {
|
|
717
809
|
const byId = new Map(this.conflicts.map((c) => [c.localDraftId, c]));
|
|
@@ -720,11 +812,14 @@ var SyncService = class {
|
|
|
720
812
|
}
|
|
721
813
|
this.conflicts = [...byId.values()];
|
|
722
814
|
await this.saveConflicts();
|
|
815
|
+
this.ensureActive();
|
|
723
816
|
this.emit("sync:conflict", result.conflicts);
|
|
724
817
|
this.onConflictDetected?.(result.conflicts);
|
|
725
818
|
}
|
|
819
|
+
this.ensureActive();
|
|
726
820
|
await this.queue.updateLastSyncAt(Date.now());
|
|
727
821
|
await this.refreshPendingCount();
|
|
822
|
+
this.ensureActive();
|
|
728
823
|
this.emit("sync:complete", result);
|
|
729
824
|
this.onSyncComplete?.(result);
|
|
730
825
|
return result;
|
|
@@ -733,7 +828,9 @@ var SyncService = class {
|
|
|
733
828
|
error instanceof Error ? error.message : "Unknown error",
|
|
734
829
|
startTime
|
|
735
830
|
);
|
|
831
|
+
if (this.isDisposed) return errorResult;
|
|
736
832
|
await this.refreshPendingCount();
|
|
833
|
+
if (this.isDisposed) return errorResult;
|
|
737
834
|
this.emit("sync:error", error);
|
|
738
835
|
this.onSyncError?.(error instanceof Error ? error : new Error(String(error)));
|
|
739
836
|
return errorResult;
|
|
@@ -743,6 +840,9 @@ var SyncService = class {
|
|
|
743
840
|
* Sync a specific draft
|
|
744
841
|
*/
|
|
745
842
|
async syncDraft(draftId) {
|
|
843
|
+
if (this.isDisposed) {
|
|
844
|
+
return this.createErrorResult("Sync service disposed");
|
|
845
|
+
}
|
|
746
846
|
if (this.isSyncing) {
|
|
747
847
|
return this.createErrorResult("Sync already in progress");
|
|
748
848
|
}
|
|
@@ -751,8 +851,7 @@ var SyncService = class {
|
|
|
751
851
|
}
|
|
752
852
|
this.isSyncing = true;
|
|
753
853
|
try {
|
|
754
|
-
|
|
755
|
-
return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
|
|
854
|
+
return await this.locked(() => this.runSyncDraft(draftId));
|
|
756
855
|
} finally {
|
|
757
856
|
this.isSyncing = false;
|
|
758
857
|
}
|
|
@@ -761,6 +860,7 @@ var SyncService = class {
|
|
|
761
860
|
const startTime = Date.now();
|
|
762
861
|
try {
|
|
763
862
|
const draft = await this.draftManager.getDraft(draftId);
|
|
863
|
+
this.ensureActive();
|
|
764
864
|
if (!draft) {
|
|
765
865
|
return this.createErrorResult("Draft not found");
|
|
766
866
|
}
|
|
@@ -769,7 +869,7 @@ var SyncService = class {
|
|
|
769
869
|
result = await this.syncSingleDraft(draft);
|
|
770
870
|
this.uploadFailures.delete(draftId);
|
|
771
871
|
} catch (error) {
|
|
772
|
-
this.recordUploadFailure(draftId, startTime);
|
|
872
|
+
if (!this.isDisposed) this.recordUploadFailure(draftId, startTime);
|
|
773
873
|
throw error;
|
|
774
874
|
}
|
|
775
875
|
return {
|
|
@@ -788,46 +888,56 @@ var SyncService = class {
|
|
|
788
888
|
startTime
|
|
789
889
|
);
|
|
790
890
|
} finally {
|
|
791
|
-
await this.refreshPendingCount();
|
|
891
|
+
if (!this.isDisposed) await this.refreshPendingCount();
|
|
792
892
|
}
|
|
793
893
|
}
|
|
794
894
|
/**
|
|
795
895
|
* Force push a draft (overwrite remote)
|
|
796
896
|
*/
|
|
797
897
|
async forcePush(draftId) {
|
|
898
|
+
this.ensureActive();
|
|
798
899
|
const draft = await this.draftManager.getDraft(draftId);
|
|
900
|
+
this.ensureActive();
|
|
799
901
|
if (!draft) {
|
|
800
902
|
throw new Error("Draft not found");
|
|
801
903
|
}
|
|
802
904
|
const payload = this.createPayload(draft);
|
|
803
905
|
if (draft.metadata.remoteId) {
|
|
804
|
-
|
|
805
|
-
await this.
|
|
906
|
+
const remoteId = draft.metadata.remoteId;
|
|
907
|
+
await this.remote((signal) => this.syncAdapter.updateDraft(remoteId, payload, { signal }));
|
|
908
|
+
await this.markUploaded(draft, remoteId);
|
|
806
909
|
} else {
|
|
807
|
-
const remote = await this.
|
|
910
|
+
const remote = await this.remote(
|
|
911
|
+
(signal) => this.syncAdapter.createDraft(payload, { signal })
|
|
912
|
+
);
|
|
808
913
|
await this.markUploaded(draft, remote.id);
|
|
809
914
|
}
|
|
915
|
+
this.ensureActive();
|
|
810
916
|
await this.removeConflict(draftId);
|
|
811
917
|
}
|
|
812
918
|
/**
|
|
813
919
|
* Force pull a draft (overwrite local)
|
|
814
920
|
*/
|
|
815
921
|
async forcePull(draftId) {
|
|
922
|
+
this.ensureActive();
|
|
816
923
|
const draft = await this.draftManager.getDraft(draftId);
|
|
924
|
+
this.ensureActive();
|
|
817
925
|
if (!draft || !draft.metadata.remoteId) {
|
|
818
926
|
throw new Error("Draft not found or not synced");
|
|
819
927
|
}
|
|
820
|
-
const remotes = await this.syncAdapter.fetchDrafts();
|
|
928
|
+
const remotes = await this.remote((signal) => this.syncAdapter.fetchDrafts({ signal }));
|
|
821
929
|
const remote = remotes.find((r) => r.id === draft.metadata.remoteId);
|
|
822
930
|
if (!remote) {
|
|
823
931
|
throw new Error("Remote draft not found");
|
|
824
932
|
}
|
|
825
933
|
await this.draftManager.updateDraft(draftId, remote.data, remote.fileRefs);
|
|
934
|
+
this.ensureActive();
|
|
826
935
|
await this.draftManager.updateDraftMetadata(draftId, {
|
|
827
936
|
name: remote.name,
|
|
828
937
|
syncStatus: "synced",
|
|
829
938
|
lastSyncedAt: Date.now()
|
|
830
939
|
});
|
|
940
|
+
this.ensureActive();
|
|
831
941
|
await this.removeConflict(draftId);
|
|
832
942
|
}
|
|
833
943
|
// ============================================
|
|
@@ -842,7 +952,9 @@ var SyncService = class {
|
|
|
842
952
|
throw new Error("Conflict not found");
|
|
843
953
|
}
|
|
844
954
|
const resolved = applyResolution(conflict.localDraft, conflict.remoteDraft, resolution);
|
|
955
|
+
this.ensureActive();
|
|
845
956
|
await this.draftManager.updateDraft(draftId, resolved.data, resolved.fileRefs);
|
|
957
|
+
this.ensureActive();
|
|
846
958
|
await this.draftManager.updateDraftMetadata(draftId, {
|
|
847
959
|
name: resolved.metadata.name,
|
|
848
960
|
syncStatus: resolved.metadata.syncStatus,
|
|
@@ -851,6 +963,7 @@ var SyncService = class {
|
|
|
851
963
|
if (resolution === "keep-local" || resolution === "merge") {
|
|
852
964
|
await this.forcePush(draftId);
|
|
853
965
|
}
|
|
966
|
+
this.ensureActive();
|
|
854
967
|
await this.removeConflict(draftId);
|
|
855
968
|
}
|
|
856
969
|
// ============================================
|
|
@@ -863,6 +976,9 @@ var SyncService = class {
|
|
|
863
976
|
if (this.autoSyncInterval !== null) {
|
|
864
977
|
return;
|
|
865
978
|
}
|
|
979
|
+
if (this.isDisposed) {
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
866
982
|
this.autoSyncInterval = setInterval(() => {
|
|
867
983
|
if (this.isOnline && !this.isSyncing) {
|
|
868
984
|
void this.syncAll();
|
|
@@ -903,6 +1019,7 @@ var SyncService = class {
|
|
|
903
1019
|
* Emit a sync event
|
|
904
1020
|
*/
|
|
905
1021
|
emit(type, data) {
|
|
1022
|
+
if (this.isDisposed) return;
|
|
906
1023
|
const event = {
|
|
907
1024
|
type,
|
|
908
1025
|
timestamp: Date.now(),
|
|
@@ -920,14 +1037,31 @@ var SyncService = class {
|
|
|
920
1037
|
// Lifecycle
|
|
921
1038
|
// ============================================
|
|
922
1039
|
/**
|
|
923
|
-
* Dispose the sync service
|
|
1040
|
+
* Dispose the sync service.
|
|
1041
|
+
*
|
|
1042
|
+
* Stops auto-sync and connectivity listening, drops every callback and
|
|
1043
|
+
* event listener, and cancels an in-flight sync: it writes nothing more to
|
|
1044
|
+
* local storage, its remote calls are aborted (the adapter receives an
|
|
1045
|
+
* AbortSignal) and it releases the sync lock. The returned promise settles
|
|
1046
|
+
* once that sync has stopped and the lock is free, so a caller switching
|
|
1047
|
+
* accounts can `await` it before starting the next account's service.
|
|
1048
|
+
* Calling it without awaiting is fine; it is idempotent.
|
|
924
1049
|
*/
|
|
925
1050
|
dispose() {
|
|
926
|
-
this.
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
1051
|
+
if (!this.lifetime.signal.aborted) {
|
|
1052
|
+
this.stopAutoSync();
|
|
1053
|
+
this.connectivityUnsubscribe?.();
|
|
1054
|
+
this.connectivityUnsubscribe = null;
|
|
1055
|
+
this.connectivity.dispose();
|
|
1056
|
+
this.queue.dispose();
|
|
1057
|
+
this.eventListeners.clear();
|
|
1058
|
+
this.onSyncComplete = void 0;
|
|
1059
|
+
this.onConflictDetected = void 0;
|
|
1060
|
+
this.onOnlineStatusChange = void 0;
|
|
1061
|
+
this.onSyncError = void 0;
|
|
1062
|
+
this.lifetime.abort();
|
|
1063
|
+
}
|
|
1064
|
+
return (this.activeSync ?? Promise.resolve()).then(() => void 0);
|
|
931
1065
|
}
|
|
932
1066
|
// ============================================
|
|
933
1067
|
// Private Methods
|
|
@@ -945,19 +1079,23 @@ var SyncService = class {
|
|
|
945
1079
|
const conflicts = [];
|
|
946
1080
|
const failures = [];
|
|
947
1081
|
const localDrafts = await this.draftManager.listDrafts();
|
|
1082
|
+
this.ensureActive();
|
|
948
1083
|
const pendingDrafts = localDrafts.filter((d) => PENDING_STATUSES.includes(d.syncStatus));
|
|
949
|
-
const remoteDrafts = await this.syncAdapter.fetchDrafts();
|
|
1084
|
+
const remoteDrafts = await this.remote((signal) => this.syncAdapter.fetchDrafts({ signal }));
|
|
950
1085
|
const remoteMap = new Map(remoteDrafts.map((r) => [r.id, r]));
|
|
951
1086
|
for (const metadata of pendingDrafts) {
|
|
1087
|
+
this.ensureActive();
|
|
952
1088
|
if (this.isBackedOff(metadata.id, startTime)) continue;
|
|
953
1089
|
try {
|
|
954
1090
|
const draft = await this.draftManager.getDraft(metadata.id);
|
|
1091
|
+
this.ensureActive();
|
|
955
1092
|
if (!draft) continue;
|
|
956
1093
|
const result = await this.syncSingleDraft(draft);
|
|
957
1094
|
this.uploadFailures.delete(metadata.id);
|
|
958
1095
|
if (result.uploaded) uploaded++;
|
|
959
1096
|
if (result.conflict) conflicts.push(result.conflict);
|
|
960
1097
|
} catch (error) {
|
|
1098
|
+
if (error instanceof SyncDisposedError) throw error;
|
|
961
1099
|
this.recordUploadFailure(metadata.id, startTime);
|
|
962
1100
|
failures.push({
|
|
963
1101
|
operation: "upload",
|
|
@@ -968,6 +1106,7 @@ var SyncService = class {
|
|
|
968
1106
|
}
|
|
969
1107
|
}
|
|
970
1108
|
for (const remote of remoteDrafts) {
|
|
1109
|
+
this.ensureActive();
|
|
971
1110
|
const localDraft = localDrafts.find((d) => d.remoteId === remote.id);
|
|
972
1111
|
try {
|
|
973
1112
|
if (!localDraft) {
|
|
@@ -975,6 +1114,7 @@ var SyncService = class {
|
|
|
975
1114
|
downloaded++;
|
|
976
1115
|
} else if (localDraft.syncStatus === "synced") {
|
|
977
1116
|
const local = await this.draftManager.getDraft(localDraft.id);
|
|
1117
|
+
this.ensureActive();
|
|
978
1118
|
if (local && remote.updatedAt > (local.metadata.lastSyncedAt ?? 0)) {
|
|
979
1119
|
if (hasLocalEdits(local.metadata)) {
|
|
980
1120
|
conflicts.push(createConflict(local, remote));
|
|
@@ -987,6 +1127,7 @@ var SyncService = class {
|
|
|
987
1127
|
}
|
|
988
1128
|
}
|
|
989
1129
|
} catch (error) {
|
|
1130
|
+
if (error instanceof SyncDisposedError) throw error;
|
|
990
1131
|
failures.push({
|
|
991
1132
|
operation: "download",
|
|
992
1133
|
draftId: localDraft?.id,
|
|
@@ -999,7 +1140,9 @@ var SyncService = class {
|
|
|
999
1140
|
for (const metadata of syncedDrafts) {
|
|
1000
1141
|
if (remoteMap.has(metadata.remoteId)) continue;
|
|
1001
1142
|
try {
|
|
1143
|
+
this.ensureActive();
|
|
1002
1144
|
const current = await this.draftManager.getDraftMetadata(metadata.id);
|
|
1145
|
+
this.ensureActive();
|
|
1003
1146
|
if (!current || current.syncStatus !== "synced" || current.version !== metadata.version || current.remoteId !== metadata.remoteId) {
|
|
1004
1147
|
continue;
|
|
1005
1148
|
}
|
|
@@ -1011,6 +1154,7 @@ var SyncService = class {
|
|
|
1011
1154
|
this.emit("draft:deleted", { draftId: metadata.id, remoteId: metadata.remoteId });
|
|
1012
1155
|
}
|
|
1013
1156
|
} catch (error) {
|
|
1157
|
+
if (error instanceof SyncDisposedError) throw error;
|
|
1014
1158
|
failures.push({
|
|
1015
1159
|
operation: "delete",
|
|
1016
1160
|
draftId: metadata.id,
|
|
@@ -1056,24 +1200,28 @@ var SyncService = class {
|
|
|
1056
1200
|
const payload = this.createPayload(draft);
|
|
1057
1201
|
try {
|
|
1058
1202
|
if (draft.metadata.remoteId) {
|
|
1059
|
-
|
|
1060
|
-
await this.
|
|
1203
|
+
const remoteId = draft.metadata.remoteId;
|
|
1204
|
+
await this.remote((signal) => this.syncAdapter.updateDraft(remoteId, payload, { signal }));
|
|
1205
|
+
await this.markUploaded(draft, remoteId);
|
|
1061
1206
|
this.emit("draft:uploaded", {
|
|
1062
1207
|
draftId: draft.metadata.id,
|
|
1063
1208
|
remoteId: draft.metadata.remoteId
|
|
1064
1209
|
});
|
|
1065
1210
|
return { uploaded: true, downloaded: false, conflict: null };
|
|
1066
1211
|
} else {
|
|
1067
|
-
const remote = await this.
|
|
1212
|
+
const remote = await this.remote(
|
|
1213
|
+
(signal) => this.syncAdapter.createDraft(payload, { signal })
|
|
1214
|
+
);
|
|
1068
1215
|
await this.markUploaded(draft, remote.id);
|
|
1069
1216
|
this.emit("draft:uploaded", { draftId: draft.metadata.id, remoteId: remote.id });
|
|
1070
1217
|
return { uploaded: true, downloaded: false, conflict: null };
|
|
1071
1218
|
}
|
|
1072
1219
|
} catch (error) {
|
|
1073
1220
|
if (isSyncConflictError(error)) {
|
|
1074
|
-
const remotes = await this.syncAdapter.fetchDrafts();
|
|
1221
|
+
const remotes = await this.remote((signal) => this.syncAdapter.fetchDrafts({ signal }));
|
|
1075
1222
|
const remote = remotes.find((r) => r.id === draft.metadata.remoteId);
|
|
1076
1223
|
if (remote) {
|
|
1224
|
+
this.ensureActive();
|
|
1077
1225
|
const conflict = createConflict(draft, remote);
|
|
1078
1226
|
await this.draftManager.updateDraftMetadata(draft.metadata.id, {
|
|
1079
1227
|
syncStatus: "conflict"
|
|
@@ -1092,12 +1240,14 @@ var SyncService = class {
|
|
|
1092
1240
|
*/
|
|
1093
1241
|
async markUploaded(draft, remoteId) {
|
|
1094
1242
|
const { id, version } = draft.metadata;
|
|
1243
|
+
this.ensureActive();
|
|
1095
1244
|
const marked = await this.draftManager.updateDraftMetadata(
|
|
1096
1245
|
id,
|
|
1097
1246
|
{ remoteId, syncStatus: "synced", lastSyncedAt: Date.now(), syncedVersion: version },
|
|
1098
1247
|
{ expectedVersion: version }
|
|
1099
1248
|
);
|
|
1100
1249
|
if (!marked) {
|
|
1250
|
+
this.ensureActive();
|
|
1101
1251
|
await this.draftManager.updateDraftMetadata(id, { remoteId });
|
|
1102
1252
|
}
|
|
1103
1253
|
}
|
|
@@ -1106,6 +1256,7 @@ var SyncService = class {
|
|
|
1106
1256
|
* is unchanged since it was read; returns false when a local edit won.
|
|
1107
1257
|
*/
|
|
1108
1258
|
async downloadRemoteDraft(remote, existing) {
|
|
1259
|
+
this.ensureActive();
|
|
1109
1260
|
if (existing) {
|
|
1110
1261
|
const { id, version } = existing.metadata;
|
|
1111
1262
|
const applied = await this.draftManager.updateDraft(id, remote.data, remote.fileRefs, {
|
|
@@ -1115,6 +1266,7 @@ var SyncService = class {
|
|
|
1115
1266
|
if (!applied) {
|
|
1116
1267
|
return false;
|
|
1117
1268
|
}
|
|
1269
|
+
this.ensureActive();
|
|
1118
1270
|
await this.draftManager.updateDraftMetadata(
|
|
1119
1271
|
id,
|
|
1120
1272
|
{
|
|
@@ -1131,6 +1283,10 @@ var SyncService = class {
|
|
|
1131
1283
|
initialData: remote.data,
|
|
1132
1284
|
initialFileRefs: remote.fileRefs
|
|
1133
1285
|
});
|
|
1286
|
+
if (this.isDisposed) {
|
|
1287
|
+
await this.draftManager.deleteDraft(metadata.id, false);
|
|
1288
|
+
throw new SyncDisposedError();
|
|
1289
|
+
}
|
|
1134
1290
|
await this.draftManager.updateDraftMetadata(metadata.id, {
|
|
1135
1291
|
syncStatus: "synced",
|
|
1136
1292
|
remoteId: remote.id,
|
|
@@ -1189,6 +1345,7 @@ var SyncService = class {
|
|
|
1189
1345
|
* Save conflicts to storage
|
|
1190
1346
|
*/
|
|
1191
1347
|
async saveConflicts() {
|
|
1348
|
+
if (this.isDisposed) return;
|
|
1192
1349
|
try {
|
|
1193
1350
|
await this.adapter.storeJSON(CONFLICTS_STORAGE_KEY, this.conflicts, {
|
|
1194
1351
|
tags: ["sync-conflicts"]
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { CacheService } from './cache/index.js';
|
|
|
8
8
|
export { CACHE_PREFIX, CacheEntry, CacheGetResult, CacheOptions, CacheStats, GetOrSetOptions, createCacheService, invalidateAllCache, invalidateCacheByTag } from './cache/index.js';
|
|
9
9
|
export { CreateAdapterOptions, CreateAdapterResult, createAdapter, detectAvailableAdapters } from './storage/index.js';
|
|
10
10
|
export { C as CreateDraftOptions, D as DRAFT_PREFIX, a as DRAFT_V2_PREFIX, b as DraftMetadata, c as DraftSyncStatus, L as ListDraftsOptions, d as LoadDraftOptions, e as LoadDraftResult, S as SaveDraftOptions, f as StoredDraft, g as StoredDraftV2, h as generateDraftId, i as getOrCreateDeviceId } from './types-CRMTQnjY.js';
|
|
11
|
-
export { ConflictResolution, ConnectivityMonitor, ConnectivityState, DraftConflict, DraftPayload, PendingSyncOperation, RemoteDraft, SyncAdapter, SyncConfig, SyncEvent, SyncEventListener, SyncEventType, SyncFailure, SyncQueue, SyncQueueState, SyncRequest, SyncResponse, SyncResult, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './sync/index.js';
|
|
11
|
+
export { ConflictResolution, ConnectivityMonitor, ConnectivityState, DraftConflict, DraftPayload, PendingSyncOperation, RemoteDraft, SyncAdapter, SyncAdapterCallOptions, SyncConfig, SyncEvent, SyncEventListener, SyncEventType, SyncFailure, SyncQueue, SyncQueueState, SyncRequest, SyncResponse, SyncResult, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './sync/index.js';
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* Error types for the offline storage package
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { CACHE_PREFIX, CacheService, createCacheService, detectStorageAdapter, getOfflineStorage, getOfflineStorageOrNull, initOfflineStorage, invalidateAllCache, invalidateCacheByTag, isOfflineStorageInitialized, resetOfflineStorage } from './chunk-
|
|
1
|
+
export { CACHE_PREFIX, CacheService, createCacheService, detectStorageAdapter, getOfflineStorage, getOfflineStorageOrNull, initOfflineStorage, invalidateAllCache, invalidateCacheByTag, isOfflineStorageInitialized, resetOfflineStorage } from './chunk-SLDAYKRY.js';
|
|
2
2
|
export { OfflineStorageError, createAdapter, detectAvailableAdapters, detectBrowser, isBrowser, isSSR, isWorker, supportsIndexedDB, supportsLocalStorage, supportsOPFS } from './chunk-4KL3GDYP.js';
|
|
3
3
|
export { FileStorageService, createFileStorageService } from './chunk-R2IP2AA5.js';
|
|
4
4
|
export { DraftStorageService, createDraftStorageService } from './chunk-UL7MZBSF.js';
|
|
5
|
-
export { ConnectivityMonitor, SyncQueue, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './chunk-
|
|
5
|
+
export { ConnectivityMonitor, SyncQueue, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './chunk-YTJQYSHR.js';
|
|
6
6
|
export { DRAFT_PREFIX, DRAFT_V2_PREFIX, DraftManagerService, createDraftManagerService, generateDraftId, getOrCreateDeviceId } from './chunk-MA4ZHPQS.js';
|
|
7
7
|
export { CleanupScheduler, DEFAULT_EXPIRATIONS, calculateExpiration, isExpired } from './chunk-QS7N4PTV.js';
|
package/dist/sync/index.d.ts
CHANGED
|
@@ -122,6 +122,17 @@ interface SyncResponse {
|
|
|
122
122
|
/**
|
|
123
123
|
* Sync adapter interface - implement this to connect to your backend
|
|
124
124
|
*/
|
|
125
|
+
/**
|
|
126
|
+
* Per-call options the sync service passes to a {@link SyncAdapter}.
|
|
127
|
+
*/
|
|
128
|
+
interface SyncAdapterCallOptions {
|
|
129
|
+
/**
|
|
130
|
+
* Aborted when the sync service is disposed (logout, account switch,
|
|
131
|
+
* unmount). Pass it to `fetch` so the request is cancelled; the service
|
|
132
|
+
* ignores the call's result after disposal either way.
|
|
133
|
+
*/
|
|
134
|
+
signal?: AbortSignal;
|
|
135
|
+
}
|
|
125
136
|
interface SyncAdapter {
|
|
126
137
|
/**
|
|
127
138
|
* Fetch all drafts for the current user.
|
|
@@ -131,23 +142,23 @@ interface SyncAdapter {
|
|
|
131
142
|
* deleted on the server and deletes the local copy (unless it was edited
|
|
132
143
|
* since the sync started). Throw instead of returning a partial list.
|
|
133
144
|
*/
|
|
134
|
-
fetchDrafts(): Promise<RemoteDraft[]>;
|
|
145
|
+
fetchDrafts(options?: SyncAdapterCallOptions): Promise<RemoteDraft[]>;
|
|
135
146
|
/**
|
|
136
147
|
* Fetch drafts changed since a timestamp
|
|
137
148
|
*/
|
|
138
|
-
fetchChanges(since: number): Promise<RemoteDraft[]>;
|
|
149
|
+
fetchChanges(since: number, options?: SyncAdapterCallOptions): Promise<RemoteDraft[]>;
|
|
139
150
|
/**
|
|
140
151
|
* Create a new draft on the server
|
|
141
152
|
*/
|
|
142
|
-
createDraft(draft: DraftPayload): Promise<RemoteDraft>;
|
|
153
|
+
createDraft(draft: DraftPayload, options?: SyncAdapterCallOptions): Promise<RemoteDraft>;
|
|
143
154
|
/**
|
|
144
155
|
* Update an existing draft on the server
|
|
145
156
|
*/
|
|
146
|
-
updateDraft(remoteId: string, draft: DraftPayload): Promise<RemoteDraft>;
|
|
157
|
+
updateDraft(remoteId: string, draft: DraftPayload, options?: SyncAdapterCallOptions): Promise<RemoteDraft>;
|
|
147
158
|
/**
|
|
148
159
|
* Delete a draft from the server
|
|
149
160
|
*/
|
|
150
|
-
deleteDraft(remoteId: string): Promise<void>;
|
|
161
|
+
deleteDraft(remoteId: string, options?: SyncAdapterCallOptions): Promise<void>;
|
|
151
162
|
/**
|
|
152
163
|
* Batch sync operation (optional, for efficiency)
|
|
153
164
|
*/
|
|
@@ -366,14 +377,22 @@ declare function createConnectivityMonitor(): ConnectivityMonitor;
|
|
|
366
377
|
declare class SyncQueue {
|
|
367
378
|
private readonly adapter;
|
|
368
379
|
private state;
|
|
369
|
-
|
|
380
|
+
/** Write currently being performed by the adapter */
|
|
381
|
+
private activeSave;
|
|
382
|
+
/** Write scheduled after `activeSave`, not started yet; later mutations join it */
|
|
383
|
+
private queuedSave;
|
|
384
|
+
/** The latest write failed, so storage is behind the in-memory state */
|
|
385
|
+
private unsaved;
|
|
370
386
|
constructor(adapter: StorageAdapter);
|
|
371
387
|
/**
|
|
372
388
|
* Initialize the queue from storage
|
|
373
389
|
*/
|
|
374
390
|
initialize(): Promise<void>;
|
|
375
391
|
/**
|
|
376
|
-
*
|
|
392
|
+
* Persist queue state. Resolves once the adapter has stored a snapshot that
|
|
393
|
+
* includes every mutation made before the call, and rejects if that write
|
|
394
|
+
* fails. Writes are serialised; calls made while a write is in flight share
|
|
395
|
+
* the next one, so bursts cost at most two writes.
|
|
377
396
|
*/
|
|
378
397
|
private save;
|
|
379
398
|
/**
|
|
@@ -461,9 +480,12 @@ declare class SyncQueue {
|
|
|
461
480
|
*/
|
|
462
481
|
clearAll(): Promise<void>;
|
|
463
482
|
/**
|
|
464
|
-
* Dispose the queue
|
|
483
|
+
* Dispose the queue, flushing any write still in flight (or retrying one
|
|
484
|
+
* that failed). The returned promise rejects if that write fails; callers
|
|
485
|
+
* that do not await it are unaffected (the rejection is marked handled), and
|
|
486
|
+
* a new queue on the same adapter still waits for the write before loading.
|
|
465
487
|
*/
|
|
466
|
-
dispose(): void
|
|
488
|
+
dispose(): Promise<void>;
|
|
467
489
|
}
|
|
468
490
|
/**
|
|
469
491
|
* Create a sync queue
|
|
@@ -535,6 +557,14 @@ declare class SyncService {
|
|
|
535
557
|
private pendingDraftCount;
|
|
536
558
|
/** Upload backoff per local draft ID */
|
|
537
559
|
private uploadFailures;
|
|
560
|
+
/**
|
|
561
|
+
* Aborted by dispose(). Passed to the remote adapter, raced against every
|
|
562
|
+
* remote call and checked after every await of a sync, so a disposed
|
|
563
|
+
* service writes nothing more and its sync lock is released promptly.
|
|
564
|
+
*/
|
|
565
|
+
private readonly lifetime;
|
|
566
|
+
/** Settles once the sync running under the lock (if any) has stopped */
|
|
567
|
+
private activeSync;
|
|
538
568
|
private onSyncComplete?;
|
|
539
569
|
private onConflictDetected?;
|
|
540
570
|
private onOnlineStatusChange?;
|
|
@@ -544,6 +574,17 @@ declare class SyncService {
|
|
|
544
574
|
* Initialize the sync service
|
|
545
575
|
*/
|
|
546
576
|
initialize(): Promise<void>;
|
|
577
|
+
/** Whether dispose() has been called */
|
|
578
|
+
get isDisposed(): boolean;
|
|
579
|
+
/** Throw if disposed: called after every await of a sync. */
|
|
580
|
+
private ensureActive;
|
|
581
|
+
/**
|
|
582
|
+
* Run a remote adapter call with the service's AbortSignal, settling as
|
|
583
|
+
* soon as the service is disposed even if the adapter ignores the signal.
|
|
584
|
+
*/
|
|
585
|
+
private remote;
|
|
586
|
+
/** Run `fn` under the shared sync lock, tracked so dispose() can await it. */
|
|
587
|
+
private locked;
|
|
547
588
|
/**
|
|
548
589
|
* Check if currently online
|
|
549
590
|
*/
|
|
@@ -617,9 +658,17 @@ declare class SyncService {
|
|
|
617
658
|
*/
|
|
618
659
|
private emit;
|
|
619
660
|
/**
|
|
620
|
-
* Dispose the sync service
|
|
661
|
+
* Dispose the sync service.
|
|
662
|
+
*
|
|
663
|
+
* Stops auto-sync and connectivity listening, drops every callback and
|
|
664
|
+
* event listener, and cancels an in-flight sync: it writes nothing more to
|
|
665
|
+
* local storage, its remote calls are aborted (the adapter receives an
|
|
666
|
+
* AbortSignal) and it releases the sync lock. The returned promise settles
|
|
667
|
+
* once that sync has stopped and the lock is free, so a caller switching
|
|
668
|
+
* accounts can `await` it before starting the next account's service.
|
|
669
|
+
* Calling it without awaiting is fine; it is idempotent.
|
|
621
670
|
*/
|
|
622
|
-
dispose(): void
|
|
671
|
+
dispose(): Promise<void>;
|
|
623
672
|
/**
|
|
624
673
|
* Perform the actual sync. One draft failing does not stop the rest: each
|
|
625
674
|
* failure is recorded in `failures` and the sync carries on.
|
|
@@ -675,4 +724,4 @@ declare class SyncService {
|
|
|
675
724
|
*/
|
|
676
725
|
declare function createSyncService(adapter: StorageAdapter, config: SyncConfig): SyncService;
|
|
677
726
|
|
|
678
|
-
export { type ConflictResolution, ConnectivityMonitor, type ConnectivityState, type DraftConflict, type DraftPayload, type PendingSyncOperation, type RemoteDraft, type SyncAdapter, type SyncConfig, SyncConflictError, type SyncEvent, type SyncEventListener, type SyncEventType, type SyncFailure, SyncQueue, type SyncQueueState, type SyncRequest, type SyncResponse, type SyncResult, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge };
|
|
727
|
+
export { type ConflictResolution, ConnectivityMonitor, type ConnectivityState, type DraftConflict, type DraftPayload, type PendingSyncOperation, type RemoteDraft, type SyncAdapter, type SyncAdapterCallOptions, type SyncConfig, SyncConflictError, type SyncEvent, type SyncEventListener, type SyncEventType, type SyncFailure, SyncQueue, type SyncQueueState, type SyncRequest, type SyncResponse, type SyncResult, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge };
|
package/dist/sync/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { ConnectivityMonitor, SyncConflictError, SyncQueue, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge } from '../chunk-
|
|
1
|
+
export { ConnectivityMonitor, SyncConflictError, SyncQueue, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge } from '../chunk-YTJQYSHR.js';
|
|
2
2
|
import '../chunk-MA4ZHPQS.js';
|
|
3
3
|
import '../chunk-QS7N4PTV.js';
|