UNPKG

tiny-essentials

Version:

Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.

322 lines 12.2 kB
export default TinyLocalStorage; /** * A function that encodes a value into a serializable JSON-compatible format. */ export type EncodeFn = (value: any, encodeSpecialJson: encodeSpecialJson) => any; /** * An object that defines how to check and decode a specific serialized type. */ export type DecodeFn = { /** * - Checks if the value matches the custom encoded structure. */ check: (value: any) => any; /** * - Decodes the structure back into its original form. */ decode: (value: any, decodeSpecialJson: decodeSpecialJson) => any; }; /** * Encodes extended JSON-compatible structures recursively. */ export type encodeSpecialJson = (value: any) => any; /** * Decodes extended JSON-compatible structures recursively. */ export type decodeSpecialJson = (value: any) => any; /** * Represents a value that can be safely stored and restored using JSON in `localStorage`, * including structures like arrays, plain objects, Map and Set. * * - `Record<string|number|symbol, any>` → plain object (e.g., `{ key: value }`) * - `any[]` → array of any JSON-serializable values * - `Map<string|number|symbol, any>` → converted to `{ __map__: true, data: [[k, v], ...] }` * - `Set<any>` → converted to `{ __set__: true, data: [v1, v2, ...] }` * * These conversions allow complex structures to be restored after JSON serialization. */ export type LocalStorageJsonValue = (Record<string | number | symbol, any> | any[] | Map<string | number | symbol, any> | Set<any>); /** * A function that encodes a value into a serializable JSON-compatible format. * * @callback EncodeFn * @param {any} value - The value to encode. * @param {encodeSpecialJson} encodeSpecialJson - Recursive encoder helper. * @returns {any} The encoded value. */ /** * An object that defines how to check and decode a specific serialized type. * * @typedef {Object} DecodeFn * @property {(value: any) => any} check - Checks if the value matches the custom encoded structure. * @property {(value: any, decodeSpecialJson: decodeSpecialJson) => any} decode - Decodes the structure back into its original form. */ /** * Encodes extended JSON-compatible structures recursively. * @callback encodeSpecialJson * @param {any} value * @returns {any} */ /** * Decodes extended JSON-compatible structures recursively. * @callback decodeSpecialJson * @param {any} value * @returns {any} */ /** * Represents a value that can be safely stored and restored using JSON in `localStorage`, * including structures like arrays, plain objects, Map and Set. * * - `Record<string|number|symbol, any>` → plain object (e.g., `{ key: value }`) * - `any[]` → array of any JSON-serializable values * - `Map<string|number|symbol, any>` → converted to `{ __map__: true, data: [[k, v], ...] }` * - `Set<any>` → converted to `{ __set__: true, data: [v1, v2, ...] }` * * These conversions allow complex structures to be restored after JSON serialization. * * @typedef {(Record<string|number|symbol, any> | any[] | Map<string|number|symbol, any> | Set<any>)} LocalStorageJsonValue */ /** * A powerful wrapper for Web Storage (`localStorage` or `sessionStorage`) that supports * type-safe methods and full JSON-like structure encoding and decoding. * * `TinyLocalStorage` allows storing and retrieving complex types such as: * - `Map`, `Set` * - `Date`, `RegExp` * - `BigInt`, `Symbol` * - `undefined`, `null` * - Plain objects and arrays * * Includes: * - Type-specific `set` and `get` methods (`setDate`, `getBool`, etc.) * - `getValue()` to retrieve any structure regardless of type * - Auto-encoding/decoding with support for custom types via `registerJsonType` * - Built-in event system to listen for changes * - Optional fallback values on decoding errors * * Supports registering and unregistering custom types via: * - `registerJsonType(...)` * - `deleteJsonType(...)` * * This class is suitable for applications that require structured persistence in the browser. */ declare class TinyLocalStorage extends EventEmitter<any> { /** * Checks whether a JSON-serializable type is already registered. * * @param {any} type - The type identifier, which can be a string (e.g., `"bigint"`, `"symbol"`) * or a reference to a class/constructor function. * @returns {boolean} True if the type has both an encoder and decoder registered. */ static hasJsonType(type: any): boolean; /** * Registers a new JSON-serializable type with its encoder and decoder. * * @param {any} type - The type identifier, which can be a string (e.g., `"bigint"`, `"symbol"`) * or a reference to a class/constructor function. * @param {EncodeFn} encodeFn - A function that receives a value of this type and returns a JSON-safe representation. * @param {DecodeFn} decodeFn - An object with `check(value)` to identify this type and `decode(value)` to restore it. * @param {boolean} [freezeType=false] - If true, prevents this type from being unregistered later. * @throws {Error} Throws an error if the type is frozen and cannot be registered. */ static registerJsonType(type: any, encodeFn: EncodeFn, decodeFn: DecodeFn, freezeType?: boolean): void; /** * Unregisters a previously registered custom type from the encoding/decoding system. * * @param {any} type - The primitive name or constructor reference used in the registration. * @returns {boolean} Returns true if the type existed and was removed, or false if it wasn't found. * @throws {Error} Throws an error if the type is frozen and cannot be unregistered. */ static deleteJsonType(type: any): boolean; static encodeSpecialJson(value: any): any; static decodeSpecialJson(value: any): any; /** * Initializes the TinyLocalStorage instance and sets up cross-tab sync. * * Adds listener for the native `storage` event to support tab synchronization. * @param {string} [dbName] - Unique database name. */ constructor(dbName?: string); /** * Updates the version of the storage and triggers migration if needed. * * @param {number} version - Desired version of the database. * @param {(oldVersion: number, newVersion: number) => void} onUpgrade - Callback to perform migration logic. * @throws {Error} If the database key has not been initialized. * @throws {TypeError} If `version` is not a valid positive number. * @throws {TypeError} If `onUpgrade` is not a function. */ updateStorageVersion(version: number, onUpgrade: (oldVersion: number, newVersion: number) => void): void; /** * Gets the current database key used in localStorage. * * @returns {string|null} The database key, or null if not set. */ getDbKey(): string | null; /** * Gets the current version of the database. * * @returns {number} The current version number. */ getVersion(): number; /** * Defines a custom storage interface (e.g. `sessionStorage`). * * @param {Storage} localstorage - A valid Storage object (localStorage or sessionStorage). */ setLocalStorage(localstorage: Storage): void; /** * Checks if `localStorage` is supported by the current environment. * * @returns {boolean} True if `localStorage` exists, false otherwise. */ localStorageExists(): boolean; /** * Stores a JSON-compatible value in `localStorage`. * * Automatically serializes nested `Map` and `Set` instances. * * @param {string} name - The key under which to store the data. * @param {LocalStorageJsonValue} data - The data to be serialized and stored. */ setJson(name: string, data: LocalStorageJsonValue): void; /** * Retrieves and parses a JSON value from `localStorage`. * * Automatically restores nested `Map` and `Set` instances. * * @param {string} name - The key to retrieve. * @param {'array'|'obj'|'map'|'set'|'null'} [defaultData] - Default fallback format if value is invalid. * @returns {LocalStorageJsonValue|null} The parsed object or fallback. */ getJson(name: string, defaultData?: "array" | "obj" | "map" | "set" | "null"): LocalStorageJsonValue | null; /** * Stores a Date in localStorage. * @param {string} name * @param {Date} data */ setDate(name: string, data: Date): void; /** * Retrieves a Date from localStorage. * @param {string} name * @returns {Date|null} */ getDate(name: string): Date | null; /** * Stores a RegExp in localStorage. * @param {string} name * @param {RegExp} data */ setRegExp(name: string, data: RegExp): void; /** * Retrieves a RegExp from localStorage. * @param {string} name * @returns {RegExp|null} */ getRegExp(name: string): RegExp | null; /** * Stores a BigInt in localStorage. * @param {string} name * @param {bigint} data */ setBigInt(name: string, data: bigint): void; /** * Retrieves a BigInt from localStorage. * @param {string} name * @returns {bigint|null} */ getBigInt(name: string): bigint | null; /** * Stores a Symbol in localStorage. * Only global symbols (`Symbol.for`) will preserve the key. * @param {string} name * @param {symbol} data */ setSymbol(name: string, data: symbol): void; /** * Retrieves a Symbol from localStorage. * @param {string} name * @returns {symbol|null} */ getSymbol(name: string): symbol | null; /** * Retrieves a value from `localStorage`. * * @param {string} name - The key to retrieve. * @returns {any} The stored value or null if not found. */ getValue(name: string): any; /** * Stores a raw string value in `localStorage`. * * @param {string} name - The key to use. * @param {any} data - The data to store. */ setItem(name: string, data: any): void; /** * Retrieves a raw string value from `localStorage`. * * @param {string} name - The key to retrieve. * @returns {string|null} The stored value or null if not found. */ getItem(name: string): string | null; /** * Stores a string in `localStorage`, ensuring the data is a valid string. * * @param {string} name - The key to store the string under. * @param {string} data - The string to store. */ setString(name: string, data: string): void; /** * Retrieves a string value from `localStorage`. * * @param {string} name - The key to retrieve. * @returns {string|null} The string if valid, or null. */ getString(name: string): string | null; /** * Stores a number value in `localStorage`. * * @param {string} name - The key to use. * @param {number} data - The number to store. */ setNumber(name: string, data: number): void; /** * Retrieves a number from `localStorage`. * * @param {string} name - The key to retrieve. * @returns {number|null} The number or null if invalid. */ getNumber(name: string): number | null; /** * Stores a boolean value in `localStorage`. * * @param {string} name - The key to use. * @param {boolean} data - The boolean value to store. */ setBool(name: string, data: boolean): void; /** * Retrieves a boolean value from `localStorage`. * * @param {string} name - The key to retrieve. * @returns {boolean|null} The boolean or null if invalid. */ getBool(name: string): boolean | null; /** * Removes a value from `localStorage`. * * @param {string} name - The key to remove. */ removeItem(name: string): void; /** * Clears all data from `localStorage`. */ clearLocalStorage(): void; /** * Destroys the storage instance by removing the storage event listener. */ destroy(): void; #private; } import { EventEmitter } from 'events'; //# sourceMappingURL=TinyLocalStorage.d.mts.map