@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.
@@ -0,0 +1,312 @@
1
+ import { DEFAULT_EXPIRATIONS } from './chunk-ZC7F2HDV.js';
2
+
3
+ // src/files/types.ts
4
+ function storedFileToBlobMetadata(file) {
5
+ return {
6
+ filename: file.filename,
7
+ contentType: file.contentType,
8
+ size: file.size,
9
+ createdAt: file.createdAt,
10
+ expiresAt: file.expiresAt,
11
+ formKey: file.formKey,
12
+ fieldName: file.fieldName
13
+ };
14
+ }
15
+ function blobMetadataToStoredFile(id, metadata) {
16
+ if (!metadata.formKey || !metadata.fieldName || !metadata.filename || metadata.size === void 0 || metadata.createdAt === void 0 || metadata.expiresAt === void 0) {
17
+ return null;
18
+ }
19
+ return {
20
+ id,
21
+ formKey: metadata.formKey,
22
+ fieldName: metadata.fieldName,
23
+ filename: metadata.filename,
24
+ contentType: metadata.contentType ?? "application/octet-stream",
25
+ size: metadata.size,
26
+ createdAt: metadata.createdAt,
27
+ expiresAt: metadata.expiresAt
28
+ };
29
+ }
30
+
31
+ // src/files/service.ts
32
+ var FILE_PREFIX = "file:";
33
+ function generateFileId() {
34
+ return `${FILE_PREFIX}${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
35
+ }
36
+ function isFileKey(key) {
37
+ return key.startsWith(FILE_PREFIX);
38
+ }
39
+ function matchesMimeType(type, pattern) {
40
+ if (pattern === "*/*" || pattern === "*") {
41
+ return true;
42
+ }
43
+ if (pattern.endsWith("/*")) {
44
+ const category = pattern.slice(0, -2);
45
+ return type.startsWith(category + "/");
46
+ }
47
+ return type === pattern;
48
+ }
49
+ var FileStorageService = class {
50
+ constructor(adapter) {
51
+ this.adapter = adapter;
52
+ }
53
+ /**
54
+ * Validate files against constraints
55
+ */
56
+ validateFiles(files, constraints, existingCount = 0) {
57
+ const errors = [];
58
+ if (constraints.maxFiles !== void 0) {
59
+ const totalCount = existingCount + files.length;
60
+ if (totalCount > constraints.maxFiles) {
61
+ const excess = files.slice(constraints.maxFiles - existingCount);
62
+ for (const file of excess) {
63
+ errors.push({
64
+ file,
65
+ code: "TOO_MANY_FILES",
66
+ message: `Maximum ${constraints.maxFiles} files allowed`
67
+ });
68
+ }
69
+ }
70
+ }
71
+ for (const file of files) {
72
+ if (constraints.maxSizeBytes !== void 0 && file.size > constraints.maxSizeBytes) {
73
+ const maxMB = (constraints.maxSizeBytes / (1024 * 1024)).toFixed(1);
74
+ errors.push({
75
+ file,
76
+ code: "TOO_LARGE",
77
+ message: `File size exceeds ${maxMB}MB limit`
78
+ });
79
+ continue;
80
+ }
81
+ if (constraints.acceptedTypes && constraints.acceptedTypes.length > 0) {
82
+ const typeMatches = constraints.acceptedTypes.some(
83
+ (pattern) => matchesMimeType(file.type, pattern)
84
+ );
85
+ if (!typeMatches) {
86
+ errors.push({
87
+ file,
88
+ code: "INVALID_TYPE",
89
+ message: `File type ${file.type || "unknown"} is not accepted`
90
+ });
91
+ }
92
+ }
93
+ }
94
+ return errors;
95
+ }
96
+ /**
97
+ * Store a file
98
+ */
99
+ async storeFile(file, options) {
100
+ const id = generateFileId();
101
+ const now = Date.now();
102
+ const expiresAt = now + (options.expirationMs ?? DEFAULT_EXPIRATIONS.FILE);
103
+ const storedFile = {
104
+ id,
105
+ formKey: options.formKey,
106
+ fieldName: options.fieldName,
107
+ filename: file.name,
108
+ contentType: file.type || "application/octet-stream",
109
+ size: file.size,
110
+ createdAt: now,
111
+ expiresAt
112
+ };
113
+ const metadata = {
114
+ ...storedFileToBlobMetadata(storedFile),
115
+ ...options.metadata
116
+ };
117
+ await this.adapter.storeBlob(id, file, metadata);
118
+ return storedFile;
119
+ }
120
+ /**
121
+ * Store multiple files
122
+ */
123
+ async storeFiles(files, options) {
124
+ const results = [];
125
+ for (const file of files) {
126
+ const stored = await this.storeFile(file, options);
127
+ results.push(stored);
128
+ }
129
+ return results;
130
+ }
131
+ /**
132
+ * Get a single file by ID
133
+ */
134
+ async getFile(id, generatePreview = false) {
135
+ const result = await this.adapter.getBlob(id);
136
+ if (!result) {
137
+ return null;
138
+ }
139
+ const storedFile = blobMetadataToStoredFile(id, result.metadata);
140
+ if (!storedFile) {
141
+ return null;
142
+ }
143
+ const persisted = {
144
+ ...storedFile,
145
+ blob: result.blob
146
+ };
147
+ if (generatePreview && result.metadata.contentType?.startsWith("image/")) {
148
+ persisted.previewUrl = URL.createObjectURL(result.blob);
149
+ }
150
+ return persisted;
151
+ }
152
+ /**
153
+ * Get files matching options
154
+ */
155
+ async getFiles(options = {}) {
156
+ const { formKey, fieldName, includeBlobs = true, generatePreviews = false } = options;
157
+ const files = [];
158
+ if (formKey && this.adapter.listBlobsByFormKey) {
159
+ const indexedResults = await this.adapter.listBlobsByFormKey(formKey, fieldName);
160
+ for (const { key, metadata } of indexedResults) {
161
+ if (!isFileKey(key)) {
162
+ continue;
163
+ }
164
+ const storedFile = blobMetadataToStoredFile(key, metadata);
165
+ if (!storedFile) {
166
+ continue;
167
+ }
168
+ let blob = new Blob();
169
+ if (includeBlobs) {
170
+ const result = await this.adapter.getBlob(key);
171
+ if (result) {
172
+ blob = result.blob;
173
+ }
174
+ }
175
+ const persisted = {
176
+ ...storedFile,
177
+ blob
178
+ };
179
+ if (generatePreviews && includeBlobs && metadata.contentType?.startsWith("image/")) {
180
+ persisted.previewUrl = URL.createObjectURL(blob);
181
+ }
182
+ files.push(persisted);
183
+ }
184
+ } else {
185
+ const keys = await this.adapter.listBlobs(FILE_PREFIX);
186
+ for (const key of keys) {
187
+ if (!isFileKey(key)) {
188
+ continue;
189
+ }
190
+ const result = await this.adapter.getBlob(key);
191
+ if (!result) {
192
+ continue;
193
+ }
194
+ if (formKey && result.metadata.formKey !== formKey) {
195
+ continue;
196
+ }
197
+ if (fieldName && result.metadata.fieldName !== fieldName) {
198
+ continue;
199
+ }
200
+ const storedFile = blobMetadataToStoredFile(key, result.metadata);
201
+ if (!storedFile) {
202
+ continue;
203
+ }
204
+ const persisted = {
205
+ ...storedFile,
206
+ blob: includeBlobs ? result.blob : new Blob()
207
+ };
208
+ if (generatePreviews && includeBlobs && result.metadata.contentType?.startsWith("image/")) {
209
+ persisted.previewUrl = URL.createObjectURL(result.blob);
210
+ }
211
+ files.push(persisted);
212
+ }
213
+ }
214
+ files.sort((a, b) => b.createdAt - a.createdAt);
215
+ return files;
216
+ }
217
+ /**
218
+ * Get file IDs for a form/field
219
+ */
220
+ async getFileIds(formKey, fieldName) {
221
+ const files = await this.getFiles({
222
+ formKey,
223
+ fieldName,
224
+ includeBlobs: false
225
+ });
226
+ return files.map((f) => f.id);
227
+ }
228
+ /**
229
+ * Delete a single file
230
+ * @returns true if file was deleted, false if file didn't exist
231
+ * @throws Error if deletion fails for other reasons
232
+ */
233
+ async deleteFile(id) {
234
+ const exists = await this.adapter.getBlob(id);
235
+ if (!exists) {
236
+ return false;
237
+ }
238
+ await this.adapter.deleteBlob(id);
239
+ return true;
240
+ }
241
+ /**
242
+ * Delete multiple files
243
+ */
244
+ async deleteFiles(ids) {
245
+ let deletedCount = 0;
246
+ let freedBytes = 0;
247
+ const deleted = [];
248
+ const failed = [];
249
+ for (const id of ids) {
250
+ try {
251
+ const result = await this.adapter.getBlob(id);
252
+ if (result) {
253
+ freedBytes += result.metadata.size ?? 0;
254
+ await this.adapter.deleteBlob(id);
255
+ deletedCount++;
256
+ deleted.push(id);
257
+ } else {
258
+ deleted.push(id);
259
+ }
260
+ } catch (error) {
261
+ failed.push({
262
+ id,
263
+ error: error instanceof Error ? error.message : "Unknown error"
264
+ });
265
+ }
266
+ }
267
+ return { deletedCount, freedBytes, deleted, failed };
268
+ }
269
+ /**
270
+ * Delete all files for a form
271
+ */
272
+ async deleteFormFiles(formKey, fieldName) {
273
+ const files = await this.getFiles({
274
+ formKey,
275
+ fieldName,
276
+ includeBlobs: false
277
+ });
278
+ return this.deleteFiles(files.map((f) => f.id));
279
+ }
280
+ /**
281
+ * Convert stored files back to File objects for submission
282
+ */
283
+ async getFilesAsFileObjects(ids) {
284
+ const result = /* @__PURE__ */ new Map();
285
+ for (const id of ids) {
286
+ const persisted = await this.getFile(id);
287
+ if (persisted) {
288
+ const file = new File([persisted.blob], persisted.filename, {
289
+ type: persisted.contentType,
290
+ lastModified: persisted.createdAt
291
+ });
292
+ result.set(id, file);
293
+ }
294
+ }
295
+ return result;
296
+ }
297
+ /**
298
+ * Revoke preview URLs to free memory
299
+ */
300
+ revokePreviewUrls(files) {
301
+ for (const file of files) {
302
+ if (file.previewUrl) {
303
+ URL.revokeObjectURL(file.previewUrl);
304
+ }
305
+ }
306
+ }
307
+ };
308
+ function createFileStorageService(adapter) {
309
+ return new FileStorageService(adapter);
310
+ }
311
+
312
+ export { FileStorageService, blobMetadataToStoredFile, createFileStorageService, storedFileToBlobMetadata };
@@ -0,0 +1,297 @@
1
+ import { DEFAULT_EXPIRATIONS } from './chunk-ZC7F2HDV.js';
2
+
3
+ // src/cache/types.ts
4
+ var CACHE_PREFIX = "cache:";
5
+ function getCacheKey(key) {
6
+ return `${CACHE_PREFIX}${key}`;
7
+ }
8
+ function getOriginalKey(storageKey) {
9
+ if (!storageKey.startsWith(CACHE_PREFIX)) {
10
+ return null;
11
+ }
12
+ return storageKey.slice(CACHE_PREFIX.length);
13
+ }
14
+
15
+ // src/cache/service.ts
16
+ var DEFAULT_IN_FLIGHT_TIMEOUT = 3e4;
17
+ var DEFAULT_MAX_IN_FLIGHT = 100;
18
+ var DEFAULT_MAX_ENTRIES = 1e3;
19
+ var DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;
20
+ var CacheService = class {
21
+ constructor(adapter, options) {
22
+ this.adapter = adapter;
23
+ this.stats = {
24
+ hits: 0,
25
+ misses: 0,
26
+ staleHits: 0
27
+ };
28
+ // Track in-flight fetches to avoid duplicate requests
29
+ this.inFlightFetches = /* @__PURE__ */ new Map();
30
+ // Track access order for LRU eviction (key -> last access timestamp)
31
+ this.accessOrder = /* @__PURE__ */ new Map();
32
+ this.inFlightTimeout = options?.inFlightTimeout ?? DEFAULT_IN_FLIGHT_TIMEOUT;
33
+ this.maxInFlight = options?.maxInFlight ?? DEFAULT_MAX_IN_FLIGHT;
34
+ this.maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;
35
+ this.maxSizeBytes = options?.maxSizeBytes ?? DEFAULT_MAX_SIZE_BYTES;
36
+ }
37
+ /**
38
+ * Clean up stale in-flight requests
39
+ */
40
+ cleanupStaleInFlight() {
41
+ const now = Date.now();
42
+ for (const [key, entry] of this.inFlightFetches) {
43
+ if (now - entry.startedAt > this.inFlightTimeout) {
44
+ this.inFlightFetches.delete(key);
45
+ }
46
+ }
47
+ }
48
+ /**
49
+ * Get a cached value
50
+ */
51
+ async get(key) {
52
+ const storageKey = getCacheKey(key);
53
+ const entry = await this.adapter.getJSON(storageKey);
54
+ if (!entry) {
55
+ this.stats.misses++;
56
+ return {
57
+ value: null,
58
+ hit: false,
59
+ stale: false,
60
+ ttlRemaining: null
61
+ };
62
+ }
63
+ const cached = entry.data;
64
+ const now = Date.now();
65
+ const isExpired = cached.expiresAt !== null && now > cached.expiresAt;
66
+ if (isExpired) {
67
+ this.stats.staleHits++;
68
+ return {
69
+ value: cached.data,
70
+ hit: true,
71
+ stale: true,
72
+ ttlRemaining: 0
73
+ };
74
+ }
75
+ this.stats.hits++;
76
+ this.accessOrder.set(key, now);
77
+ return {
78
+ value: cached.data,
79
+ hit: true,
80
+ stale: false,
81
+ ttlRemaining: cached.expiresAt !== null ? cached.expiresAt - now : null
82
+ };
83
+ }
84
+ /**
85
+ * Set a cached value
86
+ */
87
+ async set(key, value, options = {}) {
88
+ const storageKey = getCacheKey(key);
89
+ const now = Date.now();
90
+ const ttl = options.ttl ?? DEFAULT_EXPIRATIONS.CACHE;
91
+ const entry = {
92
+ data: value,
93
+ createdAt: now,
94
+ expiresAt: ttl > 0 ? now + ttl : null,
95
+ tags: options.tags
96
+ };
97
+ await this.enforceLimit();
98
+ await this.adapter.storeJSON(storageKey, entry, {
99
+ ttl: ttl > 0 ? ttl : void 0,
100
+ tags: options.tags ? [...options.tags, "cache"] : ["cache"]
101
+ });
102
+ this.accessOrder.set(key, now);
103
+ }
104
+ /**
105
+ * Enforce cache size limits using LRU eviction
106
+ */
107
+ async enforceLimit() {
108
+ const keys = await this.keys();
109
+ if (keys.length >= this.maxEntries) {
110
+ const evictCount = Math.max(1, Math.floor(this.maxEntries * 0.1));
111
+ await this.evictLRU(keys, evictCount);
112
+ }
113
+ try {
114
+ const quota = await this.adapter.getQuota();
115
+ if (quota && quota.used > this.maxSizeBytes) {
116
+ const evictCount = Math.max(1, Math.floor(keys.length * 0.2));
117
+ await this.evictLRU(await this.keys(), evictCount);
118
+ }
119
+ } catch {
120
+ }
121
+ }
122
+ /**
123
+ * Evict least recently used entries
124
+ */
125
+ async evictLRU(keys, count) {
126
+ const sorted = [...keys].sort((a, b) => {
127
+ const accessA = this.accessOrder.get(a) ?? 0;
128
+ const accessB = this.accessOrder.get(b) ?? 0;
129
+ return accessA - accessB;
130
+ });
131
+ const toEvict = sorted.slice(0, count);
132
+ for (const key of toEvict) {
133
+ await this.invalidate(key);
134
+ this.accessOrder.delete(key);
135
+ }
136
+ }
137
+ /**
138
+ * Get cached value or fetch and cache it
139
+ */
140
+ async getOrSet(key, fetcher, options = {}) {
141
+ const {
142
+ ttl = DEFAULT_EXPIRATIONS.CACHE,
143
+ tags,
144
+ staleWhileRevalidate = false,
145
+ staleTime,
146
+ onFetching,
147
+ onFetchComplete
148
+ } = options;
149
+ const cached = await this.get(key);
150
+ if (cached.hit && !cached.stale) {
151
+ return cached.value;
152
+ }
153
+ if (cached.hit && cached.stale && staleWhileRevalidate) {
154
+ const result = await this.adapter.getJSON(getCacheKey(key));
155
+ if (result) {
156
+ const entry = result.data;
157
+ const staleThreshold = staleTime ?? ttl;
158
+ const now = Date.now();
159
+ const age = entry.expiresAt !== null ? now - entry.expiresAt : 0;
160
+ if (age < staleThreshold) {
161
+ void this.revalidateInBackground(key, fetcher, { ttl, tags });
162
+ return cached.value;
163
+ }
164
+ }
165
+ }
166
+ return this.fetchAndCache(key, fetcher, { ttl, tags }, onFetching, onFetchComplete);
167
+ }
168
+ /**
169
+ * Fetch and cache a value (with deduplication)
170
+ */
171
+ async fetchAndCache(key, fetcher, options, onFetching, onFetchComplete) {
172
+ this.cleanupStaleInFlight();
173
+ const existing = this.inFlightFetches.get(key);
174
+ if (existing) {
175
+ return existing.promise;
176
+ }
177
+ if (this.inFlightFetches.size >= this.maxInFlight) {
178
+ const oldestKey = this.inFlightFetches.keys().next().value;
179
+ if (oldestKey !== void 0) {
180
+ this.inFlightFetches.delete(oldestKey);
181
+ }
182
+ }
183
+ onFetching?.();
184
+ const fetchPromise = (async () => {
185
+ try {
186
+ const value = await fetcher();
187
+ await this.set(key, value, options);
188
+ onFetchComplete?.();
189
+ return value;
190
+ } catch (error) {
191
+ onFetchComplete?.(error);
192
+ throw error;
193
+ } finally {
194
+ this.inFlightFetches.delete(key);
195
+ }
196
+ })();
197
+ this.inFlightFetches.set(key, {
198
+ promise: fetchPromise,
199
+ startedAt: Date.now()
200
+ });
201
+ return fetchPromise;
202
+ }
203
+ /**
204
+ * Revalidate cache in background
205
+ */
206
+ async revalidateInBackground(key, fetcher, options) {
207
+ this.fetchAndCache(key, fetcher, options).catch((error) => {
208
+ console.warn(`Background revalidation failed for ${key}:`, error);
209
+ });
210
+ }
211
+ /**
212
+ * Invalidate a cached value
213
+ */
214
+ async invalidate(key) {
215
+ const storageKey = getCacheKey(key);
216
+ await this.adapter.deleteJSON(storageKey);
217
+ this.accessOrder.delete(key);
218
+ }
219
+ /**
220
+ * Invalidate all entries with a specific tag
221
+ */
222
+ async invalidateByTag(tag) {
223
+ return this.adapter.deleteJSONByTag(tag);
224
+ }
225
+ /**
226
+ * Invalidate all cached values
227
+ */
228
+ async invalidateAll() {
229
+ const count = await this.adapter.deleteJSONByTag("cache");
230
+ this.accessOrder.clear();
231
+ return count;
232
+ }
233
+ /**
234
+ * Check if a key is cached
235
+ */
236
+ async has(key) {
237
+ const result = await this.get(key);
238
+ return result.hit && !result.stale;
239
+ }
240
+ /**
241
+ * List all cached keys
242
+ */
243
+ async keys() {
244
+ const storageKeys = await this.adapter.listJSON(CACHE_PREFIX);
245
+ return storageKeys.map(getOriginalKey).filter((key) => key !== null);
246
+ }
247
+ /**
248
+ * Get cache statistics
249
+ */
250
+ async getStats() {
251
+ const keys = await this.keys();
252
+ const total = this.stats.hits + this.stats.misses;
253
+ return {
254
+ hits: this.stats.hits,
255
+ misses: this.stats.misses,
256
+ staleHits: this.stats.staleHits,
257
+ hitRate: total > 0 ? this.stats.hits / total : 0,
258
+ entryCount: keys.length
259
+ };
260
+ }
261
+ /**
262
+ * Reset statistics
263
+ */
264
+ resetStats() {
265
+ this.stats = {
266
+ hits: 0,
267
+ misses: 0,
268
+ staleHits: 0
269
+ };
270
+ }
271
+ /**
272
+ * Get all cache entries (for debugging)
273
+ */
274
+ async getAll() {
275
+ const keys = await this.keys();
276
+ const entries = [];
277
+ for (const key of keys) {
278
+ const result = await this.adapter.getJSON(getCacheKey(key));
279
+ if (result) {
280
+ const entry = result.data;
281
+ entries.push({
282
+ key,
283
+ data: entry.data,
284
+ createdAt: entry.createdAt,
285
+ expiresAt: entry.expiresAt,
286
+ tags: entry.tags
287
+ });
288
+ }
289
+ }
290
+ return entries;
291
+ }
292
+ };
293
+ function createCacheService(adapter) {
294
+ return new CacheService(adapter);
295
+ }
296
+
297
+ export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey };