( target: string | PersistTarget, store: [Store<T>, SetStoreFunction<T>], )
| 551 | } |
| 552 | |
| 553 | export function persisted<T>( |
| 554 | target: string | PersistTarget, |
| 555 | store: [Store<T>, SetStoreFunction<T>], |
| 556 | ): PersistedWithReady<T> { |
| 557 | const platform = usePlatform() |
| 558 | const config = resolveTarget(typeof target === "string" ? { key: target } : target, platform) |
| 559 | |
| 560 | const defaults = snapshot(store[0]) |
| 561 | const legacy = config.legacy ?? [] |
| 562 | |
| 563 | const isDesktop = platform.platform === "desktop" && !!platform.storage |
| 564 | |
| 565 | const currentStorage = (() => { |
| 566 | if (isDesktop) return platform.storage?.(config.storage) |
| 567 | if (!config.storage) return localStorageDirect() |
| 568 | return localStorageWithPrefix(config.storage) |
| 569 | })() |
| 570 | |
| 571 | const legacyStorage = (() => { |
| 572 | if (!isDesktop) return localStorageDirect() |
| 573 | if (!config.storage) return platform.storage?.() |
| 574 | return platform.storage?.(LEGACY_STORAGE) |
| 575 | })() |
| 576 | |
| 577 | const legacyStorageNames = config.legacyStorageNames ?? [] |
| 578 | |
| 579 | const storage = (() => { |
| 580 | if (!isDesktop) { |
| 581 | const current = currentStorage as SyncStorage |
| 582 | const legacyStore = legacyStorage as SyncStorage |
| 583 | const legacyStores = legacyStorageNames.map(localStorageWithPrefix) |
| 584 | |
| 585 | const api: SyncStorage = { |
| 586 | getItem: (key) => { |
| 587 | const value = readCurrent({ storage: current, key, defaults, migrate: config.migrate }) |
| 588 | if (value !== undefined) return value |
| 589 | return migrateLegacy({ |
| 590 | current, |
| 591 | legacyStore, |
| 592 | stores: legacyStores, |
| 593 | keys: legacy, |
| 594 | key, |
| 595 | defaults, |
| 596 | migrate: config.migrate, |
| 597 | }) |
| 598 | }, |
| 599 | setItem: (key, value) => { |
| 600 | current.setItem(key, value) |
| 601 | }, |
| 602 | removeItem: (key) => { |
| 603 | current.removeItem(key) |
| 604 | }, |
| 605 | } |
| 606 | |
| 607 | return api |
| 608 | } |
| 609 | |
| 610 | const current = currentStorage as AsyncStorage |
no test coverage detected