@classic-homes/offline-svelte 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,355 @@
1
+ # @classic-homes/offline-svelte
2
+
3
+ Svelte 5 composables for offline persistence and caching. Provides reactive file storage, form draft persistence, and data caching using Svelte's runes.
4
+
5
+ ## Features
6
+
7
+ - **useFileStorage**: Reactive file storage with validation and previews
8
+ - **usePersistedForm**: Automatic form draft persistence
9
+ - **useOfflineCache**: Data caching with TTL and stale-while-revalidate
10
+ - **Svelte 5 Runes**: Built with `$state` and `$effect` for optimal reactivity
11
+ - **TypeScript**: Full type safety with generics
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @classic-homes/offline-svelte @classic-homes/offline-core
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```svelte
22
+ <script lang="ts">
23
+ import { onMount } from 'svelte';
24
+ import { initOfflineStorage } from '@classic-homes/offline-core';
25
+ import { useFileStorage, usePersistedForm, useOfflineCache } from '@classic-homes/offline-svelte';
26
+
27
+ // Initialize storage at app startup (e.g., in +layout.svelte)
28
+ onMount(async () => {
29
+ await initOfflineStorage();
30
+ });
31
+ </script>
32
+ ```
33
+
34
+ ## Composables
35
+
36
+ ### useFileStorage
37
+
38
+ Manage file attachments with validation, preview generation, and persistence.
39
+
40
+ ```svelte
41
+ <script lang="ts">
42
+ import { useFileStorage } from '@classic-homes/offline-svelte';
43
+
44
+ const documents = useFileStorage({
45
+ formKey: 'contact-form',
46
+ fieldName: 'documents',
47
+ maxFiles: 5,
48
+ maxSizeBytes: 10 * 1024 * 1024, // 10MB
49
+ acceptedTypes: ['application/pdf', 'image/*'],
50
+ onValidationError: (errors) => {
51
+ errors.forEach((e) => toast.error(e.message));
52
+ },
53
+ });
54
+
55
+ async function handleDrop(files: File[]) {
56
+ await documents.addFiles(files);
57
+ }
58
+ </script>
59
+
60
+ {#if documents.isLoading}
61
+ <Spinner />
62
+ {:else}
63
+ <ul>
64
+ {#each documents.files as file (file.id)}
65
+ <li>
66
+ {#if file.previewUrl}
67
+ <img src={file.previewUrl} alt={file.filename} />
68
+ {/if}
69
+ <span>{file.filename}</span>
70
+ <button onclick={() => documents.removeFile(file.id)}>Remove</button>
71
+ </li>
72
+ {/each}
73
+ </ul>
74
+ {/if}
75
+
76
+ <DropZone ondrop={handleDrop} />
77
+ ```
78
+
79
+ #### Options
80
+
81
+ | Option | Type | Description |
82
+ | ------------------- | ---------- | ------------------------------------------------ |
83
+ | `formKey` | `string` | Form identifier |
84
+ | `fieldName` | `string` | Field name within the form |
85
+ | `maxFiles` | `number` | Maximum number of files |
86
+ | `maxSizeBytes` | `number` | Maximum file size in bytes |
87
+ | `acceptedTypes` | `string[]` | Accepted MIME types (supports wildcards) |
88
+ | `expirationMs` | `number` | File expiration time |
89
+ | `generatePreviews` | `boolean` | Generate preview URLs for images (default: true) |
90
+ | `onValidationError` | `function` | Callback for validation errors |
91
+
92
+ #### Return Value
93
+
94
+ | Property | Type | Description |
95
+ | ------------------- | ----------------- | -------------------------------- |
96
+ | `files` | `PersistedFile[]` | Current files (reactive) |
97
+ | `fileIds` | `string[]` | File IDs for form submission |
98
+ | `isLoading` | `boolean` | Loading state |
99
+ | `error` | `Error \| null` | Current error |
100
+ | `addFiles` | `function` | Add files (validates and stores) |
101
+ | `removeFile` | `function` | Remove a file by ID |
102
+ | `clearFiles` | `function` | Remove all files |
103
+ | `reload` | `function` | Reload from storage |
104
+ | `getFilesForSubmit` | `function` | Get File objects for FormData |
105
+
106
+ ### usePersistedForm
107
+
108
+ Automatically persist form state across page reloads.
109
+
110
+ ```svelte
111
+ <script lang="ts">
112
+ import { usePersistedForm } from '@classic-homes/offline-svelte';
113
+ import { z } from 'zod';
114
+
115
+ const schema = z.object({
116
+ name: z.string().min(1),
117
+ email: z.string().email(),
118
+ message: z.string(),
119
+ });
120
+
121
+ const form = usePersistedForm({
122
+ formKey: 'contact-form',
123
+ defaultValues: { name: '', email: '', message: '' },
124
+ schema,
125
+ debounceMs: 500,
126
+ excludeFields: ['password'],
127
+ });
128
+
129
+ async function handleSubmit() {
130
+ if (!form.isValid) return;
131
+ await submitForm(form.values);
132
+ await form.clearDraft();
133
+ }
134
+ </script>
135
+
136
+ <form onsubmit|preventDefault={handleSubmit}>
137
+ {#if form.hasDraft}
138
+ <button type="button" onclick={form.restoreDraft}> Restore draft </button>
139
+ {/if}
140
+
141
+ <input
142
+ name="name"
143
+ value={form.values.name}
144
+ oninput={(e) => form.setValue('name', e.currentTarget.value)}
145
+ />
146
+ {#if form.errors.name}
147
+ <span class="error">{form.errors.name}</span>
148
+ {/if}
149
+
150
+ <input
151
+ name="email"
152
+ value={form.values.email}
153
+ oninput={(e) => form.setValue('email', e.currentTarget.value)}
154
+ />
155
+ {#if form.errors.email}
156
+ <span class="error">{form.errors.email}</span>
157
+ {/if}
158
+
159
+ <textarea
160
+ name="message"
161
+ value={form.values.message}
162
+ oninput={(e) => form.setValue('message', e.currentTarget.value)}
163
+ ></textarea>
164
+
165
+ <button type="submit" disabled={!form.isValid || form.isSubmitting}> Submit </button>
166
+ </form>
167
+ ```
168
+
169
+ #### Options
170
+
171
+ | Option | Type | Description |
172
+ | --------------- | ----------- | ------------------------------------------ |
173
+ | `formKey` | `string` | Unique form identifier |
174
+ | `defaultValues` | `T` | Default form values |
175
+ | `schema` | `ZodSchema` | Optional Zod validation schema |
176
+ | `debounceMs` | `number` | Debounce time for auto-save (default: 500) |
177
+ | `excludeFields` | `string[]` | Fields to exclude from persistence |
178
+ | `expirationMs` | `number` | Draft expiration time |
179
+ | `autoRestore` | `boolean` | Auto-restore on mount (default: false) |
180
+
181
+ #### Return Value
182
+
183
+ | Property | Type | Description |
184
+ | -------------- | ---------------- | -------------------------------- |
185
+ | `values` | `T` | Current form values (reactive) |
186
+ | `errors` | `FieldErrors<T>` | Validation errors by field |
187
+ | `isValid` | `boolean` | Whether form passes validation |
188
+ | `isDirty` | `boolean` | Whether form has unsaved changes |
189
+ | `hasDraft` | `boolean` | Whether a draft exists |
190
+ | `draftInfo` | `object` | Draft metadata |
191
+ | `setValue` | `function` | Set a field value |
192
+ | `setValues` | `function` | Set multiple values |
193
+ | `reset` | `function` | Reset to default values |
194
+ | `saveDraft` | `function` | Manually save draft |
195
+ | `restoreDraft` | `function` | Restore from draft |
196
+ | `clearDraft` | `function` | Delete the draft |
197
+
198
+ ### useOfflineCache
199
+
200
+ Cache data with TTL and stale-while-revalidate support.
201
+
202
+ ```svelte
203
+ <script lang="ts">
204
+ import { useOfflineCache } from '@classic-homes/offline-svelte';
205
+
206
+ interface User {
207
+ id: string;
208
+ name: string;
209
+ email: string;
210
+ }
211
+
212
+ let { userId } = $props<{ userId: string }>();
213
+
214
+ const userCache = useOfflineCache<User>({
215
+ key: `user:${userId}`,
216
+ ttl: 5 * 60 * 1000, // 5 minutes
217
+ tags: ['user'],
218
+ staleWhileRevalidate: true,
219
+ fetcher: () => fetchUser(userId), // Auto-fetch on mount
220
+ });
221
+
222
+ // Or manually fetch
223
+ $effect(() => {
224
+ userCache.get(() => fetchUser(userId));
225
+ });
226
+ </script>
227
+
228
+ {#if userCache.isLoading}
229
+ <Spinner />
230
+ {:else if userCache.error}
231
+ <Error error={userCache.error} />
232
+ {:else if userCache.data}
233
+ <div>
234
+ <h1>{userCache.data.name}</h1>
235
+ {#if userCache.isStale}
236
+ <span>Updating...</span>
237
+ {/if}
238
+ <button onclick={() => userCache.refresh(() => fetchUser(userId))}> Refresh </button>
239
+ </div>
240
+ {/if}
241
+ ```
242
+
243
+ #### Options
244
+
245
+ | Option | Type | Description |
246
+ | ---------------------- | ---------- | ------------------------------------- |
247
+ | `key` | `string` | Cache key |
248
+ | `ttl` | `number` | Time to live in milliseconds |
249
+ | `tags` | `string[]` | Tags for bulk invalidation |
250
+ | `staleWhileRevalidate` | `boolean` | Return stale data while fetching |
251
+ | `staleTime` | `number` | How long stale data is acceptable |
252
+ | `fetcher` | `function` | Auto-fetch function on initialization |
253
+
254
+ #### Return Value
255
+
256
+ | Property | Type | Description |
257
+ | -------------- | ---------------- | ---------------------- |
258
+ | `data` | `T \| null` | Cached data (reactive) |
259
+ | `isLoading` | `boolean` | Loading state |
260
+ | `isStale` | `boolean` | Whether data is stale |
261
+ | `error` | `Error \| null` | Current error |
262
+ | `ttlRemaining` | `number \| null` | Time until expiration |
263
+ | `get` | `function` | Get cached or fetch |
264
+ | `set` | `function` | Set cache value |
265
+ | `invalidate` | `function` | Invalidate this key |
266
+ | `refresh` | `function` | Force re-fetch |
267
+ | `has` | `function` | Check if cached |
268
+
269
+ ### Utility Functions
270
+
271
+ ```svelte
272
+ <script lang="ts">
273
+ import { invalidateCacheByTag, invalidateAllCache } from '@classic-homes/offline-svelte';
274
+
275
+ async function handleLogout() {
276
+ // Invalidate all user-related cache entries
277
+ await invalidateCacheByTag('user');
278
+ }
279
+
280
+ async function clearAllCache() {
281
+ await invalidateAllCache();
282
+ }
283
+ </script>
284
+ ```
285
+
286
+ ## Subpath Exports
287
+
288
+ Import individual composables for better tree-shaking:
289
+
290
+ ```typescript
291
+ // Import specific composable
292
+ import { useFileStorage } from '@classic-homes/offline-svelte/useFileStorage';
293
+ import { usePersistedForm } from '@classic-homes/offline-svelte/usePersistedForm';
294
+ import { useOfflineCache } from '@classic-homes/offline-svelte/useOfflineCache';
295
+ ```
296
+
297
+ ## TypeScript
298
+
299
+ All composables are fully typed with generics:
300
+
301
+ ```svelte
302
+ <script lang="ts">
303
+ interface User {
304
+ id: string;
305
+ name: string;
306
+ email: string;
307
+ }
308
+
309
+ const userCache = useOfflineCache<User>({ key: 'user' });
310
+ // userCache.data is User | null
311
+
312
+ const form = usePersistedForm<User>({
313
+ formKey: 'user',
314
+ defaultValues: { id: '', name: '', email: '' },
315
+ });
316
+ // form.values is User
317
+ // form.setValue('name', value) - 'name' is typed
318
+ </script>
319
+ ```
320
+
321
+ ## Svelte 5 Runes
322
+
323
+ The composables use Svelte 5's runes for reactivity:
324
+
325
+ - `$state` for reactive values
326
+ - `$effect` for side effects and cleanup
327
+ - Getter functions for derived values
328
+
329
+ This means the returned properties are reactive without needing stores:
330
+
331
+ ```svelte
332
+ <script lang="ts">
333
+ const cache = useOfflineCache({ key: 'data' });
334
+
335
+ // cache.data, cache.isLoading, etc. are reactive
336
+ // No need for $: reactive statements
337
+ </script>
338
+
339
+ <!-- Automatically updates when data changes -->
340
+ {#if cache.data}
341
+ <pre>{JSON.stringify(cache.data, null, 2)}</pre>
342
+ {/if}
343
+ ```
344
+
345
+ ## Testing
346
+
347
+ ```bash
348
+ npm test # Run tests
349
+ npm run test:watch # Watch mode
350
+ npm run test:coverage # With coverage
351
+ ```
352
+
353
+ ## License
354
+
355
+ MIT
@@ -0,0 +1 @@
1
+ import 'fake-indexeddb/auto';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Vitest setup file for Svelte tests
3
+ */
4
+ import { vi } from 'vitest';
5
+ import 'fake-indexeddb/auto';
6
+ // Mock URL.createObjectURL and revokeObjectURL
7
+ global.URL.createObjectURL = vi.fn((blob) => `blob:mock-${blob.size}`);
8
+ global.URL.revokeObjectURL = vi.fn();
9
+ // Mock navigator.storage
10
+ Object.defineProperty(navigator, 'storage', {
11
+ value: {
12
+ estimate: vi.fn().mockResolvedValue({
13
+ quota: 1000000000,
14
+ usage: 0,
15
+ }),
16
+ },
17
+ writable: true,
18
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Tests for useFileStorage composable
3
+ *
4
+ * Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
5
+ * These tests focus on the FileStorageService used by the composable.
6
+ */
7
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import { initOfflineStorage } from '@classic-homes/offline-core';
9
+ describe('FileStorageService integration (used by useFileStorage)', () => {
10
+ let storage;
11
+ beforeEach(async () => {
12
+ storage = await initOfflineStorage({
13
+ preferredAdapters: ['memory'],
14
+ });
15
+ });
16
+ afterEach(async () => {
17
+ await storage.cleanup.runCleanup();
18
+ await storage.dispose();
19
+ });
20
+ describe('file validation', () => {
21
+ it('should validate file size', () => {
22
+ const file = new File(['x'.repeat(2000)], 'large.txt', { type: 'text/plain' });
23
+ const errors = storage.files.validateFiles([file], { maxSizeBytes: 1000 });
24
+ expect(errors).toHaveLength(1);
25
+ expect(errors[0].code).toBe('TOO_LARGE');
26
+ });
27
+ it('should validate file count', () => {
28
+ const files = [
29
+ new File(['1'], 'file1.txt'),
30
+ new File(['2'], 'file2.txt'),
31
+ new File(['3'], 'file3.txt'),
32
+ ];
33
+ const errors = storage.files.validateFiles(files, { maxFiles: 2 });
34
+ expect(errors).toHaveLength(1);
35
+ expect(errors[0].code).toBe('TOO_MANY_FILES');
36
+ });
37
+ it('should validate file type', () => {
38
+ const file = new File(['data'], 'doc.pdf', { type: 'application/pdf' });
39
+ const errors = storage.files.validateFiles([file], { acceptedTypes: ['image/*'] });
40
+ expect(errors).toHaveLength(1);
41
+ expect(errors[0].code).toBe('INVALID_TYPE');
42
+ });
43
+ it('should accept wildcard MIME types', () => {
44
+ const imageFile = new File(['data'], 'img.png', { type: 'image/png' });
45
+ const errors = storage.files.validateFiles([imageFile], { acceptedTypes: ['image/*'] });
46
+ expect(errors).toHaveLength(0);
47
+ });
48
+ });
49
+ describe('file storage', () => {
50
+ it('should store and retrieve files', async () => {
51
+ const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
52
+ const stored = await storage.files.storeFile(file, {
53
+ formKey: 'form1',
54
+ fieldName: 'attachment',
55
+ });
56
+ expect(stored.id).toMatch(/^file:/);
57
+ expect(stored.filename).toBe('test.txt');
58
+ expect(stored.formKey).toBe('form1');
59
+ expect(stored.fieldName).toBe('attachment');
60
+ const retrieved = await storage.files.getFile(stored.id);
61
+ expect(retrieved).not.toBeNull();
62
+ expect(retrieved.filename).toBe('test.txt');
63
+ });
64
+ it('should store multiple files', async () => {
65
+ const files = [new File(['1'], 'file1.txt'), new File(['2'], 'file2.txt')];
66
+ const stored = await storage.files.storeFiles(files, {
67
+ formKey: 'form1',
68
+ fieldName: 'attachments',
69
+ });
70
+ expect(stored).toHaveLength(2);
71
+ });
72
+ it('should filter files by formKey and fieldName', async () => {
73
+ await storage.files.storeFile(new File(['1'], 'f1.txt'), {
74
+ formKey: 'form1',
75
+ fieldName: 'docs',
76
+ });
77
+ await storage.files.storeFile(new File(['2'], 'f2.txt'), {
78
+ formKey: 'form1',
79
+ fieldName: 'photos',
80
+ });
81
+ await storage.files.storeFile(new File(['3'], 'f3.txt'), {
82
+ formKey: 'form2',
83
+ fieldName: 'docs',
84
+ });
85
+ const form1Files = await storage.files.getFiles({ formKey: 'form1' });
86
+ expect(form1Files).toHaveLength(2);
87
+ const docsFiles = await storage.files.getFiles({ formKey: 'form1', fieldName: 'docs' });
88
+ expect(docsFiles).toHaveLength(1);
89
+ expect(docsFiles[0].fieldName).toBe('docs');
90
+ });
91
+ it('should delete files', async () => {
92
+ const stored = await storage.files.storeFile(new File(['data'], 'test.txt'), {
93
+ formKey: 'form1',
94
+ fieldName: 'doc',
95
+ });
96
+ const deleted = await storage.files.deleteFile(stored.id);
97
+ expect(deleted).toBe(true);
98
+ const retrieved = await storage.files.getFile(stored.id);
99
+ expect(retrieved).toBeNull();
100
+ });
101
+ it('should delete all files for a form', async () => {
102
+ await storage.files.storeFile(new File(['1'], 'f1.txt'), {
103
+ formKey: 'form1',
104
+ fieldName: 'docs',
105
+ });
106
+ await storage.files.storeFile(new File(['2'], 'f2.txt'), {
107
+ formKey: 'form1',
108
+ fieldName: 'photos',
109
+ });
110
+ await storage.files.storeFile(new File(['3'], 'f3.txt'), {
111
+ formKey: 'form2',
112
+ fieldName: 'docs',
113
+ });
114
+ const result = await storage.files.deleteFormFiles('form1');
115
+ expect(result.deletedCount).toBe(2);
116
+ const remaining = await storage.files.getFiles();
117
+ expect(remaining).toHaveLength(1);
118
+ expect(remaining[0].formKey).toBe('form2');
119
+ });
120
+ it('should generate preview URLs for images', async () => {
121
+ const imageFile = new File(['fake image'], 'photo.png', { type: 'image/png' });
122
+ const stored = await storage.files.storeFile(imageFile, {
123
+ formKey: 'form1',
124
+ fieldName: 'photo',
125
+ });
126
+ const retrieved = await storage.files.getFile(stored.id, true);
127
+ expect(retrieved.previewUrl).toBeDefined();
128
+ expect(retrieved.previewUrl).toMatch(/^blob:/);
129
+ });
130
+ it('should convert files back to File objects for submission', async () => {
131
+ const stored = await storage.files.storeFile(new File(['content'], 'test.txt', { type: 'text/plain' }), { formKey: 'form1', fieldName: 'doc' });
132
+ const fileMap = await storage.files.getFilesAsFileObjects([stored.id]);
133
+ expect(fileMap.size).toBe(1);
134
+ const file = fileMap.get(stored.id);
135
+ expect(file.name).toBe('test.txt');
136
+ expect(file.type).toBe('text/plain');
137
+ });
138
+ });
139
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Tests for useOfflineCache composable
3
+ *
4
+ * Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
5
+ * These tests focus on the utility functions and basic functionality.
6
+ */
7
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
8
+ import { initOfflineStorage } from '@classic-homes/offline-core';
9
+ import { invalidateCacheByTag, invalidateAllCache } from '../useOfflineCache.svelte.js';
10
+ describe('useOfflineCache utilities', () => {
11
+ let storage;
12
+ beforeEach(async () => {
13
+ storage = await initOfflineStorage({
14
+ preferredAdapters: ['memory'],
15
+ });
16
+ });
17
+ afterEach(async () => {
18
+ await storage.cleanup.runCleanup();
19
+ await storage.dispose();
20
+ });
21
+ describe('invalidateCacheByTag', () => {
22
+ it('should invalidate entries by tag', async () => {
23
+ await storage.cache.set('k1', 'v1', { tags: ['user'] });
24
+ await storage.cache.set('k2', 'v2', { tags: ['user'] });
25
+ await storage.cache.set('k3', 'v3', { tags: ['other'] });
26
+ const deleted = await invalidateCacheByTag('user');
27
+ expect(deleted).toBe(2);
28
+ // Verify entries are gone
29
+ const result1 = await storage.cache.get('k1');
30
+ const result2 = await storage.cache.get('k2');
31
+ const result3 = await storage.cache.get('k3');
32
+ expect(result1.hit).toBe(false);
33
+ expect(result2.hit).toBe(false);
34
+ expect(result3.hit).toBe(true);
35
+ });
36
+ it('should return 0 when no entries match', async () => {
37
+ await storage.cache.set('k1', 'v1', { tags: ['other'] });
38
+ const deleted = await invalidateCacheByTag('nonexistent');
39
+ expect(deleted).toBe(0);
40
+ });
41
+ });
42
+ describe('invalidateAllCache', () => {
43
+ it('should invalidate all cache entries', async () => {
44
+ await storage.cache.set('k1', 'v1');
45
+ await storage.cache.set('k2', 'v2');
46
+ await storage.cache.set('k3', 'v3');
47
+ const deleted = await invalidateAllCache();
48
+ expect(deleted).toBe(3);
49
+ // Verify all entries are gone
50
+ const keys = await storage.cache.keys();
51
+ expect(keys).toHaveLength(0);
52
+ });
53
+ it('should return 0 when cache is empty', async () => {
54
+ const deleted = await invalidateAllCache();
55
+ expect(deleted).toBe(0);
56
+ });
57
+ });
58
+ });
59
+ describe('CacheService integration (used by useOfflineCache)', () => {
60
+ let storage;
61
+ beforeEach(async () => {
62
+ storage = await initOfflineStorage({
63
+ preferredAdapters: ['memory'],
64
+ });
65
+ });
66
+ afterEach(async () => {
67
+ await storage.cleanup.runCleanup();
68
+ await storage.dispose();
69
+ });
70
+ it('should support get and set operations', async () => {
71
+ await storage.cache.set('test-key', { name: 'test', value: 42 }, { ttl: 10000 });
72
+ const result = await storage.cache.get('test-key');
73
+ expect(result.hit).toBe(true);
74
+ expect(result.value).toEqual({ name: 'test', value: 42 });
75
+ });
76
+ it('should support getOrSet with fetcher', async () => {
77
+ const fetcher = vi.fn().mockResolvedValue('fetched-value');
78
+ const value = await storage.cache.getOrSet('key', fetcher, { ttl: 10000 });
79
+ expect(value).toBe('fetched-value');
80
+ expect(fetcher).toHaveBeenCalledTimes(1);
81
+ // Second call should use cache
82
+ const value2 = await storage.cache.getOrSet('key', fetcher);
83
+ expect(value2).toBe('fetched-value');
84
+ expect(fetcher).toHaveBeenCalledTimes(1);
85
+ });
86
+ it('should support invalidation', async () => {
87
+ await storage.cache.set('key', 'value');
88
+ await storage.cache.invalidate('key');
89
+ const result = await storage.cache.get('key');
90
+ expect(result.hit).toBe(false);
91
+ });
92
+ it('should track staleness', async () => {
93
+ vi.useFakeTimers();
94
+ const now = Date.now();
95
+ vi.setSystemTime(now);
96
+ await storage.cache.set('key', 'value', { ttl: 1000 });
97
+ // Fresh
98
+ let result = await storage.cache.get('key');
99
+ expect(result.hit).toBe(true);
100
+ expect(result.stale).toBe(false);
101
+ // Expired (stale)
102
+ vi.setSystemTime(now + 2000);
103
+ result = await storage.cache.get('key');
104
+ expect(result.hit).toBe(true);
105
+ expect(result.stale).toBe(true);
106
+ vi.useRealTimers();
107
+ });
108
+ it('should support tags for bulk invalidation', async () => {
109
+ await storage.cache.set('user:1', { name: 'John' }, { tags: ['user', 'active'] });
110
+ await storage.cache.set('user:2', { name: 'Jane' }, { tags: ['user', 'inactive'] });
111
+ await storage.cache.set('post:1', { title: 'Hello' }, { tags: ['post'] });
112
+ const deleted = await storage.cache.invalidateByTag('user');
113
+ expect(deleted).toBe(2);
114
+ const userResult = await storage.cache.get('user:1');
115
+ expect(userResult.hit).toBe(false);
116
+ const postResult = await storage.cache.get('post:1');
117
+ expect(postResult.hit).toBe(true);
118
+ });
119
+ });
@@ -0,0 +1 @@
1
+ export {};