Open History to see the last commit
1/**
2 * IndexedDB Database Wrapper
3 *
4 * This module provides promise-based utilities for working with IndexedDB.
5 * All functions return promises and wrap IndexedDB errors with descriptive messages.
6 */
7
8/**
9 * Gets the IndexedDB factory, with cross-environment support.
10 * @param idbFactory - Optional custom IDBFactory for testing
11 * @returns The IDBFactory to use
12 * @throws Error if IndexedDB is not available
13 */
14function getIDBFactory(idbFactory?: IDBFactory): IDBFactory {
15 if (idbFactory) {
16 return idbFactory
17 }
18
19 // Try window.indexedDB first (browser environment)
20 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime check needed
21 if (typeof window !== 'undefined' && window.indexedDB) {
22 return window.indexedDB
23 }
24
25 // Try globalThis.indexedDB (modern environments, including Node.js with polyfill)
26 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime check needed
27 if (typeof globalThis !== 'undefined' && globalThis.indexedDB) {
28 return globalThis.indexedDB
29 }
30
31 throw new Error(
32 'IndexedDB is not available in this environment. ' +
33 'Ensure you are running in a browser or provide a custom IDBFactory for testing.',
34 )
35}
36
37function executeRequest<T>(
38 createRequest: () => IDBRequest<T>,
39 describeFailure: () => string,
40): Promise<T> {
41 return new Promise((resolve, reject) => {
42 let request: IDBRequest<T>
43 try {
44 request = createRequest()
45 } catch (error) {
46 reject(
47 new Error(
48 `${describeFailure()}: ${error instanceof Error ? error.message : String(error)}`,
49 { cause: error },
50 ),
51 )
52 return
53 }
54 request.onsuccess = () => resolve(request.result)
55 request.onerror = () => {
56 const errorMessage = request.error?.message || 'Unknown error'
57 reject(
58 new Error(`${describeFailure()}: ${errorMessage}`, {
59 cause: request.error,
60 }),
61 )
62 }
63 })
64}
65
66/**
67 * Opens an IndexedDB database with the specified name and version.
68 * A blocked request stays pending until native success or error. The caller
69 * owns the returned connection and must close it when no longer needed.
70 *
71 * @param name - The name of the database to open
72 * @param version - The version number of the database schema
73 * @param onUpgrade - Optional callback that runs during the onupgradeneeded event.
74 * Use this to create object stores and indexes.
75 * @param idbFactory - Optional IDBFactory for testing/mocking (defaults to window.indexedDB or globalThis.indexedDB)
76 * @param onBlocked - Optional diagnostic callback for native blocked events. The request stays pending.
77 * @returns A promise that resolves to the IDBDatabase instance
78 *
79 * @example
80 * ```typescript
81 * const db = await openDatabase('myApp', 1, (db, oldVersion, newVersion, transaction) => {
82 * if (oldVersion < 1) {
83 * db.createObjectStore('todos', { keyPath: 'id' })
84 * }
85 * })
86 * ```
87 */
88export function openDatabase(
89 name: string,
90 version: number,
91 onUpgrade?: (
92 db: IDBDatabase,
93 oldVersion: number,
94 newVersion: number,
95 transaction: IDBTransaction,
96 ) => void,
97 idbFactory?: IDBFactory,
98 onBlocked?: (event: IDBVersionChangeEvent) => void,
99): Promise<IDBDatabase> {
100 return new Promise((resolve, reject) => {
101 const factory = getIDBFactory(idbFactory)
102
103 let request: IDBOpenDBRequest
104 try {
105 request = factory.open(name, version)
106 } catch (error) {
107 reject(
108 new Error(
109 `Failed to open IndexedDB database "${name}": ${error instanceof Error ? error.message : String(error)}`,
110 { cause: error },
111 ),
112 )
113 return
114 }
115
116 request.onupgradeneeded = (event) => {
117 const db = request.result
118 const transaction = request.transaction
119 if (onUpgrade && transaction) {
120 try {
121 onUpgrade(
122 db,
123 event.oldVersion,
124 event.newVersion ?? version,
125 transaction,
126 )
127 } catch (error) {
128 // If the upgrade callback throws, abort the transaction
129 transaction.abort()
130 reject(
131 new Error(
132 `Database upgrade failed for "${name}": ${error instanceof Error ? error.message : String(error)}`,
133 { cause: error },
134 ),
135 )
136 }
137 }
138 }
139
140 if (onBlocked) request.addEventListener('blocked', onBlocked)
141
142 request.onsuccess = () => {
143 resolve(request.result)
144 }
145
146 request.onerror = () => {
147 const errorMessage = request.error?.message || 'Unknown error'
148 reject(
149 new Error(
150 `Failed to open IndexedDB database "${name}": ${errorMessage}`,
151 { cause: request.error },
152 ),
153 )
154 }
155 })
156}
157
158/**
159 * Creates an object store during a database upgrade.
160 *
161 * This function must be called within an onupgradeneeded callback
162 * (i.e., within a versionchange transaction). Calling it outside of
163 * an upgrade context will throw an error.
164 *
165 * @param db - The IDBDatabase instance
166 * @param storeName - The name of the object store to create
167 * @param options - Optional configuration for the object store (keyPath, autoIncrement)
168 * @returns The created IDBObjectStore
169 * @throws Error if not called during a version change transaction
170 *
171 * @example
172 * ```typescript
173 * const db = await openDatabase('myApp', 1, (db) => {
174 * createObjectStore(db, 'todos', { keyPath: 'id' })
175 * createObjectStore(db, 'users', { keyPath: 'id', autoIncrement: true })
176 * })
177 * ```
178 */
179export function createObjectStore(
180 db: IDBDatabase,
181 storeName: string,
182 options?: IDBObjectStoreParameters,
183): IDBObjectStore {
184 try {
185 return db.createObjectStore(storeName, options)
186 } catch (error) {
187 // Check if this is being called outside of a version change transaction
188 if (error instanceof DOMException && error.name === 'InvalidStateError') {
189 throw new Error(
190 `Cannot create object store "${storeName}": This operation is only allowed during a database upgrade. ` +
191 'Ensure you are calling createObjectStore within the onUpgrade callback of openDatabase.',
192 { cause: error },
193 )
194 }
195
196 // Check if the object store already exists
197 if (error instanceof DOMException && error.name === 'ConstraintError') {
198 throw new Error(
199 `Object store "${storeName}" already exists in the database. ` +
200 'Check the database version and only create stores when needed.',
201 { cause: error },
202 )
203 }
204
205 throw new Error(
206 `Failed to create object store "${storeName}": ${error instanceof Error ? error.message : String(error)}`,
207 { cause: error },
208 )
209 }
210}
211
212/**
213 * Executes a callback within an IndexedDB transaction.
214 *
215 * This function handles transaction lifecycle automatically:
216 * - Creates the transaction with the specified mode
217 * - Provides the transaction and object stores to the callback
218 * - Waits for both the callback and the transaction to complete (or abort)
219 * - Returns the callback's result or rejects with an error
220 *
221 * IndexedDB can commit while an async callback is still pending. If that callback
222 * later rejects, this function rejects but cannot undo the committed writes.
223 *
224 * @template T - The return type of the callback
225 * @param db - The IDBDatabase instance
226 * @param storeNames - A single store name or array of store names to include in the transaction
227 * @param mode - The transaction mode ('readonly', 'readwrite', or 'readwriteflush')
228 * @param callback - A function that performs operations within the transaction.
229 * Receives the transaction and a record of object stores keyed by name.
230 * Can be sync or async.
231 * @returns A promise that resolves to the callback's return value when the transaction completes
232 *
233 * @example
234 * ```typescript
235 * // Single store
236 * const result = await executeTransaction(db, 'todos', 'readwrite', (tx, stores) => {
237 * stores.todos.put({ id: 1, text: 'Buy milk' })
238 * return 'done'
239 * })
240 *
241 * // Multiple stores
242 * await executeTransaction(db, ['todos', 'users'], 'readwrite', (tx, stores) => {
243 * stores.todos.put({ id: 1, text: 'Task' })
244 * stores.users.put({ id: 1, name: 'Alice' })
245 * })
246 * ```
247 */
248export function executeTransaction<T>(
249 db: IDBDatabase,
250 storeNames: string | Array<string>,
251 mode: IDBTransactionMode,
252 callback: (
253 transaction: IDBTransaction,
254 stores: Record<string, IDBObjectStore>,
255 ) => T | Promise<T>,
256): Promise<T> {
257 return new Promise((resolve, reject) => {
258 const storeNamesArray = Array.isArray(storeNames)
259 ? storeNames
260 : [storeNames]
261 let transaction: IDBTransaction
262
263 try {
264 transaction = db.transaction(storeNamesArray, mode)
265 } catch (error) {
266 reject(
267 new Error(
268 `Failed to create transaction for stores [${storeNamesArray.join(', ')}]: ${error instanceof Error ? error.message : String(error)}`,
269 { cause: error },
270 ),
271 )
272 return
273 }
274
275 // Build the stores record
276 const stores: Record<string, IDBObjectStore> = {}
277 for (const storeName of storeNamesArray) {
278 try {
279 stores[storeName] = transaction.objectStore(storeName)
280 } catch (error) {
281 reject(
282 new Error(
283 `Object store "${storeName}" not found in the database. ` +
284 'Ensure the store was created during the database upgrade.',
285 { cause: error },
286 ),
287 )
288 return
289 }
290 }
291
292 // Success requires both obligations: callback result AND transaction
293 // completion. Request success alone is not a durability receipt.
294 const completed = new Promise<void>((complete, abort) => {
295 // The callback may also set native event-handler properties.
296 transaction.addEventListener('complete', () => complete())
297 transaction.addEventListener('abort', () =>
298 abort(transaction.error ?? new Error('Transaction was aborted')),
299 )
300 // Request errors normally bubble before abort. Let abort report the
301 // transaction outcome; callback rejection retains its original cause.
302 })
303 let result: T | Promise<T>
304 try {
305 result = callback(transaction, stores)
306 } catch (error) {
307 result = Promise.reject(error)
308 }
309 const callbackResult = Promise.resolve(result).catch((error) => {
310 try {
311 transaction.abort()
312 } catch {
313 // An async callback may settle after the native transaction has ended.
314 }
315 throw error
316 })
317 Promise.all([callbackResult, completed]).then(
318 ([value]) => resolve(value),
319 reject,
320 )
321 })
322}
323
324/**
325 * Retrieves all items from an object store.
326 *
327 * Uses the native `getAll()` method for efficient bulk retrieval.
328 *
329 * @template T - The type of items in the object store
330 * @param objectStore - The IDBObjectStore to read from
331 * @returns A promise that resolves to an array of all items in the store
332 *
333 * @example
334 * ```typescript
335 * await executeTransaction(db, 'todos', 'readonly', async (tx, stores) => {
336 * const allTodos = await getAll<Todo>(stores.todos)
337 * console.log('All todos:', allTodos)
338 * })
339 * ```
340 */
341export function getAll<T>(objectStore: IDBObjectStore): Promise<Array<T>> {
342 return executeRequest<Array<T>>(
343 () => objectStore.getAll(),
344 () => `Failed to get all items from object store "${objectStore.name}"`,
345 )
346}
347
348/**
349 * Retrieves all keys from an object store.
350 *
351 * Uses the native `getAllKeys()` method for efficient bulk key retrieval.
352 *
353 * @param objectStore - The IDBObjectStore to read keys from
354 * @returns A promise that resolves to an array of all keys in the store
355 *
356 * @example
357 * ```typescript
358 * await executeTransaction(db, 'todos', 'readonly', async (tx, stores) => {
359 * const allKeys = await getAllKeys(stores.todos)
360 * console.log('All keys:', allKeys)
361 * })
362 * ```
363 */
364export function getAllKeys(
365 objectStore: IDBObjectStore,
366): Promise<Array<IDBValidKey>> {
367 return executeRequest(
368 () => objectStore.getAllKeys(),
369 () => `Failed to get all keys from object store "${objectStore.name}"`,
370 )
371}
372
373/**
374 * Retrieves a single item by its key from an object store.
375 *
376 * @template T - The type of the item
377 * @param objectStore - The IDBObjectStore to read from
378 * @param key - The key of the item to retrieve
379 * @returns A promise that resolves to the item, or undefined if not found
380 *
381 * @example
382 * ```typescript
383 * await executeTransaction(db, 'todos', 'readonly', async (tx, stores) => {
384 * const todo = await getByKey<Todo>(stores.todos, 1)
385 * if (todo) {
386 * console.log('Found todo:', todo)
387 * }
388 * })
389 * ```
390 */
391export function getByKey<T>(
392 objectStore: IDBObjectStore,
393 key: IDBValidKey,
394): Promise<T | undefined> {
395 return executeRequest<T | undefined>(
396 () => objectStore.get(key),
397 () =>
398 `Failed to get item with key "${String(key)}" from object store "${objectStore.name}"`,
399 )
400}
401
402/**
403 * Writes an item to an object store using upsert semantics.
404 *
405 * If an item with the same key exists, it will be replaced.
406 * If no item with the key exists, a new one will be created.
407 *
408 * @template T - The type of the item
409 * @param objectStore - The IDBObjectStore to write to
410 * @param value - The item to write
411 * @param key - Optional key for the item. Required if the object store doesn't have a keyPath.
412 * @returns A promise that resolves to the key of the written item
413 *
414 * @example
415 * ```typescript
416 * // With keyPath (key extracted from value)
417 * await executeTransaction(db, 'todos', 'readwrite', async (tx, stores) => {
418 * const key = await put(stores.todos, { id: 1, text: 'Buy milk' })
419 * console.log('Wrote item with key:', key)
420 * })
421 *
422 * // Without keyPath (explicit key)
423 * await executeTransaction(db, 'items', 'readwrite', async (tx, stores) => {
424 * const key = await put(stores.items, { text: 'Some data' }, 'myKey')
425 * console.log('Wrote item with key:', key)
426 * })
427 * ```
428 */
429export function put<T>(
430 objectStore: IDBObjectStore,
431 value: T,
432 key?: IDBValidKey,
433): Promise<IDBValidKey> {
434 return executeRequest(
435 () =>
436 key !== undefined ? objectStore.put(value, key) : objectStore.put(value),
437 () => `Failed to write item to object store "${objectStore.name}"`,
438 )
439}
440
441/**
442 * Deletes an item by its key from an object store.
443 *
444 * @param objectStore - The IDBObjectStore to delete from
445 * @param key - The key of the item to delete
446 * @returns A promise that resolves when the item is deleted
447 *
448 * @example
449 * ```typescript
450 * await executeTransaction(db, 'todos', 'readwrite', async (tx, stores) => {
451 * await deleteByKey(stores.todos, 1)
452 * console.log('Todo deleted')
453 * })
454 * ```
455 */
456export function deleteByKey(
457 objectStore: IDBObjectStore,
458 key: IDBValidKey,
459): Promise<void> {
460 return executeRequest(
461 () => objectStore.delete(key),
462 () =>
463 `Failed to delete item with key "${String(key)}" from object store "${objectStore.name}"`,
464 )
465}
466
467/**
468 * Removes all items from an object store.
469 *
470 * @param objectStore - The IDBObjectStore to clear
471 * @returns A promise that resolves when all items are removed
472 *
473 * @example
474 * ```typescript
475 * await executeTransaction(db, 'todos', 'readwrite', async (tx, stores) => {
476 * await clear(stores.todos)
477 * console.log('All todos cleared')
478 * })
479 * ```
480 */
481export function clear(objectStore: IDBObjectStore): Promise<void> {
482 return executeRequest(
483 () => objectStore.clear(),
484 () => `Failed to clear object store "${objectStore.name}"`,
485 )
486}
487
488/**
489 * Deletes an entire IndexedDB database.
490 * A blocked request stays pending until native success or error.
491 *
492 * Use with caution - this removes the database and all of its object stores and data.
493 *
494 * @param name - The name of the database to delete
495 * @param idbFactory - Optional IDBFactory for testing/mocking
496 * @param onBlocked - Optional diagnostic callback for native blocked events. The request stays pending.
497 * @returns A promise that resolves when the database is deleted
498 *
499 * @example
500 * ```typescript
501 * await deleteDatabase('myApp')
502 * console.log('Database deleted')
503 * ```
504 */
505export function deleteDatabase(
506 name: string,
507 idbFactory?: IDBFactory,
508 onBlocked?: (event: IDBVersionChangeEvent) => void,
509): Promise<void> {
510 return new Promise((resolve, reject) => {
511 const factory = getIDBFactory(idbFactory)
512
513 let request: IDBOpenDBRequest
514 try {
515 request = factory.deleteDatabase(name)
516 } catch (error) {
517 reject(
518 new Error(
519 `Failed to delete IndexedDB database "${name}": ${error instanceof Error ? error.message : String(error)}`,
520 { cause: error },
521 ),
522 )
523 return
524 }
525
526 if (onBlocked) request.addEventListener('blocked', onBlocked)
527
528 request.onsuccess = () => {
529 resolve()
530 }
531
532 request.onerror = () => {
533 const errorMessage = request.error?.message || 'Unknown error'
534 reject(
535 new Error(
536 `Failed to delete IndexedDB database "${name}": ${errorMessage}`,
537 { cause: request.error },
538 ),
539 )
540 }
541 })
542}