import { ModernIDB } from "./ModernIDB.ts"; import { VersionChangeManager } from "./VersionChangeManager.ts"; /** * IDB supports "readonly", "readwrite", and "versionchange" transaction modes, * but "versionchange" can only be initiated automatically during DB upgrade. */ export type TransactionMode = "readonly" | "readwrite"; export type ModernIDBState = "open" | "opening" | "closed"; export type ModernIDBSchema = { [key: string]: unknown; }; export type ModernIDBIndexes = { [K in keyof Schema]?: string; }; export type VersionChangeHandlerProps< Schema extends ModernIDBSchema, IndexNames extends ModernIDBIndexes, > = { event: IDBVersionChangeEvent; manager: VersionChangeManager; db: ModernIDB; }; export type VersionChangeHandler< Schema extends ModernIDBSchema, IndexNames extends ModernIDBIndexes, > = (props: VersionChangeHandlerProps) => void; export type BlockingHandlerProps< Schema extends ModernIDBSchema, IndexNames extends ModernIDBIndexes, > = { event: IDBVersionChangeEvent; db: ModernIDB; }; export type BlockingHandler< Schema extends ModernIDBSchema, IndexNames extends ModernIDBIndexes, > = (props: BlockingHandlerProps) => void; export type OpenRequestHandlers< Schema extends ModernIDBSchema, IndexNames extends ModernIDBIndexes, > = { /** * Called when the database is initialized from scratch. * * Should be used to set up all required stores and indexes. * * If error is thrown in this handler, the version change transaction will * be aborted. * * @example * * ```ts * onInit({ manager }) { * const store = manager.createObjectStore("items", { keyPath: "id" }); * store.createIndex("createdTs", "createdTs"); * * console.info("DB initialized."); * }, * ``` */ onInit?: VersionChangeHandler; /** * Called when there is an existing IDB database present, but is is of a lower * version than the latest. * * If error is thrown inside this handler, the version change transaction * will be aborted. * * @example * ```ts * onUpgrade({ manager, event }) { * switch (event.oldVersion) { * case 1: { * // We need a `settings` store in v2, but it did't exist in v1 * const store = manager.createObjectStore("settings", { keyPath: "id" }); * store.createIndex("createdTs", "createdTs"); * } * * default: { * console.info(`Migration from DB v${event.oldVersion} complete.`); * } * } * } * ``` */ onUpgrade?: VersionChangeHandler; /** * If a new connection opens which requests a higher version number than * is the current version number, a `versionchange` event will be dispatched * on the IDBDatabase instance. This handler can specify desired behaviour. * For example, you might want to close currently connected connections * to allow the version change to proceed. */ onBlocking?: BlockingHandler; }; type ValidKeyValue = string | number | Date; export type KeyPath = T extends { [key: string]: unknown } ? { [K in keyof T]: K extends string ? T[K] extends ValidKeyValue ? `${K}` : `${K}.${KeyPath}` : never; }[keyof T] : never; export type AnyModernIDB = ModernIDB;