UNPKG

@quantajs/core

Version:

A compact, scalable, and developer-friendly state management library designed for any JavaScript environment. It includes a reactivity system that enables efficient and flexible data handling, making complex state management easy.

363 lines (329 loc) 11.2 kB
/** * ActionDefinition (user-facing) * - The object you pass as `actions` to createStore should match this shape. * - Inside these functions, `this` is the full runtime StoreInstance. */ export declare type ActionDefinition<S extends object, GDefs extends Record<string, (state: S) => any> = {}, A extends RawActions = {}> = { [K in keyof A]: A[K] extends (...args: infer P) => infer R ? (this: StoreInstance<S, GDefs, A>, ...args: P) => R : never; }; /** * Common migration patterns */ export declare const CommonMigrations: { /** * Add a new property with default value */ addProperty<T extends Record<string, any>, K extends string, V>(property: K, defaultValue: V): MigrationFunction<T & Record<K, V>>; /** * Remove a property */ removeProperty<T extends Record<string, any>, K extends keyof T>(property: K): MigrationFunction<Omit<T, K>>; /** * Rename a property */ renameProperty<T extends Record<string, any>, K extends keyof T, N extends string>(oldName: K, newName: N): MigrationFunction<Omit<T, K> & Record<N, T[K]>>; /** * Transform a property value */ transformProperty<T extends Record<string, any>, K extends keyof T>(property: K, transform: (value: T[K]) => any): MigrationFunction<T>; }; export declare const computed: <G>(getter: () => G) => { readonly value: G; }; export declare const createLogger: (config?: Partial<LoggerConfig>) => Logger; /** * Create a migration manager from a configuration object */ export declare function createMigrationManager<T = any>(config: Pick<PersistenceConfig<T>, 'migrations' | 'version'>): MigrationManager<T>; export declare function createPersistenceManager<T extends Record<string, any>>(getState: () => T, setState: (newState: Partial<T>) => void, notifySubscribers: () => void, config: PersistenceConfig<T>, storeName?: string): PersistenceManager; export declare const createStore: <S extends object, GDefs extends Record<string, (state: S) => any> = {}, A extends RawActions = {}>(name: string, options: StoreOptions<S, GDefs, A>) => StoreInstance<S, GDefs, A>; /** * GetterDefinitions: user writes getter functions in this shape. * Example: * getters: { * filteredTasks: (state) => state.tasks.filter(...) * } * * GDefs maps getter name -> (state: S) => ReturnType */ export declare type GetterDefinitions<S extends object, GDefs extends Record<string, (state: S) => any> = {}> = { [K in keyof GDefs]: (state: S) => ReturnType<GDefs[K]>; }; export declare class IndexedDBAdapter implements PersistenceAdapter { key: string; private dbName; private storeName; private version; constructor(key: string, dbName?: string, storeName?: string, version?: number); read(): Promise<any>; write(data: any): Promise<void>; remove(): Promise<void>; private openDB; } /** * InferActions (runtime/action methods on flattened store) * - Converts the raw action signatures into functions whose `this` is the StoreInstance. */ export declare type InferActions<S extends object, GDefs extends Record<string, (state: S) => any> = {}, A extends RawActions = {}> = { [K in keyof A]: A[K] extends (...args: infer P) => infer R ? (this: StoreInstance<S, GDefs, A>, ...args: P) => R : never; }; /** * InferGetterReturnTypesFromDefs * - Derive the *runtime* getter value types from the getter function defs. * - This is what the flattened store exposes as properties. */ declare type InferGetterReturnTypesFromDefs<S extends object, GDefs extends Record<string, (state: S) => any> = {}> = { [K in keyof GDefs]: GDefs[K] extends (s: S) => infer R ? R : never; }; export declare class LocalStorageAdapter implements PersistenceAdapter { key: string; constructor(key: string); read(): any; write(data: any): void; remove(): void; subscribe(callback: (data: any) => void): () => void; } export declare class Logger { private config; private isNode; private hasConsole; constructor(config?: Partial<LoggerConfig>); /** * Detect if running in Node.js environment */ private detectNodeEnvironment; /** * Detect if console is available */ private detectConsole; /** * Get timestamp string */ private getTimestamp; /** * Get color codes for different log levels (Node.js only) */ private getColorCode; /** * Reset color code (Node.js only) */ private getResetCode; /** * Get level name */ private getLevelName; /** * Format message with prefix, timestamp, and colors */ private formatMessage; /** * Safe console method execution */ private safeConsoleCall; /** * Check if logging is enabled for the given level */ private shouldLog; /** * Debug level logging */ debug(message: string, ...args: any[]): void; /** * Info level logging (alias for log) */ info(message: string, ...args: any[]): void; /** * Standard logging */ log(message: string, ...args: any[]): void; /** * Warning level logging */ warn(message: string, ...args: any[]): void; /** * Error level logging */ error(message: string, ...args: any[]): void; /** * Update logger configuration */ configure(config: Partial<LoggerConfig>): void; /** * Set log level */ setLevel(level: LogLevel): void; /** * Get current log level */ getLevel(): LogLevel; /** * Create a child logger with a prefix */ child(prefix: string): Logger; } export declare const logger: Logger; declare interface LoggerConfig { level: LogLevel; prefix?: string; timestamp?: boolean; colors?: boolean; formatters?: { [key: string]: (message: string, ...args: any[]) => string; }; } /** * logger utility that works across all JavaScript environments */ export declare enum LogLevel { DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3, SILENT = 4 } /** * Migration definition */ declare interface MigrationDefinition<T = any> { version: number; migrate: MigrationFunction<T>; description?: string; } /** * Migration function type */ declare type MigrationFunction<T = any> = (data: any) => T; /** * Migration manager for handling schema changes */ export declare class MigrationManager<T = any> { private migrations; constructor(migrations?: MigrationDefinition<T>[]); /** * Add a migration function for a specific version */ addMigration(version: number, migrate: MigrationFunction<T>): void; /** * Remove a migration for a specific version */ removeMigration(version: number): void; /** * Get all available migration versions */ getVersions(): number[]; /** * Check if a migration exists for a specific version */ hasMigration(version: number): boolean; /** * Get the highest migration version */ getHighestVersion(): number; /** * Apply migrations from current version to target version */ migrate(data: any, fromVersion: number, toVersion: number): any; /** * Validate that all migrations can be applied successfully */ validateMigrations(): { valid: boolean; errors: string[]; }; } export declare interface PersistedData<T = any> { data: T; version: number; timestamp: number; storeName?: string; checksum?: string; } export declare interface PersistenceAdapter { key: string; read(): Promise<any> | any; write(data: any): Promise<void> | void; remove(): Promise<void> | void; subscribe?(callback: (data: any) => void): () => void; } export declare interface PersistenceConfig<T = any> { adapter: PersistenceAdapter; serialize?: (data: T) => string; deserialize?: (data: string) => T; migrations?: Record<number, (data: any) => any>; version?: number; debounceMs?: number; include?: Array<keyof T>; exclude?: Array<keyof T>; transform?: { in?: (data: any) => any; out?: (data: any) => any; }; onError?: (error: Error, operation: 'read' | 'write' | 'remove' | 'watch-setup') => void; validator?: (data: any) => boolean; } export declare interface PersistenceManager { save(): Promise<void>; load(): Promise<void>; clear(): Promise<void>; getAdapter(): PersistenceAdapter; isRehydrated(): boolean; destroy(): void; } /** * Raw actions shape (user-provided action signatures) */ export declare type RawActions = Record<string, (...args: any[]) => any>; export declare const reactive: <S>(target: S) => S; export declare class SessionStorageAdapter implements PersistenceAdapter { key: string; constructor(key: string); read(): any; write(data: any): void; remove(): void; subscribe(callback: (data: any) => void): () => void; } export declare type StateDefinition<S> = () => S; /** * StoreInstance: * - Exposes state keys (S) * - Exposes getter values (derived from GDefs) * - Exposes action methods (InferActions) * - Includes runtime helpers (state/getters/actions refs, subscribe, $reset etc.) */ export declare type StoreInstance<S extends object, GDefs extends Record<string, (state: S) => any> = {}, A extends RawActions = {}> = S & InferGetterReturnTypesFromDefs<S, GDefs> & InferActions<S, GDefs, A> & { state: S; getters: { [K in keyof GDefs]: any; }; actions: A; subscribe: (callback: StoreSubscriber) => () => void; $reset: () => void; $persist?: PersistenceManager; $destroy?: () => void; }; export declare type StoreOptions<S extends object, GDefs extends Record<string, (state: S) => any> = {}, A extends RawActions = {}> = { state: StateDefinition<S>; getters?: GetterDefinitions<S, GDefs>; actions?: ActionDefinition<S, GDefs, A>; persist?: PersistenceConfig<S>; }; export declare type StoreSubscriber<S = any> = (snapshot?: S) => void; export declare function useStore<S extends object, G extends Record<string, any>, A extends RawActions>(name: string): StoreInstance<S, G, A>; export declare const watch: <T>(source: () => T, callback: (value: T, oldValue?: T) => void, options?: WatchOptions) => () => void; /** * Options for configuring a watcher. * * * @property {boolean} [deep] * Whether to perform deep watching (i.e., recursively track nested object changes). * When `true`, changes inside nested structures are detected using polling and JSON diffing. * * @property {boolean} [immediate] * Whether to invoke the watcher callback immediately upon setup, * rather than waiting for the first change. */ declare interface WatchOptions { deep?: boolean; immediate?: boolean; } export { }