UNPKG

@dfinity/auth-client

Version:

JavaScript and TypeScript library to provide a simple integration with an IC Internet Identity

95 lines 2.94 kB
import { IdbKeyVal } from "./db.js"; export const KEY_STORAGE_KEY = 'identity'; export const KEY_STORAGE_DELEGATION = 'delegation'; export const KEY_VECTOR = 'iv'; // Increment if any fields are modified export const DB_VERSION = 1; export const isBrowser = typeof window !== 'undefined'; /** * Legacy implementation of AuthClientStorage, for use where IndexedDb is not available */ export class LocalStorage { prefix; _localStorage; constructor(prefix = 'ic-', _localStorage) { this.prefix = prefix; this._localStorage = _localStorage; } get(key) { return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key)); } set(key, value) { this._getLocalStorage().setItem(this.prefix + key, value); return Promise.resolve(); } remove(key) { this._getLocalStorage().removeItem(this.prefix + key); return Promise.resolve(); } _getLocalStorage() { if (this._localStorage) { return this._localStorage; } const ls = typeof window === 'undefined' ? typeof global === 'undefined' ? typeof self === 'undefined' ? undefined : self.localStorage : global.localStorage : window.localStorage; if (!ls) { throw new Error('Could not find local storage.'); } return ls; } } /** * IdbStorage is an interface for simple storage of string key-value pairs built on {@link IdbKeyVal} * * It replaces {@link LocalStorage} * @see implements {@link AuthClientStorage} */ export class IdbStorage { #options; /** * @param options - DBCreateOptions * @param options.dbName - name for the indexeddb database * @param options.storeName - name for the indexeddb Data Store * @param options.version - version of the database. Increment to safely upgrade * @example * ```ts * const storage = new IdbStorage({ dbName: 'my-db', storeName: 'my-store', version: 2 }); * ``` */ constructor(options) { this.#options = options ?? {}; } // Initializes a KeyVal on first request initializedDb; get _db() { return new Promise(resolve => { if (this.initializedDb) { resolve(this.initializedDb); return; } IdbKeyVal.create(this.#options).then(db => { this.initializedDb = db; resolve(db); }); }); } async get(key) { const db = await this._db; return await db.get(key); // return (await db.get<string>(key)) ?? null; } async set(key, value) { const db = await this._db; await db.set(key, value); } async remove(key) { const db = await this._db; await db.remove(key); } } //# sourceMappingURL=storage.js.map