import BaseDexie, { Table } from "dexie"; import { encrypted, Encryption } from "@pvermeer/dexie-encrypted-addon"; import { Account, AccountsSchema } from "./tables/accounts"; import { Contact, ContactSchema } from "./tables/contacts"; import { Log, LogSchema } from "./tables/logs"; import { MASTER_SETTINGS_KEY, Settings, SettingsSchema, } from "./tables/settings"; import { Temp, TempSchema } from "./tables/temp"; import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app"; // Define types for tables that hold sensitive and non-sensitive data type SensitiveTables = { accounts: Table }; type NonsensitiveTables = { contacts: Table; logs: Table; settings: Table; temp: Table; }; // Using 'unknown' instead of 'any' for stricter typing and to avoid TypeScript warnings export type SensitiveDexie = BaseDexie & T; export type NonsensitiveDexie = BaseDexie & T; // Initialize Dexie databases for sensitive and non-sensitive data export const accountsDB = new BaseDexie("TimeSafariAccounts") as SensitiveDexie; export const db = new BaseDexie("TimeSafari") as NonsensitiveDexie; // Manage the encryption key. If not present in localStorage, create and store it. const secret = localStorage.getItem("secret") || Encryption.createRandomEncryptionKey(); if (!localStorage.getItem("secret")) localStorage.setItem("secret", secret); // Apply encryption to the sensitive database using the secret key encrypted(accountsDB, { secretKey: secret }); // Define the schemas for our databases // Only the tables with index modifications need listing. https://dexie.org/docs/Tutorial/Design#database-versioning accountsDB.version(1).stores(AccountsSchema); // v1 also had contacts & settings // v2 added Log db.version(2).stores({ ...ContactSchema, ...LogSchema, ...SettingsSchema, }); // v3 added Temp db.version(3).stores(TempSchema); // Event handler to initialize the non-sensitive database with default settings db.on("populate", async () => { await db.settings.add({ id: MASTER_SETTINGS_KEY, apiServer: DEFAULT_ENDORSER_API_SERVER, }); });