var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { isArray } from '../common/types.js';
export class DBClosedError extends Error {
    constructor(dbName) {
        super(`IndexedDB database '${dbName}' is closed.`);
        this.code = 'DBClosed';
    }
}
export class IndexedDB {
    constructor(database, name) {
        this.name = name;
        this.database = null;
        this.pendingTransactions = [];
        this.database = database;
    }
    runInTransaction(store, transactionMode, dbRequestFn) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.database) {
                throw new DBClosedError(this.name);
            }
            const transaction = this.database.transaction(store, transactionMode);
            this.pendingTransactions.push(transaction);
            return new Promise((c, e) => {
                transaction.oncomplete = () => {
                    if (isArray(request)) {
                        c(request.map(r => r.result));
                    }
                    else {
                        c(request.result);
                    }
                };
                transaction.onerror = () => e(transaction.error);
                const request = dbRequestFn(transaction.objectStore(store));
            }).finally(() => this.pendingTransactions.splice(this.pendingTransactions.indexOf(transaction), 1));
        });
    }
}
