@classic-homes/offline-core 0.1.3 → 0.1.5

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.
@@ -1,4 +1,4 @@
1
- import { S as StorageAdapter } from '../types-CWuauHAr.js';
1
+ import { S as StorageAdapter } from '../types-DDhQm0hc.js';
2
2
 
3
3
  /**
4
4
  * Types for cache service
@@ -139,6 +139,7 @@ declare class CacheService {
139
139
  set<T>(key: string, value: T, options?: CacheOptions): Promise<void>;
140
140
  /**
141
141
  * Enforce cache size limits using LRU eviction
142
+ * @param newKey - Key being added (skip count check if it already exists)
142
143
  */
143
144
  private enforceLimit;
144
145
  /**
@@ -195,4 +196,20 @@ declare class CacheService {
195
196
  */
196
197
  declare function createCacheService(adapter: StorageAdapter): CacheService;
197
198
 
198
- export { CACHE_PREFIX, type CacheEntry, type CacheGetResult, type CacheOptions, CacheService, type CacheStats, type GetOrSetOptions, createCacheService, getCacheKey, getOriginalKey };
199
+ /**
200
+ * Cache helper utilities that work with the offline storage singleton.
201
+ */
202
+ /**
203
+ * Invalidate cache entries by tag.
204
+ *
205
+ * Returns 0 when offline storage has not been initialized.
206
+ */
207
+ declare function invalidateCacheByTag(tag: string): Promise<number>;
208
+ /**
209
+ * Invalidate all cache entries.
210
+ *
211
+ * Returns 0 when offline storage has not been initialized.
212
+ */
213
+ declare function invalidateAllCache(): Promise<number>;
214
+
215
+ export { CACHE_PREFIX, type CacheEntry, type CacheGetResult, type CacheOptions, CacheService, type CacheStats, type GetOrSetOptions, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag };
@@ -1,2 +1,6 @@
1
- export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey } from '../chunk-K7USXDTP.js';
1
+ export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-PEQVHD6Q.js';
2
+ import '../chunk-J2ZYJDJX.js';
3
+ import '../chunk-U27TKOYZ.js';
4
+ import '../chunk-EWMN3Y7N.js';
5
+ import '../chunk-WWKATW37.js';
2
6
  import '../chunk-ZC7F2HDV.js';
@@ -1,4 +1,4 @@
1
- import { generateDraftId, DraftManagerService } from './chunk-4QWZX3LM.js';
1
+ import { generateDraftId, DraftManagerService } from './chunk-WWKATW37.js';
2
2
 
3
3
  // src/sync/types.ts
4
4
  var SyncConflictError = class extends Error {
@@ -577,7 +577,7 @@ var SyncService = class {
577
577
  this.connectivity = createConnectivityMonitor();
578
578
  this.queue = createSyncQueue(adapter);
579
579
  this.connectivityUnsubscribe = this.connectivity.subscribe((online) => {
580
- this.emit("online", online);
580
+ this.emit(online ? "online" : "offline", online);
581
581
  this.onOnlineStatusChange?.(online);
582
582
  if (online && this.config.autoSyncOnReconnect) {
583
583
  void this.syncAll();
@@ -650,7 +650,11 @@ var SyncService = class {
650
650
  const result = await this.performSync();
651
651
  this.lastSyncResult = result;
652
652
  if (result.conflicts.length > 0) {
653
- this.conflicts = result.conflicts;
653
+ const byId = new Map(this.conflicts.map((c) => [c.localDraftId, c]));
654
+ for (const conflict of result.conflicts) {
655
+ byId.set(conflict.localDraftId, conflict);
656
+ }
657
+ this.conflicts = [...byId.values()];
654
658
  await this.saveConflicts();
655
659
  this.emit("sync:conflict", result.conflicts);
656
660
  this.onConflictDetected?.(result.conflicts);
@@ -675,9 +679,13 @@ var SyncService = class {
675
679
  * Sync a specific draft
676
680
  */
677
681
  async syncDraft(draftId) {
682
+ if (this.isSyncing) {
683
+ return this.createErrorResult("Sync already in progress");
684
+ }
678
685
  if (!this.isOnline) {
679
686
  return this.createErrorResult("Device is offline");
680
687
  }
688
+ this.isSyncing = true;
681
689
  const startTime = Date.now();
682
690
  try {
683
691
  const draft = await this.draftManager.getDraft(draftId);
@@ -700,6 +708,8 @@ var SyncService = class {
700
708
  error instanceof Error ? error.message : "Unknown error",
701
709
  startTime
702
710
  );
711
+ } finally {
712
+ this.isSyncing = false;
703
713
  }
704
714
  }
705
715
  /**
@@ -894,6 +904,7 @@ var SyncService = class {
894
904
  if (!remoteMap.has(metadata.remoteId)) {
895
905
  await this.draftManager.deleteDraft(metadata.id);
896
906
  deletedLocal++;
907
+ this.emit("draft:deleted", { draftId: metadata.id, remoteId: metadata.remoteId });
897
908
  }
898
909
  }
899
910
  return {
@@ -919,6 +930,10 @@ var SyncService = class {
919
930
  syncStatus: "synced",
920
931
  lastSyncedAt: Date.now()
921
932
  });
933
+ this.emit("draft:uploaded", {
934
+ draftId: draft.metadata.id,
935
+ remoteId: draft.metadata.remoteId
936
+ });
922
937
  return { uploaded: true, downloaded: false, conflict: null };
923
938
  } else {
924
939
  const remote = await this.syncAdapter.createDraft(payload);
@@ -927,6 +942,7 @@ var SyncService = class {
927
942
  syncStatus: "synced",
928
943
  lastSyncedAt: Date.now()
929
944
  });
945
+ this.emit("draft:uploaded", { draftId: draft.metadata.id, remoteId: remote.id });
930
946
  return { uploaded: true, downloaded: false, conflict: null };
931
947
  }
932
948
  } catch (error) {
@@ -1,4 +1,4 @@
1
- import { getDraftKey, DRAFT_PREFIX, getFormKeyFromDraftKey } from './chunk-4QWZX3LM.js';
1
+ import { getDraftKey, DRAFT_PREFIX, getFormKeyFromDraftKey } from './chunk-WWKATW37.js';
2
2
  import { DEFAULT_EXPIRATIONS } from './chunk-ZC7F2HDV.js';
3
3
 
4
4
  // src/drafts/service.ts
@@ -608,6 +608,23 @@ function createIndexedDBAdapter(options) {
608
608
  return new IndexedDBAdapter(options);
609
609
  }
610
610
 
611
+ // src/storage/opfs-keys.ts
612
+ function encodeOpfsKey(key) {
613
+ return encodeURIComponent(key).replace(/_/g, "%5F").replace(/%/g, "_");
614
+ }
615
+ function decodeOpfsKey(filename) {
616
+ try {
617
+ return decodeURIComponent(filename.replace(/_/g, "%"));
618
+ } catch {
619
+ return filename;
620
+ }
621
+ }
622
+ function legacyOpfsFilename(key) {
623
+ const legacy = encodeURIComponent(key).replace(/%/g, "_");
624
+ if (legacy === encodeOpfsKey(key)) return null;
625
+ return decodeOpfsKey(legacy) === key ? legacy : null;
626
+ }
627
+
611
628
  // src/worker/opfs-worker.ts
612
629
  var ROOT_DIR = "classic-offline";
613
630
  var BLOBS_DIR = "blobs";
@@ -622,10 +639,20 @@ async function initDirectories() {
622
639
  metadataHandle = await rootHandle.getDirectoryHandle(METADATA_DIR, { create: true });
623
640
  }
624
641
  function encodeKey(key) {
625
- return encodeURIComponent(key).replace(/%/g, "_");
642
+ return encodeOpfsKey(key);
626
643
  }
627
644
  function decodeKey(filename) {
628
- return decodeURIComponent(filename.replace(/_/g, "%"));
645
+ return decodeOpfsKey(filename);
646
+ }
647
+ async function removeFiles(name) {
648
+ try {
649
+ await blobsHandle.removeEntry(name);
650
+ } catch {
651
+ }
652
+ try {
653
+ await metadataHandle.removeEntry(`${name}.json`);
654
+ } catch {
655
+ }
629
656
  }
630
657
  async function storeBlob(key, blob, metadata) {
631
658
  if (!blobsHandle || !metadataHandle) {
@@ -646,14 +673,24 @@ async function storeBlob(key, blob, metadata) {
646
673
  const metaWritable = await metaFileHandle.createWritable();
647
674
  await metaWritable.write(JSON.stringify(fullMetadata));
648
675
  await metaWritable.close();
676
+ const legacy = legacyOpfsFilename(key);
677
+ if (legacy) await removeFiles(legacy);
649
678
  }
650
679
  async function getBlob(key) {
651
680
  if (!blobsHandle || !metadataHandle) {
652
681
  throw new Error("Storage not initialized");
653
682
  }
654
- const encodedKey = encodeKey(key);
683
+ let encodedKey = encodeKey(key);
655
684
  try {
656
- const blobFileHandle = await blobsHandle.getFileHandle(encodedKey);
685
+ let blobFileHandle;
686
+ try {
687
+ blobFileHandle = await blobsHandle.getFileHandle(encodedKey);
688
+ } catch (error) {
689
+ const legacy = legacyOpfsFilename(key);
690
+ if (!legacy) throw error;
691
+ blobFileHandle = await blobsHandle.getFileHandle(legacy);
692
+ encodedKey = legacy;
693
+ }
657
694
  const blobFile = await blobFileHandle.getFile();
658
695
  let metadata = {};
659
696
  try {
@@ -676,15 +713,9 @@ async function deleteBlob(key) {
676
713
  if (!blobsHandle || !metadataHandle) {
677
714
  throw new Error("Storage not initialized");
678
715
  }
679
- const encodedKey = encodeKey(key);
680
- try {
681
- await blobsHandle.removeEntry(encodedKey);
682
- } catch {
683
- }
684
- try {
685
- await metadataHandle.removeEntry(`${encodedKey}.json`);
686
- } catch {
687
- }
716
+ await removeFiles(encodeKey(key));
717
+ const legacy = legacyOpfsFilename(key);
718
+ if (legacy) await removeFiles(legacy);
688
719
  }
689
720
  async function listBlobs(prefix) {
690
721
  if (!blobsHandle) {
@@ -694,7 +725,7 @@ async function listBlobs(prefix) {
694
725
  for await (const entry of blobsHandle.values()) {
695
726
  if (entry.kind === "file") {
696
727
  const key = decodeKey(entry.name);
697
- if (!prefix || key.startsWith(prefix)) {
728
+ if ((!prefix || key.startsWith(prefix)) && !keys.includes(key)) {
698
729
  keys.push(key);
699
730
  }
700
731
  }
@@ -832,12 +863,28 @@ let rootHandle = null;
832
863
  let blobsHandle = null;
833
864
  let metadataHandle = null;
834
865
 
866
+ // Keep in sync with storage/opfs-keys.ts
835
867
  function encodeKey(key) {
836
- return encodeURIComponent(key).replace(/%/g, '_');
868
+ return encodeURIComponent(key).replace(/_/g, '%5F').replace(/%/g, '_');
837
869
  }
838
870
 
839
871
  function decodeKey(filename) {
840
- return decodeURIComponent(filename.replace(/_/g, '%'));
872
+ try {
873
+ return decodeURIComponent(filename.replace(/_/g, '%'));
874
+ } catch {
875
+ return filename;
876
+ }
877
+ }
878
+
879
+ function legacyFilename(key) {
880
+ const legacy = encodeURIComponent(key).replace(/%/g, '_');
881
+ if (legacy === encodeKey(key)) return null;
882
+ return decodeKey(legacy) === key ? legacy : null;
883
+ }
884
+
885
+ async function removeFiles(name) {
886
+ try { await blobsHandle.removeEntry(name); } catch {}
887
+ try { await metadataHandle.removeEntry(name + '.json'); } catch {}
841
888
  }
842
889
 
843
890
  async function initDirectories() {
@@ -864,13 +911,23 @@ async function storeBlob(key, blob, metadata) {
864
911
  const metaWritable = await metaFileHandle.createWritable();
865
912
  await metaWritable.write(JSON.stringify(fullMetadata));
866
913
  await metaWritable.close();
914
+ const legacy = legacyFilename(key);
915
+ if (legacy) await removeFiles(legacy);
867
916
  }
868
917
 
869
918
  async function getBlob(key) {
870
919
  if (!blobsHandle || !metadataHandle) throw new Error('Storage not initialized');
871
- const encodedKey = encodeKey(key);
920
+ let encodedKey = encodeKey(key);
872
921
  try {
873
- const blobFileHandle = await blobsHandle.getFileHandle(encodedKey);
922
+ let blobFileHandle;
923
+ try {
924
+ blobFileHandle = await blobsHandle.getFileHandle(encodedKey);
925
+ } catch (error) {
926
+ const legacy = legacyFilename(key);
927
+ if (!legacy) throw error;
928
+ blobFileHandle = await blobsHandle.getFileHandle(legacy);
929
+ encodedKey = legacy;
930
+ }
874
931
  const blobFile = await blobFileHandle.getFile();
875
932
  let metadata = {};
876
933
  try {
@@ -891,9 +948,9 @@ async function getBlob(key) {
891
948
 
892
949
  async function deleteBlob(key) {
893
950
  if (!blobsHandle || !metadataHandle) throw new Error('Storage not initialized');
894
- const encodedKey = encodeKey(key);
895
- try { await blobsHandle.removeEntry(encodedKey); } catch {}
896
- try { await metadataHandle.removeEntry(encodedKey + '.json'); } catch {}
951
+ await removeFiles(encodeKey(key));
952
+ const legacy = legacyFilename(key);
953
+ if (legacy) await removeFiles(legacy);
897
954
  }
898
955
 
899
956
  async function listBlobs(prefix) {
@@ -902,7 +959,7 @@ async function listBlobs(prefix) {
902
959
  for await (const entry of blobsHandle.values()) {
903
960
  if (entry.kind === 'file') {
904
961
  const key = decodeKey(entry.name);
905
- if (!prefix || key.startsWith(prefix)) keys.push(key);
962
+ if ((!prefix || key.startsWith(prefix)) && !keys.includes(key)) keys.push(key);
906
963
  }
907
964
  }
908
965
  return keys;
@@ -1059,13 +1116,26 @@ var OPFSAdapter = class {
1059
1116
  * Encode key to safe filename
1060
1117
  */
1061
1118
  encodeKey(key) {
1062
- return encodeURIComponent(key).replace(/%/g, "_");
1119
+ return encodeOpfsKey(key);
1063
1120
  }
1064
1121
  /**
1065
1122
  * Decode filename back to key
1066
1123
  */
1067
1124
  decodeKey(filename) {
1068
- return decodeURIComponent(filename.replace(/_/g, "%"));
1125
+ return decodeOpfsKey(filename);
1126
+ }
1127
+ /**
1128
+ * Remove a blob file and its metadata file, ignoring missing ones
1129
+ */
1130
+ async removeFiles(name) {
1131
+ try {
1132
+ await this.blobsHandle.removeEntry(name);
1133
+ } catch {
1134
+ }
1135
+ try {
1136
+ await this.metadataHandle.removeEntry(`${name}.json`);
1137
+ } catch {
1138
+ }
1069
1139
  }
1070
1140
  // ===== Binary Storage =====
1071
1141
  async storeBlob(key, blob, metadata) {
@@ -1102,6 +1172,8 @@ var OPFSAdapter = class {
1102
1172
  const metaWritable = await metaFileHandle.createWritable();
1103
1173
  await metaWritable.write(JSON.stringify(fullMetadata));
1104
1174
  await metaWritable.close();
1175
+ const legacy = legacyOpfsFilename(key);
1176
+ if (legacy) await this.removeFiles(legacy);
1105
1177
  } catch (error) {
1106
1178
  throw OfflineStorageError.opfsError("Failed to store blob", error);
1107
1179
  }
@@ -1122,9 +1194,17 @@ var OPFSAdapter = class {
1122
1194
  if (!this.blobsHandle || !this.metadataHandle) {
1123
1195
  throw OfflineStorageError.notInitialized();
1124
1196
  }
1125
- const encodedKey = this.encodeKey(key);
1197
+ let encodedKey = this.encodeKey(key);
1126
1198
  try {
1127
- const blobFileHandle = await this.blobsHandle.getFileHandle(encodedKey);
1199
+ let blobFileHandle;
1200
+ try {
1201
+ blobFileHandle = await this.blobsHandle.getFileHandle(encodedKey);
1202
+ } catch (error) {
1203
+ const legacy = legacyOpfsFilename(key);
1204
+ if (!legacy) throw error;
1205
+ blobFileHandle = await this.blobsHandle.getFileHandle(legacy);
1206
+ encodedKey = legacy;
1207
+ }
1128
1208
  const blobFile = await blobFileHandle.getFile();
1129
1209
  let metadata = {};
1130
1210
  try {
@@ -1156,15 +1236,9 @@ var OPFSAdapter = class {
1156
1236
  if (!this.blobsHandle || !this.metadataHandle) {
1157
1237
  throw OfflineStorageError.notInitialized();
1158
1238
  }
1159
- const encodedKey = this.encodeKey(key);
1160
- try {
1161
- await this.blobsHandle.removeEntry(encodedKey);
1162
- } catch {
1163
- }
1164
- try {
1165
- await this.metadataHandle.removeEntry(`${encodedKey}.json`);
1166
- } catch {
1167
- }
1239
+ await this.removeFiles(this.encodeKey(key));
1240
+ const legacy = legacyOpfsFilename(key);
1241
+ if (legacy) await this.removeFiles(legacy);
1168
1242
  }
1169
1243
  async listBlobs(prefix) {
1170
1244
  if (this.useWorker) {
@@ -1186,7 +1260,7 @@ var OPFSAdapter = class {
1186
1260
  for await (const entry of this.blobsHandle.values()) {
1187
1261
  if (entry.kind === "file") {
1188
1262
  const key = this.decodeKey(entry.name);
1189
- if (!prefix || key.startsWith(prefix)) {
1263
+ if ((!prefix || key.startsWith(prefix)) && !keys.includes(key)) {
1190
1264
  keys.push(key);
1191
1265
  }
1192
1266
  }
@@ -1,4 +1,8 @@
1
- import { DEFAULT_EXPIRATIONS } from './chunk-ZC7F2HDV.js';
1
+ import { createAdapter, OfflineStorageError, detectAvailableAdapters } from './chunk-J2ZYJDJX.js';
2
+ import { createFileStorageService } from './chunk-U27TKOYZ.js';
3
+ import { createDraftStorageService } from './chunk-EWMN3Y7N.js';
4
+ import { createDraftManagerService } from './chunk-WWKATW37.js';
5
+ import { DEFAULT_EXPIRATIONS, CleanupScheduler } from './chunk-ZC7F2HDV.js';
2
6
 
3
7
  // src/cache/types.ts
4
8
  var CACHE_PREFIX = "cache:";
@@ -65,6 +69,7 @@ var CacheService = class {
65
69
  const isExpired = cached.expiresAt !== null && now > cached.expiresAt;
66
70
  if (isExpired) {
67
71
  this.stats.staleHits++;
72
+ this.accessOrder.set(key, now);
68
73
  return {
69
74
  value: cached.data,
70
75
  hit: true,
@@ -94,7 +99,7 @@ var CacheService = class {
94
99
  expiresAt: ttl > 0 ? now + ttl : null,
95
100
  tags: options.tags
96
101
  };
97
- await this.enforceLimit();
102
+ await this.enforceLimit(key);
98
103
  await this.adapter.storeJSON(storageKey, entry, {
99
104
  tags: options.tags ? [...options.tags, "cache"] : ["cache"]
100
105
  });
@@ -102,10 +107,12 @@ var CacheService = class {
102
107
  }
103
108
  /**
104
109
  * Enforce cache size limits using LRU eviction
110
+ * @param newKey - Key being added (skip count check if it already exists)
105
111
  */
106
- async enforceLimit() {
112
+ async enforceLimit(newKey) {
107
113
  const keys = await this.keys();
108
- if (keys.length >= this.maxEntries) {
114
+ const isNewEntry = newKey ? !keys.includes(newKey) : true;
115
+ if (isNewEntry && keys.length >= this.maxEntries) {
109
116
  const evictCount = Math.max(1, Math.floor(this.maxEntries * 0.1));
110
117
  await this.evictLRU(keys, evictCount);
111
118
  }
@@ -155,8 +162,8 @@ var CacheService = class {
155
162
  const entry = result.data;
156
163
  const staleThreshold = staleTime ?? ttl;
157
164
  const now = Date.now();
158
- const age = entry.expiresAt !== null ? now - entry.expiresAt : 0;
159
- if (age < staleThreshold) {
165
+ const age = now - entry.createdAt;
166
+ if (age < (entry.expiresAt !== null ? entry.expiresAt - entry.createdAt : 0) + staleThreshold) {
160
167
  void this.revalidateInBackground(key, fetcher, { ttl, tags });
161
168
  return cached.value;
162
169
  }
@@ -211,6 +218,7 @@ var CacheService = class {
211
218
  * Invalidate a cached value
212
219
  */
213
220
  async invalidate(key) {
221
+ this.cleanupStaleInFlight();
214
222
  const storageKey = getCacheKey(key);
215
223
  await this.adapter.deleteJSON(storageKey);
216
224
  this.accessOrder.delete(key);
@@ -219,12 +227,14 @@ var CacheService = class {
219
227
  * Invalidate all entries with a specific tag
220
228
  */
221
229
  async invalidateByTag(tag) {
230
+ this.cleanupStaleInFlight();
222
231
  return this.adapter.deleteJSONByTag(tag);
223
232
  }
224
233
  /**
225
234
  * Invalidate all cached values
226
235
  */
227
236
  async invalidateAll() {
237
+ this.cleanupStaleInFlight();
228
238
  const count = await this.adapter.deleteJSONByTag("cache");
229
239
  this.accessOrder.clear();
230
240
  return count;
@@ -293,4 +303,109 @@ function createCacheService(adapter) {
293
303
  return new CacheService(adapter);
294
304
  }
295
305
 
296
- export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey };
306
+ // src/init.ts
307
+ var instance = null;
308
+ var initPromise = null;
309
+ var DEFAULT_OPTIONS = {
310
+ preferredAdapters: ["opfs", "indexeddb", "memory"],
311
+ dbName: "classic-offline",
312
+ autoCleanup: true,
313
+ cleanupIntervalMs: 6e4
314
+ // 1 minute
315
+ };
316
+ async function initOfflineStorage(options) {
317
+ if (instance) {
318
+ return instance;
319
+ }
320
+ if (initPromise) {
321
+ return initPromise;
322
+ }
323
+ initPromise = doInitialize(options);
324
+ try {
325
+ instance = await initPromise;
326
+ return instance;
327
+ } finally {
328
+ initPromise = null;
329
+ }
330
+ }
331
+ async function doInitialize(options) {
332
+ const mergedOptions = { ...DEFAULT_OPTIONS, ...options };
333
+ const { adapter, adapterName } = await createAdapter({
334
+ preferredAdapters: mergedOptions.preferredAdapters,
335
+ dbName: mergedOptions.dbName
336
+ });
337
+ await adapter.initialize();
338
+ const files = createFileStorageService(adapter);
339
+ const drafts = createDraftStorageService(adapter);
340
+ const draftManager = createDraftManagerService(adapter);
341
+ const cache = createCacheService(adapter);
342
+ const cleanup = new CleanupScheduler(mergedOptions.cleanupIntervalMs);
343
+ cleanup.registerAdapter(adapter);
344
+ if (mergedOptions.autoCleanup && mergedOptions.cleanupIntervalMs > 0) {
345
+ cleanup.start();
346
+ }
347
+ const config = {
348
+ adapterName,
349
+ dbName: mergedOptions.dbName,
350
+ autoCleanup: mergedOptions.autoCleanup,
351
+ cleanupIntervalMs: mergedOptions.cleanupIntervalMs
352
+ };
353
+ return {
354
+ adapter,
355
+ config,
356
+ files,
357
+ drafts,
358
+ draftManager,
359
+ cache,
360
+ cleanup,
361
+ async dispose() {
362
+ cleanup.stop();
363
+ await adapter.dispose();
364
+ instance = null;
365
+ }
366
+ };
367
+ }
368
+ function getOfflineStorage() {
369
+ if (!instance) {
370
+ throw OfflineStorageError.notInitialized();
371
+ }
372
+ return instance;
373
+ }
374
+ function isOfflineStorageInitialized() {
375
+ return instance !== null;
376
+ }
377
+ function getOfflineStorageOrNull() {
378
+ return instance;
379
+ }
380
+ async function resetOfflineStorage() {
381
+ if (instance) {
382
+ await instance.dispose();
383
+ instance = null;
384
+ }
385
+ initPromise = null;
386
+ }
387
+ async function detectStorageAdapter(preferredAdapters) {
388
+ const { adapterName } = await createAdapter({
389
+ preferredAdapters
390
+ });
391
+ const { available, unavailable } = await detectAvailableAdapters();
392
+ return { adapterName, available, unavailable };
393
+ }
394
+
395
+ // src/cache/helpers.ts
396
+ async function invalidateCacheByTag(tag) {
397
+ const storage = getOfflineStorageOrNull();
398
+ if (!storage) {
399
+ return 0;
400
+ }
401
+ return storage.cache.invalidateByTag(tag);
402
+ }
403
+ async function invalidateAllCache() {
404
+ const storage = getOfflineStorageOrNull();
405
+ if (!storage) {
406
+ return 0;
407
+ }
408
+ return storage.cache.invalidateAll();
409
+ }
410
+
411
+ export { CACHE_PREFIX, CacheService, createCacheService, detectStorageAdapter, getCacheKey, getOfflineStorage, getOfflineStorageOrNull, getOriginalKey, initOfflineStorage, invalidateAllCache, invalidateCacheByTag, isOfflineStorageInitialized, resetOfflineStorage };
@@ -21,7 +21,7 @@ function parseDraftV2Key(key) {
21
21
  return null;
22
22
  }
23
23
  const rest = key.slice(DRAFT_V2_PREFIX.length);
24
- const colonIndex = rest.indexOf(":");
24
+ const colonIndex = rest.lastIndexOf(":");
25
25
  if (colonIndex === -1) {
26
26
  return null;
27
27
  }
@@ -40,17 +40,23 @@ function generateDraftId() {
40
40
  return v.toString(16);
41
41
  });
42
42
  }
43
+ var sessionDeviceId;
43
44
  function getOrCreateDeviceId() {
44
45
  const DEVICE_ID_KEY = "classic-offline-device-id";
45
- if (typeof localStorage === "undefined") {
46
- return generateDraftId();
47
- }
48
- let deviceId = localStorage.getItem(DEVICE_ID_KEY);
49
- if (!deviceId) {
50
- deviceId = generateDraftId();
51
- localStorage.setItem(DEVICE_ID_KEY, deviceId);
46
+ try {
47
+ if (typeof localStorage === "undefined") {
48
+ return generateDraftId();
49
+ }
50
+ let deviceId = localStorage.getItem(DEVICE_ID_KEY);
51
+ if (!deviceId) {
52
+ deviceId = generateDraftId();
53
+ localStorage.setItem(DEVICE_ID_KEY, deviceId);
54
+ }
55
+ return deviceId;
56
+ } catch {
57
+ sessionDeviceId ?? (sessionDeviceId = generateDraftId());
58
+ return sessionDeviceId;
52
59
  }
53
- return deviceId;
54
60
  }
55
61
  function isLegacyDraftKey(key) {
56
62
  return key.startsWith(DRAFT_PREFIX) && !key.startsWith(DRAFT_V2_PREFIX);
@@ -1,6 +1,6 @@
1
- import { a as SaveDraftOptions, L as LoadDraftOptions, b as LoadDraftResult, C as CreateDraftOptions, d as DraftMetadata, e as StoredDraftV2, f as ListDraftsOptions, c as DraftSyncStatus } from '../types-B2FJpQuN.js';
2
- export { j as CURRENT_DRAFT_PREFIX, D as DRAFT_PREFIX, g as DRAFT_V2_PREFIX, S as StoredDraft, h as generateDraftId, n as getCurrentDraftKey, k as getDraftKey, m as getDraftV2Key, l as getFormKeyFromDraftKey, i as getOrCreateDeviceId, q as isDraftV2Key, o as isLegacyDraftKey, p as parseDraftV2Key } from '../types-B2FJpQuN.js';
3
- import { S as StorageAdapter } from '../types-CWuauHAr.js';
1
+ import { S as SaveDraftOptions, d as LoadDraftOptions, e as LoadDraftResult, C as CreateDraftOptions, b as DraftMetadata, g as StoredDraftV2, L as ListDraftsOptions, c as DraftSyncStatus } from '../types-Ho1JiLQR.js';
2
+ export { j as CURRENT_DRAFT_PREFIX, D as DRAFT_PREFIX, a as DRAFT_V2_PREFIX, f as StoredDraft, h as generateDraftId, k as getCurrentDraftKey, l as getDraftKey, m as getDraftV2Key, n as getFormKeyFromDraftKey, i as getOrCreateDeviceId, o as isDraftV2Key, p as isLegacyDraftKey, q as parseDraftV2Key } from '../types-Ho1JiLQR.js';
3
+ import { S as StorageAdapter } from '../types-DDhQm0hc.js';
4
4
 
5
5
  /**
6
6
  * Form draft persistence service
@@ -1,3 +1,3 @@
1
- export { DraftStorageService, createDraftStorageService } from '../chunk-IIG4QLLN.js';
2
- export { CURRENT_DRAFT_PREFIX, DRAFT_PREFIX, DRAFT_V2_PREFIX, DraftManagerService, createDraftManagerService, generateDraftId, getCurrentDraftKey, getDraftKey, getDraftV2Key, getFormKeyFromDraftKey, getOrCreateDeviceId, isDraftV2Key, isLegacyDraftKey, parseDraftV2Key } from '../chunk-4QWZX3LM.js';
1
+ export { DraftStorageService, createDraftStorageService } from '../chunk-EWMN3Y7N.js';
2
+ export { CURRENT_DRAFT_PREFIX, DRAFT_PREFIX, DRAFT_V2_PREFIX, DraftManagerService, createDraftManagerService, generateDraftId, getCurrentDraftKey, getDraftKey, getDraftV2Key, getFormKeyFromDraftKey, getOrCreateDeviceId, isDraftV2Key, isLegacyDraftKey, parseDraftV2Key } from '../chunk-WWKATW37.js';
3
3
  import '../chunk-ZC7F2HDV.js';
@@ -1,4 +1,4 @@
1
- import { B as BlobMetadata, S as StorageAdapter } from '../types-CWuauHAr.js';
1
+ import { B as BlobMetadata, S as StorageAdapter } from '../types-DDhQm0hc.js';
2
2
 
3
3
  /**
4
4
  * Types for file storage service
package/dist/index.d.ts CHANGED
@@ -1,13 +1,13 @@
1
- import { S as StorageAdapter, O as OfflineStorageConfig, a as OfflineStorageOptions, b as StorageAdapterName } from './types-CWuauHAr.js';
2
- export { B as BlobMetadata, d as BlobWithMetadata, C as CleanupResult, J as JSONEntry, f as StorageAdapterOptions, c as StorageQuota, e as StoreJSONOptions } from './types-CWuauHAr.js';
1
+ import { S as StorageAdapter, O as OfflineStorageConfig, a as StorageAdapterName, b as OfflineStorageOptions } from './types-DDhQm0hc.js';
2
+ export { B as BlobMetadata, c as BlobWithMetadata, C as CleanupResult, J as JSONEntry, d as StorageAdapterOptions, e as StorageQuota, f as StoreJSONOptions } from './types-DDhQm0hc.js';
3
3
  import { FileStorageService } from './files/index.js';
4
4
  export { DeleteFilesResult, FileConstraints, FileValidationError, GetFilesOptions, PersistedFile, StoreFileOptions, StoredFile, createFileStorageService } from './files/index.js';
5
5
  import { DraftStorageService, DraftManagerService } from './drafts/index.js';
6
6
  export { createDraftManagerService, createDraftStorageService } from './drafts/index.js';
7
7
  import { CacheService } from './cache/index.js';
8
- export { CACHE_PREFIX, CacheEntry, CacheGetResult, CacheOptions, CacheStats, GetOrSetOptions, createCacheService } from './cache/index.js';
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
- export { C as CreateDraftOptions, D as DRAFT_PREFIX, g as DRAFT_V2_PREFIX, d as DraftMetadata, c as DraftSyncStatus, f as ListDraftsOptions, L as LoadDraftOptions, b as LoadDraftResult, a as SaveDraftOptions, S as StoredDraft, e as StoredDraftV2, h as generateDraftId, i as getOrCreateDeviceId } from './types-B2FJpQuN.js';
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-Ho1JiLQR.js';
11
11
  export { ConflictResolution, ConnectivityMonitor, ConnectivityState, DraftConflict, DraftPayload, PendingSyncOperation, RemoteDraft, SyncAdapter, SyncConfig, SyncEvent, SyncEventListener, SyncEventType, SyncQueue, SyncQueueState, SyncRequest, SyncResponse, SyncResult, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './sync/index.js';
12
12
 
13
13
  /**
package/dist/index.js CHANGED
@@ -1,107 +1,7 @@
1
- import { createAdapter, OfflineStorageError } from './chunk-IDRYBB6Z.js';
2
- export { OfflineStorageError, createAdapter, detectAvailableAdapters, detectBrowser, isBrowser, isSSR, isWorker, supportsIndexedDB, supportsLocalStorage, supportsOPFS } from './chunk-IDRYBB6Z.js';
3
- import { createFileStorageService } from './chunk-U27TKOYZ.js';
1
+ export { CACHE_PREFIX, CacheService, createCacheService, detectStorageAdapter, getOfflineStorage, getOfflineStorageOrNull, initOfflineStorage, invalidateAllCache, invalidateCacheByTag, isOfflineStorageInitialized, resetOfflineStorage } from './chunk-PEQVHD6Q.js';
2
+ export { OfflineStorageError, createAdapter, detectAvailableAdapters, detectBrowser, isBrowser, isSSR, isWorker, supportsIndexedDB, supportsLocalStorage, supportsOPFS } from './chunk-J2ZYJDJX.js';
4
3
  export { FileStorageService, createFileStorageService } from './chunk-U27TKOYZ.js';
5
- import { createDraftStorageService } from './chunk-IIG4QLLN.js';
6
- export { DraftStorageService, createDraftStorageService } from './chunk-IIG4QLLN.js';
7
- import { createCacheService } from './chunk-K7USXDTP.js';
8
- export { CACHE_PREFIX, CacheService, createCacheService } from './chunk-K7USXDTP.js';
9
- export { ConnectivityMonitor, SyncQueue, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './chunk-XHMX3BYT.js';
10
- import { createDraftManagerService } from './chunk-4QWZX3LM.js';
11
- export { DRAFT_PREFIX, DRAFT_V2_PREFIX, DraftManagerService, createDraftManagerService, generateDraftId, getOrCreateDeviceId } from './chunk-4QWZX3LM.js';
12
- import { CleanupScheduler } from './chunk-ZC7F2HDV.js';
4
+ export { DraftStorageService, createDraftStorageService } from './chunk-EWMN3Y7N.js';
5
+ export { ConnectivityMonitor, SyncQueue, SyncService, applyResolution, compareDrafts, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict } from './chunk-DIXYWY34.js';
6
+ export { DRAFT_PREFIX, DRAFT_V2_PREFIX, DraftManagerService, createDraftManagerService, generateDraftId, getOrCreateDeviceId } from './chunk-WWKATW37.js';
13
7
  export { CleanupScheduler, DEFAULT_EXPIRATIONS, calculateExpiration, isExpired } from './chunk-ZC7F2HDV.js';
14
-
15
- // src/init.ts
16
- var instance = null;
17
- var initPromise = null;
18
- var DEFAULT_OPTIONS = {
19
- preferredAdapters: ["opfs", "indexeddb", "memory"],
20
- dbName: "classic-offline",
21
- autoCleanup: true,
22
- cleanupIntervalMs: 6e4
23
- // 1 minute
24
- };
25
- async function initOfflineStorage(options) {
26
- if (instance) {
27
- return instance;
28
- }
29
- if (initPromise) {
30
- return initPromise;
31
- }
32
- initPromise = doInitialize(options);
33
- try {
34
- instance = await initPromise;
35
- return instance;
36
- } finally {
37
- initPromise = null;
38
- }
39
- }
40
- async function doInitialize(options) {
41
- const mergedOptions = { ...DEFAULT_OPTIONS, ...options };
42
- const { adapter, adapterName } = await createAdapter({
43
- preferredAdapters: mergedOptions.preferredAdapters,
44
- dbName: mergedOptions.dbName
45
- });
46
- await adapter.initialize();
47
- const files = createFileStorageService(adapter);
48
- const drafts = createDraftStorageService(adapter);
49
- const draftManager = createDraftManagerService(adapter);
50
- const cache = createCacheService(adapter);
51
- const cleanup = new CleanupScheduler(mergedOptions.cleanupIntervalMs);
52
- cleanup.registerAdapter(adapter);
53
- if (mergedOptions.autoCleanup && mergedOptions.cleanupIntervalMs > 0) {
54
- cleanup.start();
55
- }
56
- const config = {
57
- adapterName,
58
- dbName: mergedOptions.dbName,
59
- autoCleanup: mergedOptions.autoCleanup,
60
- cleanupIntervalMs: mergedOptions.cleanupIntervalMs
61
- };
62
- return {
63
- adapter,
64
- config,
65
- files,
66
- drafts,
67
- draftManager,
68
- cache,
69
- cleanup,
70
- async dispose() {
71
- cleanup.stop();
72
- await adapter.dispose();
73
- instance = null;
74
- }
75
- };
76
- }
77
- function getOfflineStorage() {
78
- if (!instance) {
79
- throw OfflineStorageError.notInitialized();
80
- }
81
- return instance;
82
- }
83
- function isOfflineStorageInitialized() {
84
- return instance !== null;
85
- }
86
- function getOfflineStorageOrNull() {
87
- return instance;
88
- }
89
- async function resetOfflineStorage() {
90
- if (instance) {
91
- await instance.dispose();
92
- instance = null;
93
- }
94
- initPromise = null;
95
- }
96
- async function detectStorageAdapter(preferredAdapters) {
97
- const { adapterName, unavailable } = await createAdapter({
98
- preferredAdapters
99
- });
100
- const available = [];
101
- if (!unavailable.includes("opfs")) available.push("opfs");
102
- if (!unavailable.includes("indexeddb")) available.push("indexeddb");
103
- available.push("memory");
104
- return { adapterName, available, unavailable };
105
- }
106
-
107
- export { detectStorageAdapter, getOfflineStorage, getOfflineStorageOrNull, initOfflineStorage, isOfflineStorageInitialized, resetOfflineStorage };
@@ -1,4 +1,4 @@
1
- import { S as StorageAdapter, f as StorageAdapterOptions, B as BlobMetadata, d as BlobWithMetadata, e as StoreJSONOptions, J as JSONEntry, C as CleanupResult, c as StorageQuota, b as StorageAdapterName } from '../types-CWuauHAr.js';
1
+ import { S as StorageAdapter, d as StorageAdapterOptions, B as BlobMetadata, c as BlobWithMetadata, f as StoreJSONOptions, J as JSONEntry, C as CleanupResult, e as StorageQuota, a as StorageAdapterName } from '../types-DDhQm0hc.js';
2
2
 
3
3
  /**
4
4
  * Memory storage adapter
@@ -124,6 +124,10 @@ declare class OPFSAdapter implements StorageAdapter {
124
124
  * Decode filename back to key
125
125
  */
126
126
  private decodeKey;
127
+ /**
128
+ * Remove a blob file and its metadata file, ignoring missing ones
129
+ */
130
+ private removeFiles;
127
131
  storeBlob(key: string, blob: Blob, metadata?: BlobMetadata): Promise<void>;
128
132
  getBlob(key: string): Promise<BlobWithMetadata | null>;
129
133
  deleteBlob(key: string): Promise<void>;
@@ -1,2 +1,2 @@
1
- export { IndexedDBAdapter, MemoryAdapter, OPFSAdapter, createAdapter, createIndexedDBAdapter, createMemoryAdapter, createOPFSAdapter, detectAvailableAdapters } from '../chunk-IDRYBB6Z.js';
1
+ export { IndexedDBAdapter, MemoryAdapter, OPFSAdapter, createAdapter, createIndexedDBAdapter, createMemoryAdapter, createOPFSAdapter, detectAvailableAdapters } from '../chunk-J2ZYJDJX.js';
2
2
  import '../chunk-ZC7F2HDV.js';
@@ -1,5 +1,5 @@
1
- import { e as StoredDraftV2 } from '../types-B2FJpQuN.js';
2
- import { S as StorageAdapter } from '../types-CWuauHAr.js';
1
+ import { g as StoredDraftV2 } from '../types-Ho1JiLQR.js';
2
+ import { S as StorageAdapter } from '../types-DDhQm0hc.js';
3
3
 
4
4
  /**
5
5
  * Types for cloud sync functionality
@@ -1,3 +1,3 @@
1
- export { ConnectivityMonitor, SyncConflictError, SyncQueue, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge } from '../chunk-XHMX3BYT.js';
2
- import '../chunk-4QWZX3LM.js';
1
+ export { ConnectivityMonitor, SyncConflictError, SyncQueue, SyncService, applyResolution, compareDrafts, createConflict, createConnectivityMonitor, createSyncQueue, createSyncService, detectConflict, isSyncConflictError, resolveKeepLocal, resolveKeepRemote, resolveMerge } from '../chunk-DIXYWY34.js';
2
+ import '../chunk-WWKATW37.js';
3
3
  import '../chunk-ZC7F2HDV.js';
@@ -201,4 +201,4 @@ interface StorageAdapterOptions {
201
201
  dbName?: string;
202
202
  }
203
203
 
204
- export type { BlobMetadata as B, CleanupResult as C, JSONEntry as J, OfflineStorageConfig as O, StorageAdapter as S, OfflineStorageOptions as a, StorageAdapterName as b, StorageQuota as c, BlobWithMetadata as d, StoreJSONOptions as e, StorageAdapterOptions as f };
204
+ export type { BlobMetadata as B, CleanupResult as C, JSONEntry as J, OfflineStorageConfig as O, StorageAdapter as S, StorageAdapterName as a, OfflineStorageOptions as b, BlobWithMetadata as c, StorageAdapterOptions as d, StorageQuota as e, StoreJSONOptions as f };
@@ -176,4 +176,4 @@ declare function isLegacyDraftKey(key: string): boolean;
176
176
  */
177
177
  declare function isDraftV2Key(key: string): boolean;
178
178
 
179
- export { type CreateDraftOptions as C, DRAFT_PREFIX as D, type LoadDraftOptions as L, type StoredDraft as S, type SaveDraftOptions as a, type LoadDraftResult as b, type DraftSyncStatus as c, type DraftMetadata as d, type StoredDraftV2 as e, type ListDraftsOptions as f, DRAFT_V2_PREFIX as g, generateDraftId as h, getOrCreateDeviceId as i, CURRENT_DRAFT_PREFIX as j, getDraftKey as k, getFormKeyFromDraftKey as l, getDraftV2Key as m, getCurrentDraftKey as n, isLegacyDraftKey as o, parseDraftV2Key as p, isDraftV2Key as q };
179
+ export { type CreateDraftOptions as C, DRAFT_PREFIX as D, type ListDraftsOptions as L, type SaveDraftOptions as S, DRAFT_V2_PREFIX as a, type DraftMetadata as b, type DraftSyncStatus as c, type LoadDraftOptions as d, type LoadDraftResult as e, type StoredDraft as f, type StoredDraftV2 as g, generateDraftId as h, getOrCreateDeviceId as i, CURRENT_DRAFT_PREFIX as j, getCurrentDraftKey as k, getDraftKey as l, getDraftV2Key as m, getFormKeyFromDraftKey as n, isDraftV2Key as o, isLegacyDraftKey as p, parseDraftV2Key as q };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/offline-core",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Framework-agnostic offline persistence and caching for Classic Theme",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -39,7 +39,7 @@
39
39
  "scripts": {
40
40
  "build": "tsup",
41
41
  "dev": "tsup --watch",
42
- "clean": "rm -rf dist",
42
+ "clean": "node ../../scripts/rm.mjs dist",
43
43
  "typecheck": "tsc --noEmit",
44
44
  "test": "vitest run",
45
45
  "test:watch": "vitest",
@@ -67,11 +67,11 @@
67
67
  "idb": "^8.0.0"
68
68
  },
69
69
  "devDependencies": {
70
- "@vitest/coverage-v8": "^2.0.0",
70
+ "@vitest/coverage-v8": "^4.1.10",
71
71
  "fake-indexeddb": "^6.0.0",
72
72
  "jsdom": "^25.0.0",
73
73
  "tsup": "^8.0.0",
74
74
  "typescript": "^5.3.0",
75
- "vitest": "^2.0.0"
75
+ "vitest": "^4.1.10"
76
76
  }
77
77
  }