Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | 1x 1x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 4958x 4958x 4958x 431x 431x 4958x 582x 582x 582x 582x 582x 582x 4958x 3945x 3945x 3945x 3945x 4958x 4958x 4958x 88x 194x 194x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 194x 88x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 88x 89x 89x 89x 89x 88x 43x 43x 43x 43x 88x 44x 44x 44x 44x 88x 68x 34x 34x 34x 68x 34x 68x 88x 61x 61x 88x 105x 105x 105x 105x 105x 105x 105x 105x 119x 119x 14x 14x 14x 119x 105x 105x 105x 105x 119x 105x 105x 105x 105x 88x 17x 17x 88x 2x 1x 1x 1x 1x 2x 88x 2x 2x 88x 17x 17x 6x 6x 6x 6x 3x 3x 3x 3x 17x 88x 18x 18x 7x 7x 7x 7x 7x 3x 3x 3x 3x 18x 88x 97x 97x 88x 7x 4x 4x 4x 4x 4x 4x 7x 88x 87x 87x 88x | import type { DataModel, StorageBase, ValueType } from "../types"; import { StorageEngine } from "../types"; /** @ignore */ export class IndexedDBStrategy implements StorageBase { private db: IDBDatabase | null = null; private memoryCache: Map<string, DataModel<ValueType>> = new Map(); private baseName: string; private storeName: string; private channel: BroadcastChannel; private dbPromise: Promise<IDBDatabase> | null = null; // Melhoria 2: Para gerenciar a promessa de abertura do DB constructor(baseName = "HybridWebCache", storeName?: string) { this.baseName = baseName.trim().length === 0 ? "HybridWebCache" : baseName.trim(); this.storeName = storeName?.trim() ?? this.baseName; this.channel = new BroadcastChannel(`${this.baseName}.${this.storeName}`); this.channel.onmessage = this.handleSyncEvent.bind(this); } private handleSyncEvent(event: MessageEvent): void { // Handle sync events for multi-instance communication const action = event.data?.action || ""; switch (action) { case "clear": this.memoryCache.clear(); break; case "unset": { const { key } = event.data; if (key) { this.memoryCache.delete(key); } break; } case "sync": { const { key, value } = event.data; this.memoryCache.set(key, value); break; } default: break; } } private async openDB(): Promise<IDBDatabase> { if (this.db) return this.db; if (this.dbPromise) return this.dbPromise; // em processo de abertura this.dbPromise = new Promise((resolve, reject) => { const request = indexedDB.open(this.baseName, 1); request.onupgradeneeded = (event) => { const db = (event.target as IDBOpenDBRequest).result; if (!db.objectStoreNames.contains(this.storeName)) { db.createObjectStore(this.storeName, { keyPath: "key" }); } }; // request.onsuccess = () => resolve(request.result); // request.onerror = () => reject(request.error); request.onsuccess = (event) => { this.db = (event.target as IDBOpenDBRequest).result; this.dbPromise = null; // Clean up the promise after success resolve(this.db); }; request.onerror = (event) => { console.error(`Failed to open IndexedDB: ${(event.target as IDBOpenDBRequest).error}`); this.dbPromise = null; // Clean up the promise after success reject((event.target as IDBOpenDBRequest).error); }; }); return this.dbPromise; } private async execute<T>(transactionMode: IDBTransactionMode, operation: (store: IDBObjectStore) => IDBRequest): Promise<T> { if (!this.db) await this.openDB(); if (!this.db) throw new Error("Database not initialized"); const transaction = this.db.transaction(this.storeName, transactionMode); const store = transaction.objectStore(this.storeName); const request = operation(store); return new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); transaction.onabort = () => reject(transaction.error || new Error("Transaction aborted")); // transaction.oncomplete = () => console.log("Transaction complete success"); }); } /** @internal */ async init(): Promise<void> { await this.openDB(); if (!this.db) throw new Error("IndexedDB not open, cannot load memory cache."); await this.getAll(); // Load existing data into memory cache } async set<T extends ValueType>(key: string, data: DataModel<T>): Promise<void> { await this.execute("readwrite", (store) => store.put({ key, ...data })); this.memoryCache.set(key, data); this.channel.postMessage({ action: "sync", key, value: data }); } setSync<T extends ValueType>(key: string, data: DataModel<T>): void { this.memoryCache.set(key, data); this.channel.postMessage({ action: "sync", key, value: data }); // this.executeQueue("readwrite", (store) => store.put({ key, ...data })); this.execute("readwrite", (store) => store.put({ key, ...data })); } async get<T extends ValueType>(key: string): Promise<DataModel<T> | undefined> { if (this.memoryCache.has(key)) { return this.memoryCache.get(key) as DataModel<T>; } const data = await this.execute<DataModel<T>>("readonly", (store) => store.get(key)); if (data) { this.memoryCache.set(key, data); return data; } return undefined; } getSync<T extends ValueType>(key: string): DataModel<T> | undefined { return this.memoryCache.has(key) ? (this.memoryCache.get(key) as DataModel<T>) : undefined; } async getAll<T extends ValueType>(): Promise<Map<string, DataModel<T>> | null> { await this.openDB(); // Garante que o DB esteja aberto if (!this.db) throw new Error("Database not initialized"); // Deve ser inatingível se openDB resolver const transaction = this.db.transaction(this.storeName, "readonly"); const store = transaction.objectStore(this.storeName); const request = store.openCursor(); return new Promise((resolve, reject) => { const result = new Map<string, DataModel<T>>(); request.onsuccess = (event) => { const cursor = (event.target as IDBRequest<IDBCursorWithValue>).result; if (cursor) { const storedData = cursor.value; result.set(cursor.key as string, storedData); cursor.continue(); } else { // Cursor finished, now update memoryCache and resolve this.memoryCache.clear(); result.forEach((value, key) => this.memoryCache.set(key, value)); resolve(result.size > 0 ? result : null); } }; request.onerror = () => reject(request.error); transaction.onabort = () => reject(transaction.error || new Error("Transaction aborted")); }); } getAllSync<T extends ValueType>(): Map<string, DataModel<T>> | null { return this.memoryCache.size > 0 ? (this.memoryCache as Map<string, DataModel<T>>) : null; } async has(key: string): Promise<boolean> { if (this.memoryCache.has(key)) { return true; } const value = await this.get(key); return value !== undefined; } hasSync(key: string): boolean { return this.memoryCache.has(key); } async unset(key?: string): Promise<boolean> { if (this.memoryCache.size === 0) return false; if (key && this.memoryCache.delete(key)) { this.channel.postMessage({ action: "unset", key, value: undefined }); // Notify other instances to remove key await this.execute("readwrite", (store) => store.delete(key)); return true; } this.memoryCache.clear(); this.channel.postMessage({ action: "clear", key: undefined, value: undefined }); // Notify other instances to clear keys await this.execute("readwrite", (store) => store.clear()); return true; } unsetSync(key?: string): boolean { if (this.memoryCache.size === 0) return false; if (key) { if (this.memoryCache.delete(key)) { this.channel.postMessage({ action: "unset", key, value: undefined }); // this.executeQueue("readwrite", (store) => store.delete(key)); this.execute("readwrite", (store) => store.delete(key)); return true; } return false; } this.memoryCache.clear(); this.channel.postMessage({ action: "clear", key: undefined, value: undefined }); // this.executeQueue("readwrite", (store) => store.clear()); this.execute("readwrite", (store) => store.clear()); return true; } get length(): number { return this.memoryCache.size; } get bytes(): number { if (this.memoryCache.size === 0) return 0; // return [...this.memoryCache.values()].reduce((acc, value) => acc + JSON.stringify(value).length, 0); let totalSize = 0; for (const [key, value] of this.memoryCache.entries()) { totalSize += new TextEncoder().encode(key).length; totalSize += new TextEncoder().encode(JSON.stringify(value)).length; } return totalSize; } get type(): StorageEngine { return StorageEngine.IndexedDB; } } |