@classic-homes/offline-core 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  */
@@ -1,4 +1,4 @@
1
- export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-JPXEFKZO.js';
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';
@@ -585,6 +585,12 @@ var CONFLICTS_STORAGE_KEY = "sync-conflicts";
585
585
  var RETRY_BASE_DELAY_MS = 5e3;
586
586
  var RETRY_MAX_DELAY_MS = 15 * 60 * 1e3;
587
587
  var PENDING_STATUSES = ["pending-upload", "local-only"];
588
+ var SyncDisposedError = class extends Error {
589
+ constructor() {
590
+ super("Sync service disposed");
591
+ this.name = "SyncDisposedError";
592
+ }
593
+ };
588
594
  function errorMessage(error) {
589
595
  return error instanceof Error ? error.message : String(error);
590
596
  }
@@ -604,6 +610,14 @@ var SyncService = class {
604
610
  this.pendingDraftCount = 0;
605
611
  /** Upload backoff per local draft ID */
606
612
  this.uploadFailures = /* @__PURE__ */ new Map();
613
+ /**
614
+ * Aborted by dispose(). Passed to the remote adapter, raced against every
615
+ * remote call and checked after every await of a sync, so a disposed
616
+ * service writes nothing more and its sync lock is released promptly.
617
+ */
618
+ this.lifetime = new AbortController();
619
+ /** Settles once the sync running under the lock (if any) has stopped */
620
+ this.activeSync = null;
607
621
  this.syncAdapter = config.adapter;
608
622
  this.config = {
609
623
  syncIntervalMs: config.syncIntervalMs ?? DEFAULT_SYNC_INTERVAL,
@@ -633,6 +647,56 @@ var SyncService = class {
633
647
  await this.loadConflicts();
634
648
  await this.refreshPendingCount();
635
649
  }
650
+ /** Whether dispose() has been called */
651
+ get isDisposed() {
652
+ return this.lifetime.signal.aborted;
653
+ }
654
+ /** Throw if disposed: called after every await of a sync. */
655
+ ensureActive() {
656
+ if (this.lifetime.signal.aborted) throw new SyncDisposedError();
657
+ }
658
+ /**
659
+ * Run a remote adapter call with the service's AbortSignal, settling as
660
+ * soon as the service is disposed even if the adapter ignores the signal.
661
+ */
662
+ remote(call) {
663
+ const signal = this.lifetime.signal;
664
+ if (signal.aborted) return Promise.reject(new SyncDisposedError());
665
+ return new Promise((resolve, reject) => {
666
+ const onAbort = () => reject(new SyncDisposedError());
667
+ signal.addEventListener("abort", onAbort, { once: true });
668
+ let pending;
669
+ try {
670
+ pending = Promise.resolve(call(signal));
671
+ } catch (error) {
672
+ pending = Promise.reject(error);
673
+ }
674
+ pending.then(
675
+ (value) => {
676
+ signal.removeEventListener("abort", onAbort);
677
+ if (signal.aborted) reject(new SyncDisposedError());
678
+ else resolve(value);
679
+ },
680
+ (error) => {
681
+ signal.removeEventListener("abort", onAbort);
682
+ reject(signal.aborted ? new SyncDisposedError() : error);
683
+ }
684
+ );
685
+ });
686
+ }
687
+ /** Run `fn` under the shared sync lock, tracked so dispose() can await it. */
688
+ async locked(fn) {
689
+ const run = withSyncLock(fn);
690
+ this.activeSync = run.catch(() => {
691
+ });
692
+ try {
693
+ const result = await run;
694
+ if (this.isDisposed) return this.createErrorResult("Sync service disposed");
695
+ return result.acquired ? result.value : this.createErrorResult("Sync already in progress");
696
+ } finally {
697
+ this.activeSync = null;
698
+ }
699
+ }
636
700
  // ============================================
637
701
  // Properties
638
702
  // ============================================
@@ -693,6 +757,9 @@ var SyncService = class {
693
757
  * Sync all drafts
694
758
  */
695
759
  async syncAll() {
760
+ if (this.isDisposed) {
761
+ return this.createErrorResult("Sync service disposed");
762
+ }
696
763
  if (this.isSyncing) {
697
764
  return this.createErrorResult("Sync already in progress");
698
765
  }
@@ -701,8 +768,7 @@ var SyncService = class {
701
768
  }
702
769
  this.isSyncing = true;
703
770
  try {
704
- const locked = await withSyncLock(() => this.runSyncAll());
705
- return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
771
+ return await this.locked(() => this.runSyncAll());
706
772
  } finally {
707
773
  this.isSyncing = false;
708
774
  }
@@ -712,6 +778,7 @@ var SyncService = class {
712
778
  this.emit("sync:start", null);
713
779
  try {
714
780
  const result = await this.performSync();
781
+ this.ensureActive();
715
782
  this.lastSyncResult = result;
716
783
  if (result.conflicts.length > 0) {
717
784
  const byId = new Map(this.conflicts.map((c) => [c.localDraftId, c]));
@@ -720,11 +787,14 @@ var SyncService = class {
720
787
  }
721
788
  this.conflicts = [...byId.values()];
722
789
  await this.saveConflicts();
790
+ this.ensureActive();
723
791
  this.emit("sync:conflict", result.conflicts);
724
792
  this.onConflictDetected?.(result.conflicts);
725
793
  }
794
+ this.ensureActive();
726
795
  await this.queue.updateLastSyncAt(Date.now());
727
796
  await this.refreshPendingCount();
797
+ this.ensureActive();
728
798
  this.emit("sync:complete", result);
729
799
  this.onSyncComplete?.(result);
730
800
  return result;
@@ -733,7 +803,9 @@ var SyncService = class {
733
803
  error instanceof Error ? error.message : "Unknown error",
734
804
  startTime
735
805
  );
806
+ if (this.isDisposed) return errorResult;
736
807
  await this.refreshPendingCount();
808
+ if (this.isDisposed) return errorResult;
737
809
  this.emit("sync:error", error);
738
810
  this.onSyncError?.(error instanceof Error ? error : new Error(String(error)));
739
811
  return errorResult;
@@ -743,6 +815,9 @@ var SyncService = class {
743
815
  * Sync a specific draft
744
816
  */
745
817
  async syncDraft(draftId) {
818
+ if (this.isDisposed) {
819
+ return this.createErrorResult("Sync service disposed");
820
+ }
746
821
  if (this.isSyncing) {
747
822
  return this.createErrorResult("Sync already in progress");
748
823
  }
@@ -751,8 +826,7 @@ var SyncService = class {
751
826
  }
752
827
  this.isSyncing = true;
753
828
  try {
754
- const locked = await withSyncLock(() => this.runSyncDraft(draftId));
755
- return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
829
+ return await this.locked(() => this.runSyncDraft(draftId));
756
830
  } finally {
757
831
  this.isSyncing = false;
758
832
  }
@@ -761,6 +835,7 @@ var SyncService = class {
761
835
  const startTime = Date.now();
762
836
  try {
763
837
  const draft = await this.draftManager.getDraft(draftId);
838
+ this.ensureActive();
764
839
  if (!draft) {
765
840
  return this.createErrorResult("Draft not found");
766
841
  }
@@ -769,7 +844,7 @@ var SyncService = class {
769
844
  result = await this.syncSingleDraft(draft);
770
845
  this.uploadFailures.delete(draftId);
771
846
  } catch (error) {
772
- this.recordUploadFailure(draftId, startTime);
847
+ if (!this.isDisposed) this.recordUploadFailure(draftId, startTime);
773
848
  throw error;
774
849
  }
775
850
  return {
@@ -788,46 +863,56 @@ var SyncService = class {
788
863
  startTime
789
864
  );
790
865
  } finally {
791
- await this.refreshPendingCount();
866
+ if (!this.isDisposed) await this.refreshPendingCount();
792
867
  }
793
868
  }
794
869
  /**
795
870
  * Force push a draft (overwrite remote)
796
871
  */
797
872
  async forcePush(draftId) {
873
+ this.ensureActive();
798
874
  const draft = await this.draftManager.getDraft(draftId);
875
+ this.ensureActive();
799
876
  if (!draft) {
800
877
  throw new Error("Draft not found");
801
878
  }
802
879
  const payload = this.createPayload(draft);
803
880
  if (draft.metadata.remoteId) {
804
- await this.syncAdapter.updateDraft(draft.metadata.remoteId, payload);
805
- await this.markUploaded(draft, draft.metadata.remoteId);
881
+ const remoteId = draft.metadata.remoteId;
882
+ await this.remote((signal) => this.syncAdapter.updateDraft(remoteId, payload, { signal }));
883
+ await this.markUploaded(draft, remoteId);
806
884
  } else {
807
- const remote = await this.syncAdapter.createDraft(payload);
885
+ const remote = await this.remote(
886
+ (signal) => this.syncAdapter.createDraft(payload, { signal })
887
+ );
808
888
  await this.markUploaded(draft, remote.id);
809
889
  }
890
+ this.ensureActive();
810
891
  await this.removeConflict(draftId);
811
892
  }
812
893
  /**
813
894
  * Force pull a draft (overwrite local)
814
895
  */
815
896
  async forcePull(draftId) {
897
+ this.ensureActive();
816
898
  const draft = await this.draftManager.getDraft(draftId);
899
+ this.ensureActive();
817
900
  if (!draft || !draft.metadata.remoteId) {
818
901
  throw new Error("Draft not found or not synced");
819
902
  }
820
- const remotes = await this.syncAdapter.fetchDrafts();
903
+ const remotes = await this.remote((signal) => this.syncAdapter.fetchDrafts({ signal }));
821
904
  const remote = remotes.find((r) => r.id === draft.metadata.remoteId);
822
905
  if (!remote) {
823
906
  throw new Error("Remote draft not found");
824
907
  }
825
908
  await this.draftManager.updateDraft(draftId, remote.data, remote.fileRefs);
909
+ this.ensureActive();
826
910
  await this.draftManager.updateDraftMetadata(draftId, {
827
911
  name: remote.name,
828
912
  syncStatus: "synced",
829
913
  lastSyncedAt: Date.now()
830
914
  });
915
+ this.ensureActive();
831
916
  await this.removeConflict(draftId);
832
917
  }
833
918
  // ============================================
@@ -842,7 +927,9 @@ var SyncService = class {
842
927
  throw new Error("Conflict not found");
843
928
  }
844
929
  const resolved = applyResolution(conflict.localDraft, conflict.remoteDraft, resolution);
930
+ this.ensureActive();
845
931
  await this.draftManager.updateDraft(draftId, resolved.data, resolved.fileRefs);
932
+ this.ensureActive();
846
933
  await this.draftManager.updateDraftMetadata(draftId, {
847
934
  name: resolved.metadata.name,
848
935
  syncStatus: resolved.metadata.syncStatus,
@@ -851,6 +938,7 @@ var SyncService = class {
851
938
  if (resolution === "keep-local" || resolution === "merge") {
852
939
  await this.forcePush(draftId);
853
940
  }
941
+ this.ensureActive();
854
942
  await this.removeConflict(draftId);
855
943
  }
856
944
  // ============================================
@@ -863,6 +951,9 @@ var SyncService = class {
863
951
  if (this.autoSyncInterval !== null) {
864
952
  return;
865
953
  }
954
+ if (this.isDisposed) {
955
+ return;
956
+ }
866
957
  this.autoSyncInterval = setInterval(() => {
867
958
  if (this.isOnline && !this.isSyncing) {
868
959
  void this.syncAll();
@@ -903,6 +994,7 @@ var SyncService = class {
903
994
  * Emit a sync event
904
995
  */
905
996
  emit(type, data) {
997
+ if (this.isDisposed) return;
906
998
  const event = {
907
999
  type,
908
1000
  timestamp: Date.now(),
@@ -920,14 +1012,31 @@ var SyncService = class {
920
1012
  // Lifecycle
921
1013
  // ============================================
922
1014
  /**
923
- * Dispose the sync service
1015
+ * Dispose the sync service.
1016
+ *
1017
+ * Stops auto-sync and connectivity listening, drops every callback and
1018
+ * event listener, and cancels an in-flight sync: it writes nothing more to
1019
+ * local storage, its remote calls are aborted (the adapter receives an
1020
+ * AbortSignal) and it releases the sync lock. The returned promise settles
1021
+ * once that sync has stopped and the lock is free, so a caller switching
1022
+ * accounts can `await` it before starting the next account's service.
1023
+ * Calling it without awaiting is fine; it is idempotent.
924
1024
  */
925
1025
  dispose() {
926
- this.stopAutoSync();
927
- this.connectivityUnsubscribe?.();
928
- this.connectivity.dispose();
929
- this.queue.dispose();
930
- this.eventListeners.clear();
1026
+ if (!this.lifetime.signal.aborted) {
1027
+ this.stopAutoSync();
1028
+ this.connectivityUnsubscribe?.();
1029
+ this.connectivityUnsubscribe = null;
1030
+ this.connectivity.dispose();
1031
+ this.queue.dispose();
1032
+ this.eventListeners.clear();
1033
+ this.onSyncComplete = void 0;
1034
+ this.onConflictDetected = void 0;
1035
+ this.onOnlineStatusChange = void 0;
1036
+ this.onSyncError = void 0;
1037
+ this.lifetime.abort();
1038
+ }
1039
+ return (this.activeSync ?? Promise.resolve()).then(() => void 0);
931
1040
  }
932
1041
  // ============================================
933
1042
  // Private Methods
@@ -945,19 +1054,23 @@ var SyncService = class {
945
1054
  const conflicts = [];
946
1055
  const failures = [];
947
1056
  const localDrafts = await this.draftManager.listDrafts();
1057
+ this.ensureActive();
948
1058
  const pendingDrafts = localDrafts.filter((d) => PENDING_STATUSES.includes(d.syncStatus));
949
- const remoteDrafts = await this.syncAdapter.fetchDrafts();
1059
+ const remoteDrafts = await this.remote((signal) => this.syncAdapter.fetchDrafts({ signal }));
950
1060
  const remoteMap = new Map(remoteDrafts.map((r) => [r.id, r]));
951
1061
  for (const metadata of pendingDrafts) {
1062
+ this.ensureActive();
952
1063
  if (this.isBackedOff(metadata.id, startTime)) continue;
953
1064
  try {
954
1065
  const draft = await this.draftManager.getDraft(metadata.id);
1066
+ this.ensureActive();
955
1067
  if (!draft) continue;
956
1068
  const result = await this.syncSingleDraft(draft);
957
1069
  this.uploadFailures.delete(metadata.id);
958
1070
  if (result.uploaded) uploaded++;
959
1071
  if (result.conflict) conflicts.push(result.conflict);
960
1072
  } catch (error) {
1073
+ if (error instanceof SyncDisposedError) throw error;
961
1074
  this.recordUploadFailure(metadata.id, startTime);
962
1075
  failures.push({
963
1076
  operation: "upload",
@@ -968,6 +1081,7 @@ var SyncService = class {
968
1081
  }
969
1082
  }
970
1083
  for (const remote of remoteDrafts) {
1084
+ this.ensureActive();
971
1085
  const localDraft = localDrafts.find((d) => d.remoteId === remote.id);
972
1086
  try {
973
1087
  if (!localDraft) {
@@ -975,6 +1089,7 @@ var SyncService = class {
975
1089
  downloaded++;
976
1090
  } else if (localDraft.syncStatus === "synced") {
977
1091
  const local = await this.draftManager.getDraft(localDraft.id);
1092
+ this.ensureActive();
978
1093
  if (local && remote.updatedAt > (local.metadata.lastSyncedAt ?? 0)) {
979
1094
  if (hasLocalEdits(local.metadata)) {
980
1095
  conflicts.push(createConflict(local, remote));
@@ -987,6 +1102,7 @@ var SyncService = class {
987
1102
  }
988
1103
  }
989
1104
  } catch (error) {
1105
+ if (error instanceof SyncDisposedError) throw error;
990
1106
  failures.push({
991
1107
  operation: "download",
992
1108
  draftId: localDraft?.id,
@@ -999,7 +1115,9 @@ var SyncService = class {
999
1115
  for (const metadata of syncedDrafts) {
1000
1116
  if (remoteMap.has(metadata.remoteId)) continue;
1001
1117
  try {
1118
+ this.ensureActive();
1002
1119
  const current = await this.draftManager.getDraftMetadata(metadata.id);
1120
+ this.ensureActive();
1003
1121
  if (!current || current.syncStatus !== "synced" || current.version !== metadata.version || current.remoteId !== metadata.remoteId) {
1004
1122
  continue;
1005
1123
  }
@@ -1011,6 +1129,7 @@ var SyncService = class {
1011
1129
  this.emit("draft:deleted", { draftId: metadata.id, remoteId: metadata.remoteId });
1012
1130
  }
1013
1131
  } catch (error) {
1132
+ if (error instanceof SyncDisposedError) throw error;
1014
1133
  failures.push({
1015
1134
  operation: "delete",
1016
1135
  draftId: metadata.id,
@@ -1056,24 +1175,28 @@ var SyncService = class {
1056
1175
  const payload = this.createPayload(draft);
1057
1176
  try {
1058
1177
  if (draft.metadata.remoteId) {
1059
- await this.syncAdapter.updateDraft(draft.metadata.remoteId, payload);
1060
- await this.markUploaded(draft, draft.metadata.remoteId);
1178
+ const remoteId = draft.metadata.remoteId;
1179
+ await this.remote((signal) => this.syncAdapter.updateDraft(remoteId, payload, { signal }));
1180
+ await this.markUploaded(draft, remoteId);
1061
1181
  this.emit("draft:uploaded", {
1062
1182
  draftId: draft.metadata.id,
1063
1183
  remoteId: draft.metadata.remoteId
1064
1184
  });
1065
1185
  return { uploaded: true, downloaded: false, conflict: null };
1066
1186
  } else {
1067
- const remote = await this.syncAdapter.createDraft(payload);
1187
+ const remote = await this.remote(
1188
+ (signal) => this.syncAdapter.createDraft(payload, { signal })
1189
+ );
1068
1190
  await this.markUploaded(draft, remote.id);
1069
1191
  this.emit("draft:uploaded", { draftId: draft.metadata.id, remoteId: remote.id });
1070
1192
  return { uploaded: true, downloaded: false, conflict: null };
1071
1193
  }
1072
1194
  } catch (error) {
1073
1195
  if (isSyncConflictError(error)) {
1074
- const remotes = await this.syncAdapter.fetchDrafts();
1196
+ const remotes = await this.remote((signal) => this.syncAdapter.fetchDrafts({ signal }));
1075
1197
  const remote = remotes.find((r) => r.id === draft.metadata.remoteId);
1076
1198
  if (remote) {
1199
+ this.ensureActive();
1077
1200
  const conflict = createConflict(draft, remote);
1078
1201
  await this.draftManager.updateDraftMetadata(draft.metadata.id, {
1079
1202
  syncStatus: "conflict"
@@ -1092,12 +1215,14 @@ var SyncService = class {
1092
1215
  */
1093
1216
  async markUploaded(draft, remoteId) {
1094
1217
  const { id, version } = draft.metadata;
1218
+ this.ensureActive();
1095
1219
  const marked = await this.draftManager.updateDraftMetadata(
1096
1220
  id,
1097
1221
  { remoteId, syncStatus: "synced", lastSyncedAt: Date.now(), syncedVersion: version },
1098
1222
  { expectedVersion: version }
1099
1223
  );
1100
1224
  if (!marked) {
1225
+ this.ensureActive();
1101
1226
  await this.draftManager.updateDraftMetadata(id, { remoteId });
1102
1227
  }
1103
1228
  }
@@ -1106,6 +1231,7 @@ var SyncService = class {
1106
1231
  * is unchanged since it was read; returns false when a local edit won.
1107
1232
  */
1108
1233
  async downloadRemoteDraft(remote, existing) {
1234
+ this.ensureActive();
1109
1235
  if (existing) {
1110
1236
  const { id, version } = existing.metadata;
1111
1237
  const applied = await this.draftManager.updateDraft(id, remote.data, remote.fileRefs, {
@@ -1115,6 +1241,7 @@ var SyncService = class {
1115
1241
  if (!applied) {
1116
1242
  return false;
1117
1243
  }
1244
+ this.ensureActive();
1118
1245
  await this.draftManager.updateDraftMetadata(
1119
1246
  id,
1120
1247
  {
@@ -1131,6 +1258,10 @@ var SyncService = class {
1131
1258
  initialData: remote.data,
1132
1259
  initialFileRefs: remote.fileRefs
1133
1260
  });
1261
+ if (this.isDisposed) {
1262
+ await this.draftManager.deleteDraft(metadata.id, false);
1263
+ throw new SyncDisposedError();
1264
+ }
1134
1265
  await this.draftManager.updateDraftMetadata(metadata.id, {
1135
1266
  syncStatus: "synced",
1136
1267
  remoteId: remote.id,
@@ -1189,6 +1320,7 @@ var SyncService = class {
1189
1320
  * Save conflicts to storage
1190
1321
  */
1191
1322
  async saveConflicts() {
1323
+ if (this.isDisposed) return;
1192
1324
  try {
1193
1325
  await this.adapter.storeJSON(CONFLICTS_STORAGE_KEY, this.conflicts, {
1194
1326
  tags: ["sync-conflicts"]
@@ -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.invalidate(key);
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(key, fetcher, { ttl, tags, staleTime }, onFetching, onFetchComplete);
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.set(key, value, options);
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.inFlightFetches.delete(key);
322
+ this.pendingWrites.delete(ticket);
323
+ if (this.inFlightFetches.get(key) === entry) this.inFlightFetches.delete(key);
253
324
  }
254
325
  })();
255
- this.inFlightFetches.set(key, {
256
- promise: fetchPromise,
257
- startedAt: Date.now()
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;
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-JPXEFKZO.js';
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-34PR6T4B.js';
5
+ export { ConnectivityMonitor, SyncQueue, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './chunk-NCAGT2LL.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';
@@ -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
  */
@@ -535,6 +546,14 @@ declare class SyncService {
535
546
  private pendingDraftCount;
536
547
  /** Upload backoff per local draft ID */
537
548
  private uploadFailures;
549
+ /**
550
+ * Aborted by dispose(). Passed to the remote adapter, raced against every
551
+ * remote call and checked after every await of a sync, so a disposed
552
+ * service writes nothing more and its sync lock is released promptly.
553
+ */
554
+ private readonly lifetime;
555
+ /** Settles once the sync running under the lock (if any) has stopped */
556
+ private activeSync;
538
557
  private onSyncComplete?;
539
558
  private onConflictDetected?;
540
559
  private onOnlineStatusChange?;
@@ -544,6 +563,17 @@ declare class SyncService {
544
563
  * Initialize the sync service
545
564
  */
546
565
  initialize(): Promise<void>;
566
+ /** Whether dispose() has been called */
567
+ get isDisposed(): boolean;
568
+ /** Throw if disposed: called after every await of a sync. */
569
+ private ensureActive;
570
+ /**
571
+ * Run a remote adapter call with the service's AbortSignal, settling as
572
+ * soon as the service is disposed even if the adapter ignores the signal.
573
+ */
574
+ private remote;
575
+ /** Run `fn` under the shared sync lock, tracked so dispose() can await it. */
576
+ private locked;
547
577
  /**
548
578
  * Check if currently online
549
579
  */
@@ -617,9 +647,17 @@ declare class SyncService {
617
647
  */
618
648
  private emit;
619
649
  /**
620
- * Dispose the sync service
650
+ * Dispose the sync service.
651
+ *
652
+ * Stops auto-sync and connectivity listening, drops every callback and
653
+ * event listener, and cancels an in-flight sync: it writes nothing more to
654
+ * local storage, its remote calls are aborted (the adapter receives an
655
+ * AbortSignal) and it releases the sync lock. The returned promise settles
656
+ * once that sync has stopped and the lock is free, so a caller switching
657
+ * accounts can `await` it before starting the next account's service.
658
+ * Calling it without awaiting is fine; it is idempotent.
621
659
  */
622
- dispose(): void;
660
+ dispose(): Promise<void>;
623
661
  /**
624
662
  * Perform the actual sync. One draft failing does not stop the rest: each
625
663
  * failure is recorded in `failures` and the sync carries on.
@@ -675,4 +713,4 @@ declare class SyncService {
675
713
  */
676
714
  declare function createSyncService(adapter: StorageAdapter, config: SyncConfig): SyncService;
677
715
 
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 };
716
+ 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 };
@@ -1,3 +1,3 @@
1
- export { ConnectivityMonitor, SyncConflictError, SyncQueue, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge } from '../chunk-34PR6T4B.js';
1
+ export { ConnectivityMonitor, SyncConflictError, SyncQueue, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge } from '../chunk-NCAGT2LL.js';
2
2
  import '../chunk-MA4ZHPQS.js';
3
3
  import '../chunk-QS7N4PTV.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/offline-core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Framework-agnostic offline persistence and caching for Classic Theme",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",