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.
449 lines • 17.8 kB
text/typescript
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 (`TinyEvents`) 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 {
/**
* 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);
/**
* Enables or disables throwing an error when the maximum number of listeners is exceeded.
*
* @param {boolean} shouldThrow - If true, an error will be thrown when the max is exceeded.
*/
setThrowOnMaxListeners(shouldThrow: boolean): void;
/**
* Checks whether an error will be thrown when the max listener limit is exceeded.
*
* @returns {boolean} True if an error will be thrown, false if only a warning is shown.
*/
getThrowOnMaxListeners(): boolean;
/**
* Adds a listener to the beginning of the listeners array for the specified event.
*
* @param {string|string[]} event - Event name.
* @param {handler} handler - The callback function.
*/
prependListener(event: string | string[], handler: import("./TinyEvents.mjs").handler): void;
/**
* Adds a one-time listener to the beginning of the listeners array for the specified event.
*
* @param {string|string[]} event - Event name.
* @param {handler} handler - The callback function.
* @returns {handler[]} - The wrapped handler used internally.
*/
prependListenerOnce(event: string | string[], handler: import("./TinyEvents.mjs").handler): import("./TinyEvents.mjs").handler[];
/**
* Adds a event listener.
*
* @param {string|string[]} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
* @param {handler} handler - Callback function to be called when event fires.
*/
appendListener(event: string | string[], handler: import("./TinyEvents.mjs").handler): void;
/**
* Registers an event listener that runs only once, then is removed.
*
* @param {string|string[]} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
* @param {handler} handler - The callback function to run on event.
* @returns {handler[]} - The wrapped version of the handler.
*/
appendListenerOnce(event: string | string[], handler: import("./TinyEvents.mjs").handler): import("./TinyEvents.mjs").handler[];
/**
* Adds a event listener.
*
* @param {string|string[]} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
* @param {handler} handler - Callback function to be called when event fires.
*/
on(event: string | string[], handler: import("./TinyEvents.mjs").handler): void;
/**
* Registers an event listener that runs only once, then is removed.
*
* @param {string|string[]} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
* @param {handler} handler - The callback function to run on event.
* @returns {handler[]} - The wrapped version of the handler.
*/
once(event: string | string[], handler: import("./TinyEvents.mjs").handler): import("./TinyEvents.mjs").handler[];
/**
* Removes a previously registered event listener.
*
* @param {string|string[]} event - The name of the event to remove the handler from.
* @param {handler} handler - The specific callback function to remove.
*/
off(event: string | string[], handler: import("./TinyEvents.mjs").handler): void;
/**
* Removes all event listeners of a specific type from the element.
*
* @param {string|string[]} event - The event type to remove (e.g. 'onScrollBoundary').
*/
offAll(event: string | string[]): void;
/**
* Removes all event listeners of all types from the element.
*/
offAllTypes(): void;
/**
* Returns the number of listeners for a given event.
*
* @param {string} event - The name of the event.
* @returns {number} Number of listeners for the event.
*/
listenerCount(event: string): number;
/**
* Returns a copy of the array of listeners for the specified event.
*
* @param {string} event - The name of the event.
* @returns {handler[]} Array of listener functions.
*/
listeners(event: string): import("./TinyEvents.mjs").handler[];
/**
* Returns a copy of the array of listeners for the specified event.
*
* @param {string} event - The name of the event.
* @returns {handler[]} Array of listener functions.
*/
onceListeners(event: string): import("./TinyEvents.mjs").handler[];
/**
* Returns a copy of the internal listeners array for the specified event,
* including wrapper functions like those used by `.once()`.
* @param {string | symbol} event - The event name.
* @returns {handler[]} An array of raw listener functions.
*/
allListeners(event: string | symbol): import("./TinyEvents.mjs").handler[];
/**
* Returns an array of event names for which there are registered listeners.
*
* @returns {string[]} Array of registered event names.
*/
eventNames(): string[];
/**
* Emits an event, triggering all registered handlers for that event.
*
* @param {string} event - The event name to emit.
* @param {...any} payload - Optional data to pass to each handler.
* @returns {boolean[]} True if any listeners were called, false otherwise.
*/
emit(event: string, ...payload: any[]): boolean[];
/**
* Sets the maximum number of listeners per event before a warning is shown.
*
* @param {number} n - The maximum number of listeners.
*/
setMaxListeners(n: number): void;
/**
* Gets the maximum number of listeners allowed per event.
*
* @returns {number} The maximum number of listeners.
*/
getMaxListeners(): number;
/**
* 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;
}
//# sourceMappingURL=TinyLocalStorage.d.mts.map