@choksheak/react-utils 0.2.9 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sharedState.ts","../src/storage.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState([], { indexedDbKey: \"users\" });\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n}\n\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n/** Please use sharedState() instead. */\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: Dispatch<SetStateAction<T>>;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (next: SetStateAction<T>) => {\n this.setValue(next);\n };\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: SetStateAction<T>): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.set(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.set(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.get(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValueBounded];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\nexport type StoreOptions = {\n persistTo: PersistTo;\n\n // Storage key to act as a namespace to store the data.\n key: string;\n\n // How long to wait before the value is considered expired.\n expiryMs?: number;\n};\n\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n\n switch (store.persistTo) {\n case \"localStorage\":\n return new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n }).asStorageAdapter<T>();\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n await kvStore.clear();\n },\n };\n }\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n"],"mappings":"AA2CA,OAAS,cAAAA,MAAkB,oCAC3B,OAAmC,wBAAAC,MAA4B,QC5C/D,OAAS,WAAAC,MAAe,8BACxB,OAAS,cAAAC,MAAkB,iCAwBpB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eACH,OAAO,IAAIJ,EAAWI,EAAM,IAAK,CAC/B,gBAAiBC,CACnB,CAAC,EAAE,iBAAoB,EAEzB,IAAK,YAAa,CAEhB,IAA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C,GAAI,KAAK,SAAU,OACnB,KAAK,SAAW,GAEhB,IAAMO,EAAI,MAAM,KAAK,gBAAgB,IAAIP,CAAW,EACpDD,EAAY,IAAI,KAAK,UAAWQ,IAAM,OAAYA,EAAI,KAAK,YAAY,CACzE,CACF,EAUO,SAASC,EACdL,EACAC,EACgB,CAChB,OAAO,IAAIF,EAAYC,EAAcC,CAAO,CAC9C,CAUO,SAASK,EACdC,EACkC,CAClC,OAAAA,EAAM,qBAAqB,EASpB,CAPOC,EACXC,GAAkBF,EAAM,UAAUE,CAAa,EAChD,IAAMF,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,eAAe,CACtC,CAUO,SAASG,EAAuBH,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAUO,SAASI,EAAwBJ,EAAuB,CAC7D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC","names":["MS_PER_DAY","useSyncExternalStore","kvStore","LocalStore","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","keyPrefix","key","value","SharedStateConfig","MS_PER_DAY","configureSharedState","config","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","lazyLoad","v","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
1
+ {"version":3,"sources":["../src/sharedState.ts","../src/storage.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState([], { indexedDbKey: \"users\" });\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n}\n\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n/** Please use sharedState() instead. */\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: Dispatch<SetStateAction<T>>;\n public initStarted = false;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (next: SetStateAction<T>) => {\n this.setValue(next);\n };\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: SetStateAction<T>): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.set(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.set(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone || this.initStarted) return;\n this.initStarted = true;\n\n const v = await this.storageAdapter?.get(STORAGE_KEY);\n const value = v !== undefined ? v : this.defaultValue;\n pubSubStore.set(this.pubSubKey, value);\n this.initDone = true;\n\n // Make sure React rerenders with the new initDone=true set.\n pubSubStore.set(this.pubSubKey, value);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValueBounded];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\nexport type StoreOptions = {\n persistTo: PersistTo;\n\n // Storage key to act as a namespace to store the data.\n key: string;\n\n // How long to wait before the value is considered expired.\n expiryMs?: number;\n};\n\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n\n switch (store.persistTo) {\n case \"localStorage\": {\n const adapter = new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n });\n\n // Handle SSR.\n return {\n set: (key: string, value: T): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n adapter.set(key, value);\n },\n get: (key: string): T | undefined => {\n if (typeof window === \"undefined\") return undefined; // handle SSR\n\n return adapter.get(key);\n },\n delete: (key: string): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n adapter.delete(key);\n },\n clear: (): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n adapter.clear();\n },\n };\n }\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n if (typeof window === \"undefined\") return undefined; // handle SSR\n\n return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n await kvStore.clear();\n },\n };\n }\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n"],"mappings":"AA2CA,OAAS,cAAAA,MAAkB,oCAC3B,OAAmC,wBAAAC,MAA4B,QC5C/D,OAAS,WAAAC,MAAe,8BACxB,OAAS,cAAAC,MAAkB,iCAwBpB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eAAgB,CACnB,IAAME,EAAU,IAAIN,EAAWI,EAAM,IAAK,CACxC,gBAAiBC,CACnB,C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AAoC,CACnD,OAAOK,EAAY,UAAU,KAAK,UAAW,IAAML,EAAW,CAAC,CACjE,CAIO,aAAiB,CACtB,OAAOK,EAAY,IAAI,KAAK,SAAS,CACvC,CAGO,SAASH,EAA+B,CAC7C,GAAI,OAAOA,GAAS,WAAY,CAC9B,IAAMH,EAAOM,EAAY,IAAO,KAAK,SAAS,EAC9CH,EAAQA,EAAqBH,CAAI,CACnC,CAEAM,EAAY,IAAI,KAAK,UAAWH,CAAI,EAC/B,KAAK,gBAAgB,IAAII,EAAaJ,CAAI,CACjD,CAIO,QAAS,CACdG,EAAY,IAAI,KAAK,UAAW,KAAK,YAAY,EAC5C,KAAK,gBAAgB,IAAIC,EAAa,KAAK,YAAY,CAC9D,CAGA,MAAa,sBAAuB,CAClC,GAAI,KAAK,UAAY,KAAK,YAAa,OACvC,KAAK,YAAc,GAEnB,IAAMO,EAAI,MAAM,KAAK,gBAAgB,IAAIP,CAAW,EAC9CR,EAAQe,IAAM,OAAYA,EAAI,KAAK,aACzCR,EAAY,IAAI,KAAK,UAAWP,CAAK,EACrC,KAAK,SAAW,GAGhBO,EAAY,IAAI,KAAK,UAAWP,CAAK,CACvC,CACF,EAUO,SAASgB,EACdL,EACAC,EACgB,CAChB,OAAO,IAAIF,EAAYC,EAAcC,CAAO,CAC9C,CAUO,SAASK,EACdC,EACkC,CAClC,OAAAA,EAAM,qBAAqB,EASpB,CAPOC,EACXC,GAAkBF,EAAM,UAAUE,CAAa,EAChD,IAAMF,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,eAAe,CACtC,CAUO,SAASG,EAAuBH,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAUO,SAASI,EAAwBJ,EAAuB,CAC7D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC","names":["MS_PER_DAY","useSyncExternalStore","kvStore","LocalStore","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","adapter","key","value","keyPrefix","SharedStateConfig","MS_PER_DAY","configureSharedState","config","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","lazyLoad","v","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
package/sharedState.mjs CHANGED
@@ -13,23 +13,46 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
13
13
  if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
14
14
  const expiryMs = store.expiryMs || defaultStoreExpiryMs;
15
15
  switch (store.persistTo) {
16
- case "localStorage":
17
- return new LocalStore(store.key, {
16
+ case "localStorage": {
17
+ const adapter = new LocalStore(store.key, {
18
18
  defaultExpiryMs: expiryMs
19
- }).asStorageAdapter();
19
+ });
20
+ return {
21
+ set: (key, value) => {
22
+ if (typeof window === "undefined") return;
23
+ adapter.set(key, value);
24
+ },
25
+ get: (key) => {
26
+ if (typeof window === "undefined") return void 0;
27
+ return adapter.get(key);
28
+ },
29
+ delete: (key) => {
30
+ if (typeof window === "undefined") return;
31
+ adapter.delete(key);
32
+ },
33
+ clear: () => {
34
+ if (typeof window === "undefined") return;
35
+ adapter.clear();
36
+ }
37
+ };
38
+ }
20
39
  case "indexedDb": {
21
40
  const keyPrefix = store.key + ":";
22
41
  return {
23
42
  set: async (key, value) => {
43
+ if (typeof window === "undefined") return;
24
44
  await kvStore.set(keyPrefix + key, value, expiryMs);
25
45
  },
26
46
  get: async (key) => {
47
+ if (typeof window === "undefined") return void 0;
27
48
  return await kvStore.get(keyPrefix + key);
28
49
  },
29
50
  delete: async (key) => {
51
+ if (typeof window === "undefined") return;
30
52
  await kvStore.delete(keyPrefix + key);
31
53
  },
32
54
  clear: async () => {
55
+ if (typeof window === "undefined") return;
33
56
  await kvStore.clear();
34
57
  }
35
58
  };
@@ -128,6 +151,7 @@ var SharedState = class {
128
151
  pubSubKey;
129
152
  storageAdapter;
130
153
  setValueBounded;
154
+ initStarted = false;
131
155
  initDone = false;
132
156
  // `subscribe` function required by useSyncExternalStore
133
157
  subscribe(subscriber) {
@@ -155,10 +179,13 @@ var SharedState = class {
155
179
  }
156
180
  // Initial default handling
157
181
  async initDefaultValueOnce() {
158
- if (this.initDone) return;
159
- this.initDone = true;
182
+ if (this.initDone || this.initStarted) return;
183
+ this.initStarted = true;
160
184
  const v = await this.storageAdapter?.get(STORAGE_KEY);
161
- pubSubStore.set(this.pubSubKey, v !== void 0 ? v : this.defaultValue);
185
+ const value = v !== void 0 ? v : this.defaultValue;
186
+ pubSubStore.set(this.pubSubKey, value);
187
+ this.initDone = true;
188
+ pubSubStore.set(this.pubSubKey, value);
162
189
  }
163
190
  };
164
191
  function sharedState(defaultValue, options) {
package/storage.cjs CHANGED
@@ -33,23 +33,46 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
33
33
  if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
34
34
  const expiryMs = store.expiryMs || defaultStoreExpiryMs;
35
35
  switch (store.persistTo) {
36
- case "localStorage":
37
- return new import_localStore.LocalStore(store.key, {
36
+ case "localStorage": {
37
+ const adapter = new import_localStore.LocalStore(store.key, {
38
38
  defaultExpiryMs: expiryMs
39
- }).asStorageAdapter();
39
+ });
40
+ return {
41
+ set: (key, value) => {
42
+ if (typeof window === "undefined") return;
43
+ adapter.set(key, value);
44
+ },
45
+ get: (key) => {
46
+ if (typeof window === "undefined") return void 0;
47
+ return adapter.get(key);
48
+ },
49
+ delete: (key) => {
50
+ if (typeof window === "undefined") return;
51
+ adapter.delete(key);
52
+ },
53
+ clear: () => {
54
+ if (typeof window === "undefined") return;
55
+ adapter.clear();
56
+ }
57
+ };
58
+ }
40
59
  case "indexedDb": {
41
60
  const keyPrefix = store.key + ":";
42
61
  return {
43
62
  set: async (key, value) => {
63
+ if (typeof window === "undefined") return;
44
64
  await import_kvStore.kvStore.set(keyPrefix + key, value, expiryMs);
45
65
  },
46
66
  get: async (key) => {
67
+ if (typeof window === "undefined") return void 0;
47
68
  return await import_kvStore.kvStore.get(keyPrefix + key);
48
69
  },
49
70
  delete: async (key) => {
71
+ if (typeof window === "undefined") return;
50
72
  await import_kvStore.kvStore.delete(keyPrefix + key);
51
73
  },
52
74
  clear: async () => {
75
+ if (typeof window === "undefined") return;
53
76
  await import_kvStore.kvStore.clear();
54
77
  }
55
78
  };
package/storage.min.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var n=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var c=(r,t)=>{for(var e in t)n(r,e,{get:t[e],enumerable:!0})},l=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of y(t))!T.call(r,o)&&o!==e&&n(r,o,{get:()=>t[o],enumerable:!(s=g(t,o))||s.enumerable});return r};var f=r=>l(n({},"__esModule",{value:!0}),r);var S={};c(S,{getStorageAdapter:()=>u});module.exports=f(S);var a=require("@choksheak/ts-utils/kvStore"),p=require("@choksheak/ts-utils/localStore");function u(r,t){let{store:e}=r??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let s=e.expiryMs||t;switch(e.persistTo){case"localStorage":return new p.LocalStore(e.key,{defaultExpiryMs:s}).asStorageAdapter();case"indexedDb":{let o=e.key+":";return{set:async(i,d)=>{await a.kvStore.set(o+i,d,s)},get:async i=>await a.kvStore.get(o+i),delete:async i=>{await a.kvStore.delete(o+i)},clear:async()=>{await a.kvStore.clear()}}}default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}0&&(module.exports={getStorageAdapter});
1
+ "use strict";var a=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var w=(i,r)=>{for(var e in r)a(i,e,{get:r[e],enumerable:!0})},g=(i,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of u(r))!y.call(i,t)&&t!==e&&a(i,t,{get:()=>r[t],enumerable:!(o=p(r,t))||o.enumerable});return i};var c=i=>g(a({},"__esModule",{value:!0}),i);var T={};w(T,{getStorageAdapter:()=>l});module.exports=c(T);var s=require("@choksheak/ts-utils/kvStore"),f=require("@choksheak/ts-utils/localStore");function l(i,r){let{store:e}=i??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let o=e.expiryMs||r;switch(e.persistTo){case"localStorage":{let t=new f.LocalStore(e.key,{defaultExpiryMs:o});return{set:(n,d)=>{typeof window>"u"||t.set(n,d)},get:n=>{if(!(typeof window>"u"))return t.get(n)},delete:n=>{typeof window>"u"||t.delete(n)},clear:()=>{typeof window>"u"||t.clear()}}}case"indexedDb":{let t=e.key+":";return{set:async(n,d)=>{typeof window>"u"||await s.kvStore.set(t+n,d,o)},get:async n=>{if(!(typeof window>"u"))return await s.kvStore.get(t+n)},delete:async n=>{typeof window>"u"||await s.kvStore.delete(t+n)},clear:async()=>{typeof window>"u"||await s.kvStore.clear()}}}default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}0&&(module.exports={getStorageAdapter});
2
2
  //# sourceMappingURL=storage.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\nexport type StoreOptions = {\n persistTo: PersistTo;\n\n // Storage key to act as a namespace to store the data.\n key: string;\n\n // How long to wait before the value is considered expired.\n expiryMs?: number;\n};\n\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n\n switch (store.persistTo) {\n case \"localStorage\":\n return new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n }).asStorageAdapter<T>();\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n await kvStore.clear();\n },\n };\n }\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,uBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAwB,uCACxBC,EAA2B,0CAwBpB,SAASH,EACdI,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eACH,OAAO,IAAI,aAAWA,EAAM,IAAK,CAC/B,gBAAiBC,CACnB,CAAC,EAAE,iBAAoB,EAEzB,IAAK,YAAa,CAEhB,IAAMC,EAAYF,EAAM,IAAM,IAK9B,MAAO,CACL,IAAK,MAAOG,EAAaC,IAA4B,CAEnD,MAAM,UAAQ,IAAIF,EAAYC,EAAKC,EAAOH,CAAQ,CACpD,EACA,IAAK,MAAOE,GACH,MAAM,UAAQ,IAAID,EAAYC,CAAG,EAE1C,OAAQ,MAAOA,GAA+B,CAC5C,MAAM,UAAQ,OAAOD,EAAYC,CAAG,CACtC,EACA,MAAO,SAA2B,CAChC,MAAM,UAAQ,MAAM,CACtB,CACF,CACF,CAEA,QACE,MAAAH,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT","names":["storage_exports","__export","getStorageAdapter","__toCommonJS","import_kvStore","import_localStore","options","defaultStoreExpiryMs","store","expiryMs","keyPrefix","key","value"]}
1
+ {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\nexport type StoreOptions = {\n persistTo: PersistTo;\n\n // Storage key to act as a namespace to store the data.\n key: string;\n\n // How long to wait before the value is considered expired.\n expiryMs?: number;\n};\n\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n\n switch (store.persistTo) {\n case \"localStorage\": {\n const adapter = new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n });\n\n // Handle SSR.\n return {\n set: (key: string, value: T): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n adapter.set(key, value);\n },\n get: (key: string): T | undefined => {\n if (typeof window === \"undefined\") return undefined; // handle SSR\n\n return adapter.get(key);\n },\n delete: (key: string): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n adapter.delete(key);\n },\n clear: (): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n adapter.clear();\n },\n };\n }\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n if (typeof window === \"undefined\") return undefined; // handle SSR\n\n return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n await kvStore.clear();\n },\n };\n }\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,uBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAwB,uCACxBC,EAA2B,0CAwBpB,SAASH,EACdI,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eAAgB,CACnB,IAAME,EAAU,IAAI,aAAWF,EAAM,IAAK,CACxC,gBAAiBC,CACnB,CAAC,EAGD,MAAO,CACL,IAAK,CAACE,EAAaC,IAAmB,CAChC,OAAO,OAAW,KAGtBF,EAAQ,IAAIC,EAAKC,CAAK,CACxB,EACA,IAAMD,GAA+B,CACnC,GAAI,SAAO,OAAW,KAEtB,OAAOD,EAAQ,IAAIC,CAAG,CACxB,EACA,OAASA,GAAsB,CACzB,OAAO,OAAW,KAEtBD,EAAQ,OAAOC,CAAG,CACpB,EACA,MAAO,IAAY,CACb,OAAO,OAAW,KAEtBD,EAAQ,MAAM,CAChB,CACF,CACF,CAEA,IAAK,YAAa,CAEhB,IAAMG,EAAYL,EAAM,IAAM,IAK9B,MAAO,CACL,IAAK,MAAOG,EAAaC,IAA4B,CAC/C,OAAO,OAAW,KAGtB,MAAM,UAAQ,IAAIC,EAAYF,EAAKC,EAAOH,CAAQ,CACpD,EACA,IAAK,MAAOE,GAAwC,CAClD,GAAI,SAAO,OAAW,KAEtB,OAAO,MAAM,UAAQ,IAAIE,EAAYF,CAAG,CAC1C,EACA,OAAQ,MAAOA,GAA+B,CACxC,OAAO,OAAW,KAEtB,MAAM,UAAQ,OAAOE,EAAYF,CAAG,CACtC,EACA,MAAO,SAA2B,CAC5B,OAAO,OAAW,KAEtB,MAAM,UAAQ,MAAM,CACtB,CACF,CACF,CAEA,QACE,MAAAH,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT","names":["storage_exports","__export","getStorageAdapter","__toCommonJS","import_kvStore","import_localStore","options","defaultStoreExpiryMs","store","expiryMs","adapter","key","value","keyPrefix"]}
package/storage.min.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{kvStore as r}from"@choksheak/ts-utils/kvStore";import{LocalStore as p}from"@choksheak/ts-utils/localStore";function y(i,a){let{store:e}=i??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let s=e.expiryMs||a;switch(e.persistTo){case"localStorage":return new p(e.key,{defaultExpiryMs:s}).asStorageAdapter();case"indexedDb":{let o=e.key+":";return{set:async(t,n)=>{await r.set(o+t,n,s)},get:async t=>await r.get(o+t),delete:async t=>{await r.delete(o+t)},clear:async()=>{await r.clear()}}}default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}export{y as getStorageAdapter};
1
+ import{kvStore as n}from"@choksheak/ts-utils/kvStore";import{LocalStore as a}from"@choksheak/ts-utils/localStore";function u(s,d){let{store:e}=s??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let o=e.expiryMs||d;switch(e.persistTo){case"localStorage":{let r=new a(e.key,{defaultExpiryMs:o});return{set:(t,i)=>{typeof window>"u"||r.set(t,i)},get:t=>{if(!(typeof window>"u"))return r.get(t)},delete:t=>{typeof window>"u"||r.delete(t)},clear:()=>{typeof window>"u"||r.clear()}}}case"indexedDb":{let r=e.key+":";return{set:async(t,i)=>{typeof window>"u"||await n.set(r+t,i,o)},get:async t=>{if(!(typeof window>"u"))return await n.get(r+t)},delete:async t=>{typeof window>"u"||await n.delete(r+t)},clear:async()=>{typeof window>"u"||await n.clear()}}}default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}export{u as getStorageAdapter};
2
2
  //# sourceMappingURL=storage.min.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\nexport type StoreOptions = {\n persistTo: PersistTo;\n\n // Storage key to act as a namespace to store the data.\n key: string;\n\n // How long to wait before the value is considered expired.\n expiryMs?: number;\n};\n\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n\n switch (store.persistTo) {\n case \"localStorage\":\n return new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n }).asStorageAdapter<T>();\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n await kvStore.clear();\n },\n };\n }\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,8BACxB,OAAS,cAAAC,MAAkB,iCAwBpB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eACH,OAAO,IAAIJ,EAAWI,EAAM,IAAK,CAC/B,gBAAiBC,CACnB,CAAC,EAAE,iBAAoB,EAEzB,IAAK,YAAa,CAEhB,IAAMC,EAAYF,EAAM,IAAM,IAK9B,MAAO,CACL,IAAK,MAAOG,EAAaC,IAA4B,CAEnD,MAAMT,EAAQ,IAAIO,EAAYC,EAAKC,EAAOH,CAAQ,CACpD,EACA,IAAK,MAAOE,GACH,MAAMR,EAAQ,IAAIO,EAAYC,CAAG,EAE1C,OAAQ,MAAOA,GAA+B,CAC5C,MAAMR,EAAQ,OAAOO,EAAYC,CAAG,CACtC,EACA,MAAO,SAA2B,CAChC,MAAMR,EAAQ,MAAM,CACtB,CACF,CACF,CAEA,QACE,MAAAK,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT","names":["kvStore","LocalStore","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","keyPrefix","key","value"]}
1
+ {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\nexport type StoreOptions = {\n persistTo: PersistTo;\n\n // Storage key to act as a namespace to store the data.\n key: string;\n\n // How long to wait before the value is considered expired.\n expiryMs?: number;\n};\n\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n\n switch (store.persistTo) {\n case \"localStorage\": {\n const adapter = new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n });\n\n // Handle SSR.\n return {\n set: (key: string, value: T): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n adapter.set(key, value);\n },\n get: (key: string): T | undefined => {\n if (typeof window === \"undefined\") return undefined; // handle SSR\n\n return adapter.get(key);\n },\n delete: (key: string): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n adapter.delete(key);\n },\n clear: (): void => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n adapter.clear();\n },\n };\n }\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n if (typeof window === \"undefined\") return undefined; // handle SSR\n\n return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (typeof window === \"undefined\") return; // handle SSR\n\n await kvStore.clear();\n },\n };\n }\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,8BACxB,OAAS,cAAAC,MAAkB,iCAwBpB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eAAgB,CACnB,IAAME,EAAU,IAAIN,EAAWI,EAAM,IAAK,CACxC,gBAAiBC,CACnB,CAAC,EAGD,MAAO,CACL,IAAK,CAACE,EAAaC,IAAmB,CAChC,OAAO,OAAW,KAGtBF,EAAQ,IAAIC,EAAKC,CAAK,CACxB,EACA,IAAMD,GAA+B,CACnC,GAAI,SAAO,OAAW,KAEtB,OAAOD,EAAQ,IAAIC,CAAG,CACxB,EACA,OAASA,GAAsB,CACzB,OAAO,OAAW,KAEtBD,EAAQ,OAAOC,CAAG,CACpB,EACA,MAAO,IAAY,CACb,OAAO,OAAW,KAEtBD,EAAQ,MAAM,CAChB,CACF,CACF,CAEA,IAAK,YAAa,CAEhB,IAAMG,EAAYL,EAAM,IAAM,IAK9B,MAAO,CACL,IAAK,MAAOG,EAAaC,IAA4B,CAC/C,OAAO,OAAW,KAGtB,MAAMT,EAAQ,IAAIU,EAAYF,EAAKC,EAAOH,CAAQ,CACpD,EACA,IAAK,MAAOE,GAAwC,CAClD,GAAI,SAAO,OAAW,KAEtB,OAAO,MAAMR,EAAQ,IAAIU,EAAYF,CAAG,CAC1C,EACA,OAAQ,MAAOA,GAA+B,CACxC,OAAO,OAAW,KAEtB,MAAMR,EAAQ,OAAOU,EAAYF,CAAG,CACtC,EACA,MAAO,SAA2B,CAC5B,OAAO,OAAW,KAEtB,MAAMR,EAAQ,MAAM,CACtB,CACF,CACF,CAEA,QACE,MAAAK,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT","names":["kvStore","LocalStore","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","adapter","key","value","keyPrefix"]}
package/storage.mjs CHANGED
@@ -9,23 +9,46 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
9
9
  if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
10
10
  const expiryMs = store.expiryMs || defaultStoreExpiryMs;
11
11
  switch (store.persistTo) {
12
- case "localStorage":
13
- return new LocalStore(store.key, {
12
+ case "localStorage": {
13
+ const adapter = new LocalStore(store.key, {
14
14
  defaultExpiryMs: expiryMs
15
- }).asStorageAdapter();
15
+ });
16
+ return {
17
+ set: (key, value) => {
18
+ if (typeof window === "undefined") return;
19
+ adapter.set(key, value);
20
+ },
21
+ get: (key) => {
22
+ if (typeof window === "undefined") return void 0;
23
+ return adapter.get(key);
24
+ },
25
+ delete: (key) => {
26
+ if (typeof window === "undefined") return;
27
+ adapter.delete(key);
28
+ },
29
+ clear: () => {
30
+ if (typeof window === "undefined") return;
31
+ adapter.clear();
32
+ }
33
+ };
34
+ }
16
35
  case "indexedDb": {
17
36
  const keyPrefix = store.key + ":";
18
37
  return {
19
38
  set: async (key, value) => {
39
+ if (typeof window === "undefined") return;
20
40
  await kvStore.set(keyPrefix + key, value, expiryMs);
21
41
  },
22
42
  get: async (key) => {
43
+ if (typeof window === "undefined") return void 0;
23
44
  return await kvStore.get(keyPrefix + key);
24
45
  },
25
46
  delete: async (key) => {
47
+ if (typeof window === "undefined") return;
26
48
  await kvStore.delete(keyPrefix + key);
27
49
  },
28
50
  clear: async () => {
51
+ if (typeof window === "undefined") return;
29
52
  await kvStore.clear();
30
53
  }
31
54
  };