|
import { w as wrap, r as replaceTraps } from './wrap-idb-value.js'; |
|
export { u as unwrap, w as wrap } from './wrap-idb-value.js'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { |
|
const request = indexedDB.open(name, version); |
|
const openPromise = wrap(request); |
|
if (upgrade) { |
|
request.addEventListener('upgradeneeded', (event) => { |
|
upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); |
|
}); |
|
} |
|
if (blocked) { |
|
request.addEventListener('blocked', (event) => blocked( |
|
|
|
event.oldVersion, event.newVersion, event)); |
|
} |
|
openPromise |
|
.then((db) => { |
|
if (terminated) |
|
db.addEventListener('close', () => terminated()); |
|
if (blocking) { |
|
db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event)); |
|
} |
|
}) |
|
.catch(() => { }); |
|
return openPromise; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
function deleteDB(name, { blocked } = {}) { |
|
const request = indexedDB.deleteDatabase(name); |
|
if (blocked) { |
|
request.addEventListener('blocked', (event) => blocked( |
|
|
|
event.oldVersion, event)); |
|
} |
|
return wrap(request).then(() => undefined); |
|
} |
|
|
|
const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; |
|
const writeMethods = ['put', 'add', 'delete', 'clear']; |
|
const cachedMethods = new Map(); |
|
function getMethod(target, prop) { |
|
if (!(target instanceof IDBDatabase && |
|
!(prop in target) && |
|
typeof prop === 'string')) { |
|
return; |
|
} |
|
if (cachedMethods.get(prop)) |
|
return cachedMethods.get(prop); |
|
const targetFuncName = prop.replace(/FromIndex$/, ''); |
|
const useIndex = prop !== targetFuncName; |
|
const isWrite = writeMethods.includes(targetFuncName); |
|
if ( |
|
|
|
!(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || |
|
!(isWrite || readMethods.includes(targetFuncName))) { |
|
return; |
|
} |
|
const method = async function (storeName, ...args) { |
|
|
|
const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); |
|
let target = tx.store; |
|
if (useIndex) |
|
target = target.index(args.shift()); |
|
|
|
|
|
|
|
|
|
|
|
return (await Promise.all([ |
|
target[targetFuncName](...args), |
|
isWrite && tx.done, |
|
]))[0]; |
|
}; |
|
cachedMethods.set(prop, method); |
|
return method; |
|
} |
|
replaceTraps((oldTraps) => ({ |
|
...oldTraps, |
|
get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), |
|
has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop), |
|
})); |
|
|
|
export { deleteDB, openDB }; |
|
|