import { navigator as localNavigator } from "../../../shared/src/navigator.js";
import { promiseVoid } from "../../../shared/src/resolved-promises.js";
import { IDBStore } from "./idb-store.js";
import { dropMemStore, MemStore } from "./mem-store.js";
class IDBStoreWithMemFallback {
  #lc;
  #name;
  #store;
  constructor(lc, name) {
    this.#lc = lc;
    this.#name = name;
    this.#store = new IDBStore(name);
  }
  read() {
    return this.#withBrainTransplant((s) => s.read());
  }
  write() {
    return this.#withBrainTransplant((s) => s.write());
  }
  async #withBrainTransplant(f) {
    try {
      return await f(this.#store);
    } catch (e) {
      if (isFirefoxPrivateBrowsingError(e)) {
        if (this.#store instanceof IDBStore) {
          this.#lc.info?.(
            "Switching to MemStore because of Firefox private browsing error"
          );
          this.#store = new MemStore(this.#name);
        }
        return f(this.#store);
      }
      throw e;
    }
  }
  close() {
    return this.#store.close();
  }
  get closed() {
    return this.#store.closed;
  }
}
function isFirefoxPrivateBrowsingError(e) {
  return isFirefox() && e instanceof DOMException && e.name === "InvalidStateError" && e.message === "A mutation operation was attempted on a database that did not allow mutations.";
}
function isFirefox() {
  return localNavigator?.userAgent?.includes("Firefox") ?? false;
}
function newIDBStoreWithMemFallback(lc, name) {
  if (isFirefox()) {
    return new IDBStoreWithMemFallback(lc, name);
  }
  return new IDBStore(name);
}
function dropIDBStoreWithMemFallback(name) {
  if (!isFirefox()) {
    return dropIDBStore(name);
  }
  try {
    return dropIDBStore(name);
  } catch (e) {
    if (isFirefoxPrivateBrowsingError(e)) {
      return dropMemStore(name);
    }
  }
  return promiseVoid;
}
function dropIDBStore(name) {
  return new Promise((resolve, reject) => {
    const req = indexedDB.deleteDatabase(name);
    req.onsuccess = () => resolve();
    req.onerror = () => reject(req.error);
  });
}
export {
  IDBStoreWithMemFallback,
  dropIDBStoreWithMemFallback,
  newIDBStoreWithMemFallback
};
//# sourceMappingURL=idb-store-with-mem-fallback.js.map
