All files / coherent.js/packages/core/src/state state-persistence.js

74.54% Statements 448/601
76.23% Branches 77/101
74.41% Functions 32/43
74.54% Lines 448/601

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 6891x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 23x 23x   1x 29x 29x 29x 29x       29x   1x 29x 29x 29x 29x 29x       29x   1x 3x 3x 3x 3x 3x       3x   1x                   1x   1x 1x 1x 1x 1x 4x 4x   1x 5x 5x 5x 5x       5x   1x 4x 4x 4x 4x 4x       4x   1x                     1x                   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                                   1x 1x                                 1x   1x                                       1x                                       1x                                     1x   1x 1x 1x 1x 1x 8x 8x 8x   1x 1x 1x   1x 1x 1x 1x   1x       1x       1x   1x 1x 1x 1x 1x 1x 3x 3x   1x 4x 4x 394x 394x 394x 394x 4x 4x   1x 2x 2x 2x 198x 198x 198x 198x 2x 2x 1x   1x 1x 1x 1x 1x 36x 36x 36x 23x 36x 4x 36x 1x 36x 8x 36x   36x 36x   1x 1x 1x 1x 1x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x   36x 36x   36x 36x 36x   36x 36x 36x 36x 36x 36x 36x   36x 36x 2x 2x 4x 4x 4x 2x 2x 2x   34x 36x 2x 2x 2x 2x 2x 2x   32x 36x   36x 36x 36x 36x 36x 39x 3x 3x 3x 3x   36x 36x 36x   36x 36x 36x 36x 36x 36x 36x   36x   36x 39x 4x 4x   34x   34x 39x 5x 5x   34x 39x         39x 2x 2x 2x 2x 2x 39x   36x 36x 36x 36x 36x 36x 36x   15x 36x 2x 2x   15x   15x 36x 4x 4x 2x 2x 2x 4x   13x 36x 2x 2x 2x 2x       11x   11x 36x 2x 2x   11x 36x             36x   36x 36x 36x 36x 36x 36x 2x 2x 2x   36x 36x 36x 36x 36x 36x 41x 2x 2x 2x     41x 41x   36x 36x 36x 36x 36x 36x 12x 12x   36x 36x 36x 36x 36x 36x 28x   28x 1x 1x   28x   28x   28x 20x 20x 28x   36x 36x 36x 36x 36x 1x 1x 1x   1x     1x   36x 36x 36x 36x 1x 1x   36x 36x 36x 36x       36x 36x 36x 36x 35x 35x 12x 12x 12x 12x 12x 23x 35x   36x 36x                     36x 36x 28x 28x   36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 3x 3x 36x 36x   1x 1x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 22x 22x   1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x  
/**
 * @fileoverview State Persistence for Coherent.js
 * Provides persistent state management with multiple storage backends
 * @module @coherentjs/core/state/state-persistence
 */
 
/**
 * @typedef {'localStorage'|'sessionStorage'|'indexedDB'|'memory'} StorageType
 */
 
/**
 * @typedef {Object} PersistenceOptions
 * @property {StorageType} [storage='localStorage'] - Storage backend to use
 * @property {string} [key='coherent-state'] - Storage key prefix
 * @property {boolean} [debounce=true] - Debounce state saves
 * @property {number} [debounceDelay=300] - Debounce delay in ms
 * @property {Function} [serialize=JSON.stringify] - Serialization function
 * @property {Function} [deserialize=JSON.parse] - Deserialization function
 * @property {Array<string>} [include] - Keys to include (whitelist)
 * @property {Array<string>} [exclude] - Keys to exclude (blacklist)
 * @property {boolean} [encrypt=false] - Encrypt stored data
 * @property {string} [encryptionKey] - Encryption key
 * @property {Function} [onSave] - Callback when state is saved
 * @property {Function} [onLoad] - Callback when state is loaded
 * @property {Function} [onError] - Error callback
 * @property {boolean} [versioning=false] - Enable versioning
 * @property {string} [version='1.0.0'] - Current version
 * @property {Function} [migrate] - Migration function for version changes
 * @property {number} [ttl] - Time to live in milliseconds
 * @property {boolean} [crossTab=false] - Enable cross-tab synchronization
 */
 
/**
 * Storage adapter interface
 * @interface StorageAdapter
 */
 
/**
 * LocalStorage adapter
 */
class LocalStorageAdapter {
  constructor() {
    this.available = typeof localStorage !== 'undefined';
  }
 
  async get(key) {
    if (!this.available) return null;
    try {
      return localStorage.getItem(key);
    } catch (error) {
      console.error('LocalStorage get error:', error);
      return null;
    }
  }
 
  async set(key, value) {
    if (!this.available) return false;
    try {
      localStorage.setItem(key, value);
      return true;
    } catch (error) {
      console.error('LocalStorage set error:', error);
      return false;
    }
  }
 
  async remove(key) {
    if (!this.available) return false;
    try {
      localStorage.removeItem(key);
      return true;
    } catch (error) {
      console.error('LocalStorage remove error:', error);
      return false;
    }
  }
 
  async clear() {
    if (!this.available) return false;
    try {
      localStorage.clear();
      return true;
    } catch (error) {
      console.error('LocalStorage clear error:', error);
      return false;
    }
  }
}
 
/**
 * SessionStorage adapter
 */
class SessionStorageAdapter {
  constructor() {
    this.available = typeof sessionStorage !== 'undefined';
  }
 
  async get(key) {
    if (!this.available) return null;
    try {
      return sessionStorage.getItem(key);
    } catch (error) {
      console.error('SessionStorage get error:', error);
      return null;
    }
  }
 
  async set(key, value) {
    if (!this.available) return false;
    try {
      sessionStorage.setItem(key, value);
      return true;
    } catch (error) {
      console.error('SessionStorage set error:', error);
      return false;
    }
  }
 
  async remove(key) {
    if (!this.available) return false;
    try {
      sessionStorage.removeItem(key);
      return true;
    } catch (error) {
      console.error('SessionStorage remove error:', error);
      return false;
    }
  }
 
  async clear() {
    if (!this.available) return false;
    try {
      sessionStorage.clear();
      return true;
    } catch (error) {
      console.error('SessionStorage clear error:', error);
      return false;
    }
  }
}
 
/**
 * IndexedDB adapter
 */
class IndexedDBAdapter {
  constructor(dbName = 'coherent-db', storeName = 'state') {
    this.dbName = dbName;
    this.storeName = storeName;
    this.available = typeof indexedDB !== 'undefined';
    this.db = null;
  }
 
  async init() {
    if (!this.available) return false;
    if (this.db) return true;
 
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, 1);
 
      request.onerror = () => {
        console.error('IndexedDB open error:', request.error);
        reject(request.error);
      };
 
      request.onsuccess = () => {
        this.db = request.result;
        resolve(true);
      };
 
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains(this.storeName)) {
          db.createObjectStore(this.storeName);
        }
      };
    });
  }
 
  async get(key) {
    if (!this.available) return null;
    await this.init();
 
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([this.storeName], 'readonly');
      const store = transaction.objectStore(this.storeName);
      const request = store.get(key);
 
      request.onerror = () => {
        console.error('IndexedDB get error:', request.error);
        reject(request.error);
      };
 
      request.onsuccess = () => {
        resolve(request.result || null);
      };
    });
  }
 
  async set(key, value) {
    if (!this.available) return false;
    await this.init();
 
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([this.storeName], 'readwrite');
      const store = transaction.objectStore(this.storeName);
      const request = store.put(value, key);
 
      request.onerror = () => {
        console.error('IndexedDB set error:', request.error);
        reject(request.error);
      };
 
      request.onsuccess = () => {
        resolve(true);
      };
    });
  }
 
  async remove(key) {
    if (!this.available) return false;
    await this.init();
 
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([this.storeName], 'readwrite');
      const store = transaction.objectStore(this.storeName);
      const request = store.delete(key);
 
      request.onerror = () => {
        console.error('IndexedDB remove error:', request.error);
        reject(request.error);
      };
 
      request.onsuccess = () => {
        resolve(true);
      };
    });
  }
 
  async clear() {
    if (!this.available) return false;
    await this.init();
 
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([this.storeName], 'readwrite');
      const store = transaction.objectStore(this.storeName);
      const request = store.clear();
 
      request.onerror = () => {
        console.error('IndexedDB clear error:', request.error);
        reject(request.error);
      };
 
      request.onsuccess = () => {
        resolve(true);
      };
    });
  }
}
 
/**
 * Memory adapter (for testing or fallback)
 */
class MemoryAdapter {
  constructor() {
    this.storage = new Map();
    this.available = true;
  }
 
  async get(key) {
    return this.storage.get(key) || null;
  }
 
  async set(key, value) {
    this.storage.set(key, value);
    return true;
  }
 
  async remove(key) {
    return this.storage.delete(key);
  }
 
  async clear() {
    this.storage.clear();
    return true;
  }
}
 
/**
 * Simple encryption/decryption (basic XOR cipher)
 * For production, use Web Crypto API or a proper crypto library
 */
class SimpleEncryption {
  constructor(key) {
    this.key = key || 'default-key';
  }
 
  encrypt(text) {
    let result = '';
    for (let i = 0; i < text.length; i++) {
      result += String.fromCharCode(
        text.charCodeAt(i) ^ this.key.charCodeAt(i % this.key.length)
      );
    }
    return btoa(result);
  }
 
  decrypt(encrypted) {
    const text = atob(encrypted);
    let result = '';
    for (let i = 0; i < text.length; i++) {
      result += String.fromCharCode(
        text.charCodeAt(i) ^ this.key.charCodeAt(i % this.key.length)
      );
    }
    return result;
  }
}
 
/**
 * Create storage adapter
 * @param {StorageType} type - Storage type
 * @returns {StorageAdapter} Storage adapter instance
 */
function createStorageAdapter(type) {
  switch (type) {
    case 'localStorage':
      return new LocalStorageAdapter();
    case 'sessionStorage':
      return new SessionStorageAdapter();
    case 'indexedDB':
      return new IndexedDBAdapter();
    case 'memory':
      return new MemoryAdapter();
    default:
      return new LocalStorageAdapter();
  }
}
 
/**
 * Create persistent state manager
 * @param {Object} initialState - Initial state
 * @param {PersistenceOptions} options - Persistence options
 * @returns {Object} Persistent state manager
 */
export function createPersistentState(initialState = {}, options = {}) {
  const opts = {
    storage: 'localStorage',
    key: 'coherent-state',
    debounce: true,
    debounceDelay: 300,
    serialize: JSON.stringify,
    deserialize: JSON.parse,
    include: null,
    exclude: null,
    encrypt: false,
    encryptionKey: null,
    onSave: null,
    onLoad: null,
    onError: null,
    versioning: false,
    version: '1.0.0',
    migrate: null,
    ttl: null,
    crossTab: false,
    ...options
  };
 
  const adapter = createStorageAdapter(opts.storage);
  const encryption = opts.encrypt ? new SimpleEncryption(opts.encryptionKey) : null;
 
  let state = { ...initialState };
  let saveTimeout = null;
  const listeners = new Set();
 
  /**
   * Filter state keys based on include/exclude options
   * @param {Object} obj - State object
   * @returns {Object} Filtered state
   */
  function filterKeys(obj) {
    if (!obj || typeof obj !== 'object') return obj;
 
    // If include list is provided, only include those keys
    if (opts.include && Array.isArray(opts.include)) {
      const filtered = {};
      opts.include.forEach(key => {
        if (key in obj) {
          filtered[key] = obj[key];
        }
      });
      return filtered;
    }
 
    // If exclude list is provided, exclude those keys
    if (opts.exclude && Array.isArray(opts.exclude)) {
      const filtered = { ...obj };
      opts.exclude.forEach(key => {
        delete filtered[key];
      });
      return filtered;
    }
 
    return obj;
  }
 
  /**
   * Save state to storage
   * @param {boolean} immediate - Save immediately without debounce
   */
  async function save(immediate = false) {
    if (opts.debounce && !immediate) {
      clearTimeout(saveTimeout);
      saveTimeout = setTimeout(() => save(true), opts.debounceDelay);
      return;
    }
 
    try {
      const filteredState = filterKeys(state);
      const serialized = opts.serialize(filteredState);
 
      // Add metadata
      const data = {
        state: serialized,
        version: opts.version,
        timestamp: Date.now(),
        ttl: opts.ttl
      };
 
      let dataString = JSON.stringify(data);
 
      // Encrypt if enabled
      if (encryption) {
        dataString = encryption.encrypt(dataString);
      }
 
      await adapter.set(opts.key, dataString);
 
      // Call onSave callback
      if (opts.onSave) {
        opts.onSave(filteredState);
      }
 
      // Broadcast to other tabs if cross-tab sync is enabled
      if (opts.crossTab && typeof BroadcastChannel !== 'undefined') {
        const channel = new BroadcastChannel('coherent-state-sync');
        channel.postMessage({ type: 'state-update', state: filteredState });
        channel.close();
      }
    } catch (error) {
      console.error('State save error:', error);
      if (opts.onError) {
        opts.onError(error);
      }
    }
  }
 
  /**
   * Load state from storage
   */
  async function load() {
    try {
      let dataString = await adapter.get(opts.key);
      if (!dataString) return null;
 
      // Decrypt if enabled
      if (encryption) {
        dataString = encryption.decrypt(dataString);
      }
 
      const data = JSON.parse(dataString);
 
      // Check TTL
      if (data.ttl && data.timestamp) {
        const age = Date.now() - data.timestamp;
        if (age > data.ttl) {
          await adapter.remove(opts.key);
          return null;
        }
      }
 
      // Check version and migrate if needed
      if (opts.versioning && data.version !== opts.version) {
        if (opts.migrate) {
          const migrated = opts.migrate(data.state, data.version, opts.version);
          return opts.deserialize(migrated);
        }
        return null;
      }
 
      const loadedState = opts.deserialize(data.state);
 
      // Call onLoad callback
      if (opts.onLoad) {
        opts.onLoad(loadedState);
      }
 
      return loadedState;
    } catch (error) {
      console.error('State load error:', error);
      if (opts.onError) {
        opts.onError(error);
      }
      return null;
    }
  }
 
  /**
   * Subscribe to state changes
   * @param {Function} listener - Change listener
   * @returns {Function} Unsubscribe function
   */
  function subscribe(listener) {
    listeners.add(listener);
    return () => listeners.delete(listener);
  }
 
  /**
   * Notify listeners of state changes
   * @param {Object} oldState - Previous state
   * @param {Object} newState - New state
   */
  function notifyListeners(oldState, newState) {
    listeners.forEach(listener => {
      try {
        listener(newState, oldState);
      } catch (error) {
        console.error('Listener error:', error);
      }
    });
  }
 
  /**
   * Get current state
   * @param {string} [key] - State key
   * @returns {*} State value or entire state
   */
  function getState(key) {
    return key ? state[key] : { ...state };
  }
 
  /**
   * Set state
   * @param {Object|Function} updates - State updates or updater function
   * @param {boolean} persist - Persist to storage
   */
  function setState(updates, persist = true) {
    const oldState = { ...state };
 
    if (typeof updates === 'function') {
      updates = updates(oldState);
    }
 
    state = { ...state, ...updates };
 
    notifyListeners(oldState, state);
 
    if (persist) {
      save();
    }
  }
 
  /**
   * Reset state to initial values
   * @param {boolean} persist - Persist to storage
   */
  function resetState(persist = true) {
    const oldState = { ...state };
    state = { ...initialState };
    notifyListeners(oldState, state);
 
    if (persist) {
      save(true);
    }
  }
 
  /**
   * Clear persisted state
   */
  async function clearStorage() {
    await adapter.remove(opts.key);
  }
 
  /**
   * Manually trigger persistence
   */
  async function persist() {
    await save(true);
  }
 
  /**
   * Restore state from storage
   */
  async function restore() {
    const loaded = await load();
    if (loaded) {
      const oldState = { ...state };
      state = { ...state, ...loaded };
      notifyListeners(oldState, state);
      return true;
    }
    return false;
  }
 
  // Setup cross-tab synchronization
  if (opts.crossTab && typeof BroadcastChannel !== 'undefined') {
    const channel = new BroadcastChannel('coherent-state-sync');
    channel.onmessage = (event) => {
      if (event.data.type === 'state-update') {
        const oldState = { ...state };
        state = { ...state, ...event.data.state };
        notifyListeners(oldState, state);
      }
    };
  }
 
  // Auto-restore on creation
  if (opts.storage !== 'memory') {
    restore();
  }
 
  return {
    getState,
    setState,
    resetState,
    subscribe,
    persist,
    restore,
    clearStorage,
    load,
    save: () => save(true),
    get adapter() {
      return adapter;
    }
  };
}
 
/**
 * Create persistent state with localStorage
 * @param {Object} initialState - Initial state
 * @param {string} key - Storage key
 * @param {Partial<PersistenceOptions>} options - Additional options
 * @returns {Object} Persistent state manager
 */
export function withLocalStorage(initialState = {}, key = 'coherent-state', options = {}) {
  return createPersistentState(initialState, {
    ...options,
    storage: 'localStorage',
    key
  });
}
 
/**
 * Create persistent state with sessionStorage
 * @param {Object} initialState - Initial state
 * @param {string} key - Storage key
 * @param {Partial<PersistenceOptions>} options - Additional options
 * @returns {Object} Persistent state manager
 */
export function withSessionStorage(initialState = {}, key = 'coherent-state', options = {}) {
  return createPersistentState(initialState, {
    ...options,
    storage: 'sessionStorage',
    key
  });
}
 
/**
 * Create persistent state with IndexedDB
 * @param {Object} initialState - Initial state
 * @param {string} key - Storage key
 * @param {Partial<PersistenceOptions>} options - Additional options
 * @returns {Object} Persistent state manager
 */
export function withIndexedDB(initialState = {}, key = 'coherent-state', options = {}) {
  return createPersistentState(initialState, {
    ...options,
    storage: 'indexedDB',
    key
  });
}
 
export default {
  createPersistentState,
  withLocalStorage,
  withSessionStorage,
  withIndexedDB,
  createStorageAdapter
};