@classic-homes/offline-core 0.1.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/README.md ADDED
@@ -0,0 +1,272 @@
1
+ # @classic-homes/offline-core
2
+
3
+ Framework-agnostic offline persistence and caching for Classic Theme applications. Provides file storage, form draft persistence, and data caching with automatic browser storage selection.
4
+
5
+ ## Features
6
+
7
+ - **Three-tier storage fallback**: OPFS → IndexedDB → Memory
8
+ - **File storage**: Store, retrieve, and manage file attachments
9
+ - **Draft persistence**: Save and restore form data with file references
10
+ - **Data caching**: TTL-based caching with stale-while-revalidate support
11
+ - **Automatic cleanup**: Expired entries are cleaned up automatically
12
+ - **Type-safe**: Full TypeScript support throughout
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @classic-homes/offline-core
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```typescript
23
+ import { initOfflineStorage, getOfflineStorage } from '@classic-homes/offline-core';
24
+
25
+ // Initialize at app startup
26
+ await initOfflineStorage();
27
+
28
+ // Get the storage instance
29
+ const storage = getOfflineStorage();
30
+
31
+ // Store a file
32
+ const file = new File(['content'], 'document.pdf');
33
+ const stored = await storage.files.storeFile(file, {
34
+ formKey: 'contact-form',
35
+ fieldName: 'attachments',
36
+ });
37
+
38
+ // Save a form draft
39
+ await storage.drafts.saveDraft('contact-form', {
40
+ name: 'John Doe',
41
+ email: 'john@example.com',
42
+ });
43
+
44
+ // Cache data
45
+ await storage.cache.set('user:123', { name: 'John' }, { ttl: 60000 });
46
+ ```
47
+
48
+ ## API Reference
49
+
50
+ ### Initialization
51
+
52
+ #### `initOfflineStorage(options?)`
53
+
54
+ Initialize the offline storage system. Call once at application startup.
55
+
56
+ ```typescript
57
+ const storage = await initOfflineStorage({
58
+ preferredAdapters: ['opfs', 'indexeddb', 'memory'], // Fallback order
59
+ dbName: 'my-app-offline', // IndexedDB database name
60
+ autoCleanup: true, // Run cleanup on init
61
+ cleanupIntervalMs: 60000, // Cleanup interval (0 to disable)
62
+ });
63
+ ```
64
+
65
+ #### `getOfflineStorage()`
66
+
67
+ Get the initialized storage instance. Throws if not initialized.
68
+
69
+ #### `isOfflineStorageInitialized()`
70
+
71
+ Check if storage has been initialized.
72
+
73
+ ### File Storage
74
+
75
+ ```typescript
76
+ const files = storage.files;
77
+
78
+ // Validate files before storing
79
+ const errors = files.validateFiles(fileList, {
80
+ maxSizeBytes: 10 * 1024 * 1024, // 10MB
81
+ maxFiles: 5,
82
+ acceptedTypes: ['image/*', 'application/pdf'],
83
+ });
84
+
85
+ // Store a file
86
+ const stored = await files.storeFile(file, {
87
+ formKey: 'form-id',
88
+ fieldName: 'attachment',
89
+ expirationMs: 7 * 24 * 60 * 60 * 1000, // 7 days
90
+ });
91
+
92
+ // Get a file with preview URL
93
+ const persisted = await files.getFile(stored.id, true);
94
+ // persisted.previewUrl for images
95
+
96
+ // Get files for a form
97
+ const formFiles = await files.getFiles({
98
+ formKey: 'form-id',
99
+ fieldName: 'attachment',
100
+ generatePreviews: true,
101
+ });
102
+
103
+ // Delete files
104
+ await files.deleteFile(fileId);
105
+ await files.deleteFormFiles('form-id');
106
+
107
+ // Convert to File objects for form submission
108
+ const fileMap = await files.getFilesAsFileObjects([id1, id2]);
109
+ ```
110
+
111
+ ### Draft Storage
112
+
113
+ ```typescript
114
+ const drafts = storage.drafts;
115
+
116
+ // Save a draft
117
+ await drafts.saveDraft(
118
+ 'contact-form',
119
+ { name: 'John', email: 'john@example.com' },
120
+ { attachments: ['file:1', 'file:2'] }, // File references
121
+ { excludeFields: ['password'], expirationMs: 86400000 }
122
+ );
123
+
124
+ // Load a draft
125
+ const result = await drafts.loadDraft<FormData>('contact-form');
126
+ if (result.restored) {
127
+ const { data, fileRefs } = result.draft;
128
+ }
129
+
130
+ // Check if draft exists
131
+ const hasDraft = await drafts.hasDraft('contact-form');
132
+
133
+ // Clear a draft
134
+ await drafts.clearDraft('contact-form');
135
+
136
+ // Merge partial data
137
+ await drafts.mergeDraft('contact-form', { phone: '123-456-7890' });
138
+
139
+ // Update file references
140
+ await drafts.updateFileRefs('contact-form', 'photos', ['file:3']);
141
+
142
+ // List all drafts
143
+ const formKeys = await drafts.listDraftFormKeys();
144
+ ```
145
+
146
+ ### Cache
147
+
148
+ ```typescript
149
+ const cache = storage.cache;
150
+
151
+ // Set a value
152
+ await cache.set(
153
+ 'key',
154
+ { data: 'value' },
155
+ {
156
+ ttl: 60000, // 1 minute
157
+ tags: ['user', 'profile'],
158
+ }
159
+ );
160
+
161
+ // Get a value
162
+ const result = await cache.get<User>('key');
163
+ if (result.hit && !result.stale) {
164
+ console.log(result.value);
165
+ }
166
+
167
+ // Get or fetch
168
+ const user = await cache.getOrSet('user:123', () => fetchUser(123), {
169
+ ttl: 300000,
170
+ staleWhileRevalidate: true,
171
+ staleTime: 60000,
172
+ });
173
+
174
+ // Invalidate
175
+ await cache.invalidate('key');
176
+ await cache.invalidateByTag('user');
177
+ await cache.invalidateAll();
178
+
179
+ // Statistics
180
+ const stats = await cache.getStats();
181
+ // { hits, misses, staleHits, hitRate, entryCount }
182
+ ```
183
+
184
+ ### Maintenance
185
+
186
+ ```typescript
187
+ // Manual cleanup of expired entries
188
+ const { deletedCount, freedBytes } = await storage.cleanup();
189
+
190
+ // Get storage quota info
191
+ const { used, available } = await storage.getQuota();
192
+
193
+ // Dispose when done
194
+ await storage.dispose();
195
+ ```
196
+
197
+ ## Storage Adapters
198
+
199
+ The package automatically selects the best available storage:
200
+
201
+ | Adapter | Priority | Browser Support | Performance |
202
+ | --------- | -------- | -------------------------------------- | -------------- |
203
+ | OPFS | 1 | Chrome 86+, Firefox 111+, Safari 15.2+ | Excellent |
204
+ | IndexedDB | 2 | All modern browsers | Good |
205
+ | Memory | 3 | All environments | N/A (volatile) |
206
+
207
+ ### Safari OPFS
208
+
209
+ Safari requires OPFS operations to run in a Web Worker. The package handles this automatically with a built-in worker.
210
+
211
+ ## Browser Compatibility
212
+
213
+ | Feature | Chrome | Firefox | Safari | Edge |
214
+ | --------- | ------ | ------- | ------ | ---- |
215
+ | OPFS | 86+ | 111+ | 15.2+ | 86+ |
216
+ | IndexedDB | Yes | Yes | Yes | Yes |
217
+ | Memory | Yes | Yes | Yes | Yes |
218
+
219
+ ## Subpath Exports
220
+
221
+ ```typescript
222
+ // Main entry
223
+ import { initOfflineStorage } from '@classic-homes/offline-core';
224
+
225
+ // Storage adapters only
226
+ import { createMemoryAdapter } from '@classic-homes/offline-core/storage';
227
+
228
+ // File service only
229
+ import { createFileStorageService } from '@classic-homes/offline-core/files';
230
+
231
+ // Draft service only
232
+ import { createDraftStorageService } from '@classic-homes/offline-core/drafts';
233
+
234
+ // Cache service only
235
+ import { createCacheService } from '@classic-homes/offline-core/cache';
236
+ ```
237
+
238
+ ## Default Expirations
239
+
240
+ - **Files**: 7 days
241
+ - **Drafts**: 24 hours
242
+ - **Cache**: 5 minutes
243
+
244
+ These can be overridden per-operation.
245
+
246
+ ## Error Handling
247
+
248
+ ```typescript
249
+ import { OfflineStorageError } from '@classic-homes/offline-core';
250
+
251
+ try {
252
+ await storage.files.storeFile(largeFile, options);
253
+ } catch (error) {
254
+ if (error instanceof OfflineStorageError) {
255
+ if (error.code === 'STORAGE_FULL') {
256
+ // Handle quota exceeded
257
+ }
258
+ }
259
+ }
260
+ ```
261
+
262
+ ## Testing
263
+
264
+ ```bash
265
+ npm test # Run tests
266
+ npm run test:watch # Watch mode
267
+ npm run test:coverage # With coverage
268
+ ```
269
+
270
+ ## License
271
+
272
+ MIT
@@ -0,0 +1,198 @@
1
+ import { S as StorageAdapter } from '../types-CWuauHAr.js';
2
+
3
+ /**
4
+ * Types for cache service
5
+ */
6
+ /**
7
+ * Cache entry structure
8
+ */
9
+ interface CacheEntry<T = unknown> {
10
+ /** Cache key */
11
+ key: string;
12
+ /** Cached data */
13
+ data: T;
14
+ /** Timestamp when entry was created */
15
+ createdAt: number;
16
+ /** Timestamp when entry will expire (null = never) */
17
+ expiresAt: number | null;
18
+ /** Tags for bulk invalidation */
19
+ tags?: string[];
20
+ }
21
+ /**
22
+ * Options for caching a value
23
+ */
24
+ interface CacheOptions {
25
+ /** Time to live in milliseconds */
26
+ ttl?: number;
27
+ /** Tags for bulk invalidation */
28
+ tags?: string[];
29
+ }
30
+ /**
31
+ * Options for the getOrSet operation
32
+ */
33
+ interface GetOrSetOptions extends CacheOptions {
34
+ /**
35
+ * Use stale data while revalidating in background
36
+ * @default false
37
+ */
38
+ staleWhileRevalidate?: boolean;
39
+ /**
40
+ * Time in ms that stale data is acceptable
41
+ * Only used when staleWhileRevalidate is true
42
+ * @default ttl (same as original ttl)
43
+ */
44
+ staleTime?: number;
45
+ /**
46
+ * Callback when value is being fetched (for loading states)
47
+ */
48
+ onFetching?: () => void;
49
+ /**
50
+ * Callback when fetch completes (success or error)
51
+ */
52
+ onFetchComplete?: (error?: Error) => void;
53
+ }
54
+ /**
55
+ * Result of a cache get operation
56
+ */
57
+ interface CacheGetResult<T> {
58
+ /** The cached value (null if not found or expired) */
59
+ value: T | null;
60
+ /** Whether the value was found in cache */
61
+ hit: boolean;
62
+ /** Whether the returned value is stale */
63
+ stale: boolean;
64
+ /** Time until expiration in ms (null if not cached or never expires) */
65
+ ttlRemaining: number | null;
66
+ }
67
+ /**
68
+ * Cache statistics
69
+ */
70
+ interface CacheStats {
71
+ /** Number of cache hits */
72
+ hits: number;
73
+ /** Number of cache misses */
74
+ misses: number;
75
+ /** Number of stale hits */
76
+ staleHits: number;
77
+ /** Hit rate (0-1) */
78
+ hitRate: number;
79
+ /** Number of entries currently cached */
80
+ entryCount: number;
81
+ }
82
+ /**
83
+ * Cache key prefix for organizing cache entries in storage
84
+ */
85
+ declare const CACHE_PREFIX = "cache:";
86
+ /**
87
+ * Generate a cache storage key
88
+ */
89
+ declare function getCacheKey(key: string): string;
90
+ /**
91
+ * Extract original key from cache storage key
92
+ */
93
+ declare function getOriginalKey(storageKey: string): string | null;
94
+
95
+ /**
96
+ * Generic cache service
97
+ *
98
+ * Provides caching with TTL, tags for bulk invalidation,
99
+ * and stale-while-revalidate support.
100
+ */
101
+
102
+ /**
103
+ * Cache service options
104
+ */
105
+ interface CacheServiceOptions {
106
+ /** Timeout for in-flight requests in ms (default: 30000) */
107
+ inFlightTimeout?: number;
108
+ /** Maximum concurrent in-flight requests (default: 100) */
109
+ maxInFlight?: number;
110
+ /** Maximum number of cache entries (default: 1000) */
111
+ maxEntries?: number;
112
+ /** Maximum total cache size in bytes (default: 50MB) */
113
+ maxSizeBytes?: number;
114
+ }
115
+ /**
116
+ * Cache storage service
117
+ */
118
+ declare class CacheService {
119
+ private readonly adapter;
120
+ private stats;
121
+ private inFlightFetches;
122
+ private readonly inFlightTimeout;
123
+ private readonly maxInFlight;
124
+ private readonly maxEntries;
125
+ private readonly maxSizeBytes;
126
+ private accessOrder;
127
+ constructor(adapter: StorageAdapter, options?: CacheServiceOptions);
128
+ /**
129
+ * Clean up stale in-flight requests
130
+ */
131
+ private cleanupStaleInFlight;
132
+ /**
133
+ * Get a cached value
134
+ */
135
+ get<T>(key: string): Promise<CacheGetResult<T>>;
136
+ /**
137
+ * Set a cached value
138
+ */
139
+ set<T>(key: string, value: T, options?: CacheOptions): Promise<void>;
140
+ /**
141
+ * Enforce cache size limits using LRU eviction
142
+ */
143
+ private enforceLimit;
144
+ /**
145
+ * Evict least recently used entries
146
+ */
147
+ private evictLRU;
148
+ /**
149
+ * Get cached value or fetch and cache it
150
+ */
151
+ getOrSet<T>(key: string, fetcher: () => Promise<T>, options?: GetOrSetOptions): Promise<T>;
152
+ /**
153
+ * Fetch and cache a value (with deduplication)
154
+ */
155
+ private fetchAndCache;
156
+ /**
157
+ * Revalidate cache in background
158
+ */
159
+ private revalidateInBackground;
160
+ /**
161
+ * Invalidate a cached value
162
+ */
163
+ invalidate(key: string): Promise<void>;
164
+ /**
165
+ * Invalidate all entries with a specific tag
166
+ */
167
+ invalidateByTag(tag: string): Promise<number>;
168
+ /**
169
+ * Invalidate all cached values
170
+ */
171
+ invalidateAll(): Promise<number>;
172
+ /**
173
+ * Check if a key is cached
174
+ */
175
+ has(key: string): Promise<boolean>;
176
+ /**
177
+ * List all cached keys
178
+ */
179
+ keys(): Promise<string[]>;
180
+ /**
181
+ * Get cache statistics
182
+ */
183
+ getStats(): Promise<CacheStats>;
184
+ /**
185
+ * Reset statistics
186
+ */
187
+ resetStats(): void;
188
+ /**
189
+ * Get all cache entries (for debugging)
190
+ */
191
+ getAll<T>(): Promise<CacheEntry<T>[]>;
192
+ }
193
+ /**
194
+ * Create a cache service
195
+ */
196
+ declare function createCacheService(adapter: StorageAdapter): CacheService;
197
+
198
+ export { CACHE_PREFIX, type CacheEntry, type CacheGetResult, type CacheOptions, CacheService, type CacheStats, type GetOrSetOptions, createCacheService, getCacheKey, getOriginalKey };
@@ -0,0 +1,2 @@
1
+ export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey } from '../chunk-UQUCUBV2.js';
2
+ import '../chunk-ZC7F2HDV.js';