@choksheak/react-utils 0.3.1 → 0.3.2

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/sharedQuery.ts","../src/sharedState.ts","../src/storage.ts","../src/stringify.ts","../src/useDeepMemo.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared query\" is a data fetching convenience library that helps users\n * to load data, check for staleness and expiration, cache in memory, local\n * storage or indexed db, and be able to manipulate the data anytime.\n *\n * Each shared query creates a new private shared state that handles the data\n * storage. This shared state contains the records for all queries, where each\n * query is a unique set of arguments used to make the query. The number of\n * records and the total byte size of data can be limited so as to ensure the\n * query does not take up too much memory.\n *\n * Example:\n * ```\n * import { sharedQuery, useSharedQuery } from \"@choksheak/react-utils/sharedQuery\";\n *\n * // Create a new shared query in the top level scope.\n * // The query function `queryFn` here does not take any arguments.\n * //\n * // Only the queryName and queryFn are required and everything else is\n * // optional.\n * //\n * // The queryName must be unique, otherwise we will throw an\n * // error. This is because defining the same queryName for two different\n * // queries implies that the queries are the same, thus violating the idea\n * // of a \"shared\" query, and almost certainly points to a bug in the code.\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * // Note that the query will only start fetching on mount in React.\n * // But you can do `usersQuery.getCachedOrFetch()` here to prefetch the\n * // data if necessary.\n * usersQuery.getCachedOrFetch();\n *\n * // Example of using a query function with arguments.\n * export const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: getUser, // getUser(userId: string) => User\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * export const UsersComponent: React.FC = () => {\n * // Second argument is optional, and is an array of arguments to be\n * // passed to the `queryFn`.\n * const users = useSharedQuery(usersQuery);\n *\n * return (\n * <>\n * <h1>List of Users</h1>\n *\n * <button onclick={users.refetch}>Refresh</button>\n *\n * {users.loading && <Loader />}\n *\n * {users.error && !users.data && <p>Error: {String(users.error)}</p>}\n *\n * <p>Data: {users.data ? JSON.stringify(users.data) : \"-\"}</p>\n * </>\n * );\n * };\n *\n * export const AnotherComponent: React.FC = () => {\n * // This query will be deduped with the one above, sharing the same\n * // data and the same fetches.\n * const users = useSharedQuery(usersQuery);\n * ...\n * };\n *\n * export const DisplayOneUser: React.FC<{userId: string}> = ({userId}) => {\n * // Example of using the query with an argument. Whenever the argument\n * // changes, the data will be fetched and updated automatically.\n * const user = useSharedQuery(getUserQuery, [userId]);\n *\n * return <>User: {user.data ? JSON.stringify(user.data) : \"-\"}</>;\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport getByteSize from \"object-sizeof\";\nimport {\n SetStateAction,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport {\n SharedState,\n sharedState,\n SharedStateOptions,\n useSharedState,\n} from \"./sharedState\";\nimport { PersistTo } from \"./storage\";\nimport { stringifyDeterministicForKeys } from \"./stringify\";\nimport { useDeepMemo } from \"./useDeepMemo\";\n\n/** Type of the queryFn used to fetch the data from source. */\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\n/** An entry for a persisted state corresponding to one query key. */\nexport type QueryStateValue<TData> = Readonly<{\n /**\n * When this record was last updated. Used for LRU determination. If you want\n * the data age, please use `dataUpdatedMs` instead.\n */\n lastUpdatedMs: number;\n\n loading: boolean;\n data?: TData;\n dataUpdatedMs?: number;\n\n /**\n * Use unknown type for error because we can't assume what type of variable\n * will be thrown from the query function. We also don't want to add this\n * type to QueryStateValue<TError> as it adds complexity to the type.\n */\n error?: unknown;\n\n errorUpdatedMs?: number;\n}>;\n\n/** Return type for useSharedQuery(). */\nexport type UseQueryResult<TData> = QueryStateValue<TData> &\n Readonly<{\n /**\n * Return the last non-empty data if you want to display the last loaded data\n * while waiting for the new data to load.\n */\n lastNonEmptyData: TData | undefined;\n\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => void;\n\n /**\n * If you got the data from somewhere else (e.g. an in-memory data update),\n * just set it directly.\n */\n setData: (data: TData, dataUpdatedMs?: number) => void;\n\n deleteData: () => void;\n }>;\n\n/**\n * The full query state is a record of all the fetch states mapped by\n * query key to the state entry.\n */\nexport type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;\n\n/** Options to configure a shared query. */\nexport type SharedQueryOptions<TArgs extends unknown[], TData> = {\n /**\n * The name could have been auto-generated, but we let the user give us a\n * human-readable name that can be identified quickly in the logs.\n * Note that the queryKey is a string formed by the queryName plus the query\n * arguments.\n */\n queryName: string;\n\n /**\n * Function to fetch data.\n */\n queryFn: QueryFn<TArgs, TData>;\n\n /**\n * ms before data considered stale; 0 means always stale.\n */\n staleMs?: number;\n\n /**\n * ms before data is removed from cache; 0 means never expire.\n */\n expiryMs?: number;\n\n /**\n * Trigger background re-fetch if stale.\n */\n refetchOnStale?: boolean;\n\n /**\n * Shortcut to set the localStorageKey or indexedDbKey automatically from\n * queryName. This is important because it avoids requiring the user to\n * specify the same queryName twice everytime.\n */\n persistTo?: PersistTo;\n\n /**\n * Max number of entries to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxSize?: number;\n\n /**\n * Max number of bytes to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxBytes?: number;\n\n /**\n * Keep a copy of the last non-empty data so that when you change the\n * query arguments, you can still display the old data while waiting for the\n * new data to load.\n */\n keepLastNonEmptyData?: boolean;\n\n /**\n * Customize the logger.\n */\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryConfig = {\n /** Refetch on every page load. */\n staleMs: 0,\n\n /** Keep in cache for a long time. */\n expiryMs: 30 * MS_PER_DAY,\n\n /** Always refetch automatically if the data is stale. */\n refetchOnStale: true,\n\n /** No default persistence configured. */\n persistTo: undefined as PersistTo | undefined,\n\n /** 100 is not too large, but please tweak accordingly. */\n maxSize: 100,\n\n /** 100kb limit before discarding old records. */\n maxBytes: 100_000,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedQuery]\", ...args),\n};\n\nexport type SharedQueryConfig = typeof SharedQueryConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedQuery(config: Partial<SharedQueryConfig>) {\n Object.assign(SharedQueryConfig, config);\n}\n\n/** Please use sharedQuery() instead. */\nexport class SharedQuery<TArgs extends unknown[], TData> {\n private readonly inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n public readonly queryState: SharedState<SharedQueryState<TData>>;\n\n /**\n * Keep track of the mounted query keys. This handles the case where an\n * earlier-started query returns later, and when it returns, it was already\n * unmounted, thus making it eligible for clean up right after fetch.\n */\n private readonly mountedKeys = new Map<string, number>();\n\n public readonly queryName: string;\n private readonly queryFn: QueryFn<TArgs, TData>;\n public readonly expiryMs: number;\n public readonly staleMs: number;\n public readonly refetchOnStale: boolean;\n public readonly maxSize: number;\n public readonly maxBytes: number;\n public readonly keepLastNonEmptyData: boolean;\n public readonly log: (...args: unknown[]) => void;\n\n public constructor(options: SharedQueryOptions<TArgs, TData>) {\n this.queryName = options.queryName;\n this.queryFn = options.queryFn;\n\n this.staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;\n this.expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;\n\n this.refetchOnStale =\n options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the `store` will take precedence over `persistTo`.\n if (!options.store) {\n const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;\n\n if (persistTo) {\n options.store = {\n persistTo,\n key: options.queryName,\n expiryMs: this.expiryMs,\n };\n }\n }\n\n this.maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;\n this.maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;\n\n this.keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);\n\n this.log = options?.log ?? SharedQueryConfig.log;\n\n this.queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n options,\n );\n }\n\n /** Returns a key to identify requests based on the given args. */\n public getQueryKey(args: TArgs): string {\n return this.queryName + \":\" + stringifyDeterministicForKeys(args);\n }\n\n /**\n * Get the AbortController to abort the inflight query (if any).\n *\n * Note that once you get the controller, you can also get the signal easily\n * using `controller.signal`. So if you need both the controller and the\n * signal, just use this function.\n */\n public getAbortController(args: TArgs): AbortController | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortControllerByKey(queryKey);\n }\n\n public getAbortControllerByKey(queryKey: string): AbortController | null {\n return this.inflightQueries.get(queryKey)?.abortController ?? null;\n }\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await fetch(`/users/${userId}`, { signal });\n *\n * // Check for errors.\n * if (!response.ok) {\n * throw new Error(response.statusText);\n * }\n *\n * // Return the data.\n * return await response.json();\n * },\n * });\n * ```\n */\n public getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortSignalByKey(queryKey);\n }\n\n public getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return this.getAbortControllerByKey(queryKey)?.signal ?? null;\n }\n\n private isStale(dataUpdatedMs: number): boolean {\n if (this.staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.staleMs;\n }\n\n private isExpired(dataUpdatedMs: number): boolean {\n if (this.expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.expiryMs;\n }\n\n public async getCachedOrFetch(...args: TArgs): Promise<TData> {\n const queryKey = this.getQueryKey(args);\n const cached = this.queryState.getSnapshot()?.[queryKey];\n\n if (cached?.data && !this.isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!this.isStale(cached.dataUpdatedMs ?? 0)) {\n this.log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached.data;\n }\n\n // If stale, optionally update the data in the background.\n if (this.refetchOnStale) {\n this.log(`refetchOnStale for ${queryKey}`);\n void this.dedupedFetch(queryKey, ...args);\n }\n\n // Still return stale data immediately.\n this.log(`Returning stale data for ${queryKey}`);\n return cached.data;\n }\n\n return await this.dedupedFetch(queryKey, ...args);\n }\n\n private dedupedFetch(queryKey: string, ...args: TArgs): Promise<TData> {\n const inflightQuery = this.inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests\n if (inflightQuery) {\n this.log(`Deduplicating inflight fetch for ${queryKey}`);\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = this.startFetching(queryKey, args);\n const abortController = new AbortController();\n\n this.inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n private async startFetching(queryKey: string, args: TArgs) {\n this.log(`Start fetching ${queryKey}`);\n\n try {\n const data = await this.queryFn(...args);\n\n this.log(`Successfully fetched ${queryKey}`);\n this.setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n this.log(`Failed to fetch ${queryKey}: ${e}`);\n throw e;\n } finally {\n this.inflightQueries.delete(queryKey);\n }\n }\n\n /** Get the entire stored entry for a query key. */\n public getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return this.queryState.getSnapshot()?.[queryKey];\n }\n\n /** Get the current stored data for a query key. */\n public getData(queryKey: string): TData | undefined {\n const stateValue: QueryStateValue<TData> | undefined =\n this.queryState.getSnapshot()?.[queryKey];\n\n // Check for expiration.\n if (stateValue?.lastUpdatedMs) {\n if (this.isExpired(stateValue.lastUpdatedMs)) {\n this.deleteData(queryKey);\n return undefined;\n }\n }\n\n return stateValue?.data;\n }\n\n /** Set the data directly if the user obtained it from somewhere else. */\n public setData(\n queryKey: string,\n data: TData,\n dataUpdatedMs = Date.now(),\n ): void {\n const entry: QueryStateValue<TData> = {\n lastUpdatedMs: Date.now(),\n loading: false,\n data,\n dataUpdatedMs,\n };\n\n this.queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n this.enforceSizeLimit();\n }\n\n /**\n * Do a new fetch even when the data is already cached, but don't fetch if\n * another fetch is already inflight.\n */\n public async updateFromSource(...args: TArgs): Promise<TData> {\n const key = this.getQueryKey(args);\n return await this.dedupedFetch(key, ...args);\n }\n\n /** Delete the cached data for one set of arguments. */\n public deleteData(queryKey: string): void {\n const record = this.queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n this.queryState.setValue(clone);\n\n const inflight = this.inflightQueries.get(queryKey);\n if (inflight) {\n this.inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n }\n\n /** Delete all currently cached data & all inflight promises. */\n public clear(): void {\n this.queryState.delete();\n\n for (const { abortController } of Array.from(\n this.inflightQueries.values(),\n )) {\n abortController.abort(\"Cleared\");\n }\n\n this.inflightQueries.clear();\n }\n\n /** Keep track of mounted keys. */\n public mount(queryKey: string): void {\n this.mountedKeys.set(queryKey, (this.mountedKeys.get(queryKey) ?? 0) + 1);\n }\n\n /** Clean up mounted keys. */\n public unmount(queryKey: string): void {\n const count = this.mountedKeys.get(queryKey);\n if (count === 1) {\n this.mountedKeys.delete(queryKey);\n } else {\n this.mountedKeys.set(queryKey, (count ?? 0) - 1);\n }\n }\n\n /**\n * Discard the oldest entries if the size exceeds the limit. The last\n * remaining record cannot be deleted no matter what the limit is.\n */\n public enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!this.maxSize && !this.maxBytes) {\n return;\n }\n\n const oldState = this.queryState.getSnapshot();\n const oldSize = Object.keys(oldState).length;\n\n // Cannot do GC if size is 1 or less.\n if (oldSize <= 1) {\n return;\n }\n\n const oldByteSize = getByteSize(oldState);\n\n let numToCut = this.maxSize ? oldSize - this.maxSize : 0;\n let bytesToCut = this.maxBytes ? oldByteSize - this.maxBytes : 0;\n\n // Log to indicate why trimming was not needed.\n if (numToCut <= 0 && bytesToCut <= 0) {\n this.log(\n `No need to trim data for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Log to inform user that trimming is needed.\n this.log(\n `Need to trim ${this.queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`,\n );\n\n const newState = { ...oldState }; // shallow clone\n let needUpdate = false;\n\n const deleteKeyIfNotMounted = (key: string, expired: boolean) => {\n // Mounted keys cannot be cleaned up as they are visible in the UI.\n if (this.mountedKeys.has(key)) {\n this.log(`Cannot clean up ${key} as it is mounted`);\n return;\n }\n\n const byteSize = getByteSize(key) + getByteSize(newState[key]);\n this.log(\n `Cleaning up unmounted${expired ? \", expired\" : \"\"} ${key} (byteSize=${byteSize.toLocaleString()})`,\n );\n\n numToCut--;\n bytesToCut -= byteSize;\n\n delete newState[key];\n needUpdate = true;\n };\n\n let entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n // Clean up all expired entries. Note that the auto-expiration in the\n // storage adapter only applies to the entire state, which contains all\n // the different query keys and their values. Each query key has its own\n // timestamp and we need to apply our own expiration here.\n for (const [key] of entriesByTimeAscending) {\n // Anything after this is not expired yet.\n if (!this.isExpired(newState[key].lastUpdatedMs)) {\n break;\n }\n\n deleteKeyIfNotMounted(key, true);\n }\n\n if (numToCut > 0 || bytesToCut > 0) {\n if (needUpdate) {\n entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n }\n\n // Clean up starting from oldest entry first.\n for (const [key] of entriesByTimeAscending) {\n deleteKeyIfNotMounted(key, false);\n\n if (numToCut <= 0 && bytesToCut <= 0) {\n break;\n }\n }\n }\n\n // Log to indicate why trimming was not needed.\n if (!needUpdate) {\n this.log(\n `No trimmable entries found for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Update the state.\n this.queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n this.log(\n `Trimmed data for ${this.queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${this.maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${this.maxBytes.toLocaleString()})`,\n );\n }\n}\n\n// Disallow duplicate query names.\nconst seenQueryNames = new Set<string>();\n\n/**\n * Create a reusable shared query object that can be used to auto de-duplicate\n * and cache all data fetches, with auto-expiration and staleness checks.\n *\n * Each `queryName` must be unique, and can only be declared once, most often\n * in the top level scope. The queryName is used for logging only.\n *\n * Example:\n * ```\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n * ```\n */\nexport function sharedQuery<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n): SharedQuery<TArgs, TData> {\n if (seenQueryNames.has(options.queryName)) {\n throw new Error(`Duplicate shared query \"${options.queryName}\"`);\n }\n seenQueryNames.add(options.queryName);\n\n return new SharedQuery(options);\n}\n\n// Using any so that we don't need to typecast later.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst DEFAULT_QUERY_STATE_ENTRY: Readonly<QueryStateValue<any>> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component. The\n * args do not need to be specified if no args are needed, i.e. this would work\n * ```\n * const allUsers = useSharedQuery(listUsersQuery);\n * ```\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, \"userid123\");\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Optional: Default to use no arguments.\n ...args: TArgs\n): UseQueryResult<TData> {\n // We don't expect users to provide a stable `args`, so stabilize it here.\n const stableArgs = useDeepMemo(args);\n\n const [queryState, setQueryState] = useSharedState(query.queryState);\n\n const isMounted = useRef(true);\n\n const queryKey = useMemo(\n () => query.getQueryKey(stableArgs),\n [query, stableArgs],\n );\n\n // Init with empty object.\n const queryStateValue: QueryStateValue<TData> =\n queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;\n\n const setQueryStateValue = useCallback(\n (next: SetStateAction<QueryStateValue<TData>>) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof next === \"function\"\n ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY)\n : next;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // Keep the last non-empty data loaded in case you want to show a placeholder\n // during new loads.\n const [lastNonEmptyData, setLastNonEmptyData] = useState<TData | undefined>();\n\n useEffect(() => {\n if (query.keepLastNonEmptyData && queryStateValue.data !== undefined) {\n setLastNonEmptyData(queryStateValue.data);\n }\n }, [query.keepLastNonEmptyData, queryStateValue.data]);\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (forceRefresh: boolean) => {\n query.log(`Begin executing shared query ${queryKey}`);\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...prev,\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n const data = await (forceRefresh\n ? query.updateFromSource(...stableArgs)\n : query.getCachedOrFetch(...stableArgs));\n\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue({\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n });\n }\n } catch (e) {\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue((prev) => ({\n // Keep old data.\n ...prev,\n lastUpdatedMs: now,\n loading: false,\n error: e,\n errorUpdatedMs: now,\n }));\n }\n }\n },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n query.mount(queryKey);\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n query.unmount(queryKey);\n };\n }, [execute, query, queryKey]);\n\n return useMemo(() => {\n return {\n ...queryStateValue,\n lastNonEmptyData,\n // This works only if the user-given queryFn supports abort. If not,\n // this function doesn't do anything, since we don't have any means to\n // abort the running queryFn.\n abortCurrentQuery: (reason?: unknown) => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: () => {\n void execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number) => {\n const now = Date.now();\n setQueryStateValue((prev) => ({\n ...prev,\n data,\n dataUpdatedMs: dataUpdatedMs ?? now,\n lastUpdatedMs: now,\n loading: false,\n }));\n },\n deleteData: () => {\n setQueryState((prev) => {\n const clone = { ...prev };\n delete clone[queryKey];\n return clone;\n });\n },\n } satisfies UseQueryResult<TData>;\n }, [\n execute,\n lastNonEmptyData,\n query,\n queryKey,\n queryStateValue,\n setQueryState,\n setQueryStateValue,\n ]);\n}\n","/**\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","/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n","import isEqual from \"lodash/isEqual\";\nimport { useMemo, useState } from \"react\";\n\n/**\n * Provides a stable value for T based on deep equality. The deep equality is\n * determined by the `isEqual()` function in lodash.\n */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (state === value || isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"],"mappings":"AAoFA,OAAS,cAAAA,MAAkB,oCAC3B,OAAOC,MAAiB,gBACxB,OAEE,eAAAC,EACA,aAAAC,EACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QClDP,OAAS,cAAAC,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,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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J,EACAb,EACAjC,EACA0C,EACAL,EACAM,CACF,CAAC,CACH","names":["MS_PER_DAY","getByteSize","useCallback","useEffect","useMemo","useRef","useState","MS_PER_DAY","useSyncExternalStore","kvStore","LocalStore","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","adapter","key","value","keyPrefix","SharedStateConfig","MS_PER_DAY","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","SharedStateConfig","lazyLoad","v","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","stringifyDeterministicForKeys","params","cache","_","value","result","key","isEqual","useMemo","useState","useDeepMemo","value","state","setState","SharedQueryConfig","MS_PER_DAY","args","configureSharedQuery","config","SharedQuery","options","persistTo","sharedState","stringifyDeterministicForKeys","queryKey","dataUpdatedMs","cached","inflightQuery","promise","abortController","data","e","stateValue","entry","prev","key","clone","inflight","count","oldState","oldSize","oldByteSize","getByteSize","numToCut","bytesToCut","newState","needUpdate","deleteKeyIfNotMounted","expired","byteSize","entriesByTimeAscending","entry1","entry2","seenQueryNames","sharedQuery","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","queryState","setQueryState","useSharedState","isMounted","useRef","useMemo","queryStateValue","setQueryStateValue","useCallback","next","lastNonEmptyData","setLastNonEmptyData","useState","useEffect","execute","forceRefresh","now","reason","controller"]}
1
+ {"version":3,"sources":["../src/sharedQuery.ts","../src/sharedState.ts","../src/storage.ts","../src/stringify.ts","../src/useDeepMemo.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared query\" is a data fetching convenience library that helps users\n * to load data, check for staleness and expiration, cache in memory, local\n * storage or indexed db, and be able to manipulate the data anytime.\n *\n * Each shared query creates a new private shared state that handles the data\n * storage. This shared state contains the records for all queries, where each\n * query is a unique set of arguments used to make the query. The number of\n * records and the total byte size of data can be limited so as to ensure the\n * query does not take up too much memory.\n *\n * Example:\n * ```\n * import { sharedQuery, useSharedQuery } from \"@choksheak/react-utils/sharedQuery\";\n *\n * // Create a new shared query in the top level scope.\n * // The query function `queryFn` here does not take any arguments.\n * //\n * // Only the queryName and queryFn are required and everything else is\n * // optional.\n * //\n * // The queryName must be unique, otherwise we will throw an\n * // error. This is because defining the same queryName for two different\n * // queries implies that the queries are the same, thus violating the idea\n * // of a \"shared\" query, and almost certainly points to a bug in the code.\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * // Note that the query will only start fetching on mount in React.\n * // But you can do `usersQuery.getCachedOrFetch()` here to prefetch the\n * // data if necessary.\n * usersQuery.getCachedOrFetch();\n *\n * // Example of using a query function with arguments.\n * export const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: getUser, // getUser(userId: string) => User\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * export const UsersComponent: React.FC = () => {\n * // Second argument is optional, and is an array of arguments to be\n * // passed to the `queryFn`.\n * const users = useSharedQuery(usersQuery);\n *\n * return (\n * <>\n * <h1>List of Users</h1>\n *\n * <button onclick={users.refetch}>Refresh</button>\n *\n * {users.loading && <Loader />}\n *\n * {users.error && !users.data && <p>Error: {String(users.error)}</p>}\n *\n * <p>Data: {users.data ? JSON.stringify(users.data) : \"-\"}</p>\n * </>\n * );\n * };\n *\n * export const AnotherComponent: React.FC = () => {\n * // This query will be deduped with the one above, sharing the same\n * // data and the same fetches.\n * const users = useSharedQuery(usersQuery);\n * ...\n * };\n *\n * export const DisplayOneUser: React.FC<{userId: string}> = ({userId}) => {\n * // Example of using the query with an argument. Whenever the argument\n * // changes, the data will be fetched and updated automatically.\n * const user = useSharedQuery(getUserQuery, [userId]);\n *\n * return <>User: {user.data ? JSON.stringify(user.data) : \"-\"}</>;\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport getByteSize from \"object-sizeof\";\nimport {\n SetStateAction,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport {\n SharedState,\n sharedState,\n SharedStateOptions,\n useSharedState,\n} from \"./sharedState\";\nimport { PersistTo } from \"./storage\";\nimport { stringifyDeterministicForKeys } from \"./stringify\";\nimport { useDeepMemo } from \"./useDeepMemo\";\n\n/** Type of the queryFn used to fetch the data from source. */\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\n/** An entry for a persisted state corresponding to one query key. */\nexport type QueryStateValue<TData> = Readonly<{\n /**\n * When this record was last updated. Used for LRU determination. If you want\n * the data age, please use `dataUpdatedMs` instead.\n */\n lastUpdatedMs: number;\n\n loading: boolean;\n data?: TData;\n dataUpdatedMs?: number;\n\n /**\n * Use unknown type for error because we can't assume what type of variable\n * will be thrown from the query function. We also don't want to add this\n * type to QueryStateValue<TError> as it adds complexity to the type.\n */\n error?: unknown;\n\n errorUpdatedMs?: number;\n}>;\n\n/** Return type for useSharedQuery(). */\nexport type UseQueryResult<TData> = QueryStateValue<TData> &\n Readonly<{\n /**\n * Return the last non-empty data if you want to display the last loaded data\n * while waiting for the new data to load.\n */\n lastNonEmptyData: TData | undefined;\n\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => void;\n\n /**\n * If you got the data from somewhere else (e.g. an in-memory data update),\n * just set it directly.\n */\n setData: (data: TData, dataUpdatedMs?: number) => void;\n\n deleteData: () => void;\n }>;\n\n/**\n * The full query state is a record of all the fetch states mapped by\n * query key to the state entry.\n */\nexport type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;\n\n/** Options to configure a shared query. */\nexport type SharedQueryOptions<TArgs extends unknown[], TData> = {\n /**\n * The name could have been auto-generated, but we let the user give us a\n * human-readable name that can be identified quickly in the logs.\n * Note that the queryKey is a string formed by the queryName plus the query\n * arguments.\n */\n queryName: string;\n\n /**\n * Function to fetch data.\n */\n queryFn: QueryFn<TArgs, TData>;\n\n /**\n * ms before data considered stale; 0 means always stale.\n */\n staleMs?: number;\n\n /**\n * ms before data is removed from cache; 0 means never expire.\n */\n expiryMs?: number;\n\n /**\n * Trigger background re-fetch if stale.\n */\n refetchOnStale?: boolean;\n\n /**\n * Shortcut to set the localStorageKey or indexedDbKey automatically from\n * queryName. This is important because it avoids requiring the user to\n * specify the same queryName twice everytime.\n */\n persistTo?: PersistTo;\n\n /**\n * Max number of entries to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxSize?: number;\n\n /**\n * Max number of bytes to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxBytes?: number;\n\n /**\n * Keep a copy of the last non-empty data so that when you change the\n * query arguments, you can still display the old data while waiting for the\n * new data to load.\n */\n keepLastNonEmptyData?: boolean;\n\n /**\n * Customize the logger.\n */\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryConfig = {\n /** Refetch on every page load. */\n staleMs: 0,\n\n /** Keep in cache for a long time. */\n expiryMs: 30 * MS_PER_DAY,\n\n /** Always refetch automatically if the data is stale. */\n refetchOnStale: true,\n\n /** No default persistence configured. */\n persistTo: undefined as PersistTo | undefined,\n\n /** 100 is not too large, but please tweak accordingly. */\n maxSize: 100,\n\n /** 100kb limit before discarding old records. */\n maxBytes: 100_000,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedQuery]\", ...args),\n};\n\nexport type SharedQueryConfig = typeof SharedQueryConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedQuery(config: Partial<SharedQueryConfig>) {\n Object.assign(SharedQueryConfig, config);\n}\n\n/** Please use sharedQuery() instead. */\nexport class SharedQuery<TArgs extends unknown[], TData> {\n private readonly inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n public readonly queryState: SharedState<SharedQueryState<TData>>;\n\n /**\n * Keep track of the mounted query keys. This handles the case where an\n * earlier-started query returns later, and when it returns, it was already\n * unmounted, thus making it eligible for clean up right after fetch.\n */\n private readonly mountedKeys = new Map<string, number>();\n\n public readonly queryName: string;\n private readonly queryFn: QueryFn<TArgs, TData>;\n public readonly expiryMs: number;\n public readonly staleMs: number;\n public readonly refetchOnStale: boolean;\n public readonly maxSize: number;\n public readonly maxBytes: number;\n public readonly keepLastNonEmptyData: boolean;\n public readonly log: (...args: unknown[]) => void;\n\n public constructor(options: SharedQueryOptions<TArgs, TData>) {\n this.queryName = options.queryName;\n this.queryFn = options.queryFn;\n\n this.staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;\n this.expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;\n\n this.refetchOnStale =\n options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the `store` will take precedence over `persistTo`.\n if (!options.store) {\n const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;\n\n if (persistTo) {\n options.store = {\n persistTo,\n key: options.queryName,\n expiryMs: this.expiryMs,\n };\n }\n }\n\n this.maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;\n this.maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;\n\n this.keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);\n\n this.log = options?.log ?? SharedQueryConfig.log;\n\n this.queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n options,\n );\n }\n\n /** Returns a key to identify requests based on the given args. */\n public getQueryKey(args: TArgs): string {\n return this.queryName + \":\" + stringifyDeterministicForKeys(args);\n }\n\n /**\n * Get the AbortController to abort the inflight query (if any).\n *\n * Note that once you get the controller, you can also get the signal easily\n * using `controller.signal`. So if you need both the controller and the\n * signal, just use this function.\n */\n public getAbortController(args: TArgs): AbortController | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortControllerByKey(queryKey);\n }\n\n public getAbortControllerByKey(queryKey: string): AbortController | null {\n return this.inflightQueries.get(queryKey)?.abortController ?? null;\n }\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await fetch(`/users/${userId}`, { signal });\n *\n * // Check for errors.\n * if (!response.ok) {\n * throw new Error(response.statusText);\n * }\n *\n * // Return the data.\n * return await response.json();\n * },\n * });\n * ```\n */\n public getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortSignalByKey(queryKey);\n }\n\n public getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return this.getAbortControllerByKey(queryKey)?.signal ?? null;\n }\n\n private isStale(dataUpdatedMs: number): boolean {\n if (this.staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.staleMs;\n }\n\n private isExpired(dataUpdatedMs: number): boolean {\n if (this.expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.expiryMs;\n }\n\n public async getCachedOrFetch(...args: TArgs): Promise<TData> {\n const queryKey = this.getQueryKey(args);\n const cached = this.queryState.getSnapshot()?.[queryKey];\n\n if (cached?.data && !this.isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!this.isStale(cached.dataUpdatedMs ?? 0)) {\n this.log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached.data;\n }\n\n // If stale, optionally update the data in the background.\n if (this.refetchOnStale) {\n this.log(`refetchOnStale for ${queryKey}`);\n void this.dedupedFetch(queryKey, ...args);\n }\n\n // Still return stale data immediately.\n this.log(`Returning stale data for ${queryKey}`);\n return cached.data;\n }\n\n return await this.dedupedFetch(queryKey, ...args);\n }\n\n private dedupedFetch(queryKey: string, ...args: TArgs): Promise<TData> {\n const inflightQuery = this.inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests\n if (inflightQuery) {\n this.log(`Deduplicating inflight fetch for ${queryKey}`);\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = this.startFetching(queryKey, args);\n const abortController = new AbortController();\n\n this.inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n private async startFetching(queryKey: string, args: TArgs) {\n this.log(`Start fetching ${queryKey}`);\n\n try {\n const data = await this.queryFn(...args);\n\n this.log(`Successfully fetched ${queryKey}`);\n this.setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n this.log(`Failed to fetch ${queryKey}: ${e}`);\n throw e;\n } finally {\n this.inflightQueries.delete(queryKey);\n }\n }\n\n /** Get the entire stored entry for a query key. */\n public getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return this.queryState.getSnapshot()?.[queryKey];\n }\n\n /** Get the current stored data for a query key. */\n public getData(queryKey: string): TData | undefined {\n const stateValue: QueryStateValue<TData> | undefined =\n this.queryState.getSnapshot()?.[queryKey];\n\n // Check for expiration.\n if (stateValue?.lastUpdatedMs) {\n if (this.isExpired(stateValue.lastUpdatedMs)) {\n this.deleteData(queryKey);\n return undefined;\n }\n }\n\n return stateValue?.data;\n }\n\n /** Set the data directly if the user obtained it from somewhere else. */\n public setData(\n queryKey: string,\n data: TData,\n dataUpdatedMs = Date.now(),\n ): void {\n const entry: QueryStateValue<TData> = {\n lastUpdatedMs: Date.now(),\n loading: false,\n data,\n dataUpdatedMs,\n };\n\n this.queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n this.enforceSizeLimit();\n }\n\n /**\n * Do a new fetch even when the data is already cached, but don't fetch if\n * another fetch is already inflight.\n */\n public async updateFromSource(...args: TArgs): Promise<TData> {\n const key = this.getQueryKey(args);\n return await this.dedupedFetch(key, ...args);\n }\n\n /** Delete the cached data for one set of arguments. */\n public deleteData(queryKey: string): void {\n const record = this.queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n this.queryState.setValue(clone);\n\n const inflight = this.inflightQueries.get(queryKey);\n if (inflight) {\n this.inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n }\n\n /** Delete all currently cached data & all inflight promises. */\n public clear(): void {\n this.queryState.delete();\n\n for (const { abortController } of Array.from(\n this.inflightQueries.values(),\n )) {\n abortController.abort(\"Cleared\");\n }\n\n this.inflightQueries.clear();\n }\n\n /** Keep track of mounted keys. */\n public mount(queryKey: string): void {\n this.mountedKeys.set(queryKey, (this.mountedKeys.get(queryKey) ?? 0) + 1);\n }\n\n /** Clean up mounted keys. */\n public unmount(queryKey: string): void {\n const count = this.mountedKeys.get(queryKey);\n if (count === 1) {\n this.mountedKeys.delete(queryKey);\n } else {\n this.mountedKeys.set(queryKey, (count ?? 0) - 1);\n }\n }\n\n /**\n * Discard the oldest entries if the size exceeds the limit. The last\n * remaining record cannot be deleted no matter what the limit is.\n */\n public enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!this.maxSize && !this.maxBytes) {\n return;\n }\n\n const oldState = this.queryState.getSnapshot();\n const oldSize = Object.keys(oldState).length;\n\n // Cannot do GC if size is 1 or less.\n if (oldSize <= 1) {\n return;\n }\n\n const oldByteSize = getByteSize(oldState);\n\n let numToCut = this.maxSize ? oldSize - this.maxSize : 0;\n let bytesToCut = this.maxBytes ? oldByteSize - this.maxBytes : 0;\n\n // Log to indicate why trimming was not needed.\n if (numToCut <= 0 && bytesToCut <= 0) {\n this.log(\n `No need to trim data for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Log to inform user that trimming is needed.\n this.log(\n `Need to trim ${this.queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`,\n );\n\n const newState = { ...oldState }; // shallow clone\n let needUpdate = false;\n\n const deleteKeyIfNotMounted = (key: string, expired: boolean) => {\n // Mounted keys cannot be cleaned up as they are visible in the UI.\n if (this.mountedKeys.has(key)) {\n this.log(`Cannot clean up ${key} as it is mounted`);\n return;\n }\n\n const byteSize = getByteSize(key) + getByteSize(newState[key]);\n this.log(\n `Cleaning up unmounted${expired ? \", expired\" : \"\"} ${key} (byteSize=${byteSize.toLocaleString()})`,\n );\n\n numToCut--;\n bytesToCut -= byteSize;\n\n delete newState[key];\n needUpdate = true;\n };\n\n let entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n // Clean up all expired entries. Note that the auto-expiration in the\n // storage adapter only applies to the entire state, which contains all\n // the different query keys and their values. Each query key has its own\n // timestamp and we need to apply our own expiration here.\n for (const [key] of entriesByTimeAscending) {\n // Anything after this is not expired yet.\n if (!this.isExpired(newState[key].lastUpdatedMs)) {\n break;\n }\n\n deleteKeyIfNotMounted(key, true);\n }\n\n if (numToCut > 0 || bytesToCut > 0) {\n if (needUpdate) {\n entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n }\n\n // Clean up starting from oldest entry first.\n for (const [key] of entriesByTimeAscending) {\n deleteKeyIfNotMounted(key, false);\n\n if (numToCut <= 0 && bytesToCut <= 0) {\n break;\n }\n }\n }\n\n // Log to indicate why trimming was not needed.\n if (!needUpdate) {\n this.log(\n `No trimmable entries found for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Update the state.\n this.queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n this.log(\n `Trimmed data for ${this.queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${this.maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${this.maxBytes.toLocaleString()})`,\n );\n }\n}\n\n// Disallow duplicate query names.\nconst seenQueryNames = new Set<string>();\n\n/**\n * Create a reusable shared query object that can be used to auto de-duplicate\n * and cache all data fetches, with auto-expiration and staleness checks.\n *\n * Each `queryName` must be unique, and can only be declared once, most often\n * in the top level scope. The queryName is used for logging only.\n *\n * Example:\n * ```\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n * ```\n */\nexport function sharedQuery<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n): SharedQuery<TArgs, TData> {\n if (seenQueryNames.has(options.queryName)) {\n throw new Error(`Duplicate shared query \"${options.queryName}\"`);\n }\n seenQueryNames.add(options.queryName);\n\n return new SharedQuery(options);\n}\n\n// Using any so that we don't need to typecast later.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst DEFAULT_QUERY_STATE_ENTRY: Readonly<QueryStateValue<any>> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component. The\n * args do not need to be specified if no args are needed, i.e. this would work\n * ```\n * const allUsers = useSharedQuery(listUsersQuery);\n * ```\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, \"userid123\");\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Optional: Default to use no arguments.\n ...args: TArgs\n): UseQueryResult<TData> {\n // We don't expect users to provide a stable `args`, so stabilize it here.\n const stableArgs = useDeepMemo(args);\n\n const [queryState, setQueryState] = useSharedState(query.queryState);\n\n const isMounted = useRef(true);\n\n const queryKey = useMemo(\n () => query.getQueryKey(stableArgs),\n [query, stableArgs],\n );\n\n // Init with empty object.\n const queryStateValue: QueryStateValue<TData> =\n queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;\n\n const setQueryStateValue = useCallback(\n (next: SetStateAction<QueryStateValue<TData>>) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof next === \"function\"\n ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY)\n : next;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // Keep the last non-empty data loaded in case you want to show a placeholder\n // during new loads.\n const [lastNonEmptyData, setLastNonEmptyData] = useState<TData | undefined>();\n\n useEffect(() => {\n if (query.keepLastNonEmptyData && queryStateValue.data !== undefined) {\n setLastNonEmptyData(queryStateValue.data);\n }\n }, [query.keepLastNonEmptyData, queryStateValue.data]);\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (forceRefresh: boolean) => {\n query.log(`Begin executing shared query ${queryKey}`);\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...prev,\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n const data = await (forceRefresh\n ? query.updateFromSource(...stableArgs)\n : query.getCachedOrFetch(...stableArgs));\n\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue({\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n });\n }\n } catch (e) {\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue((prev) => ({\n // Keep old data.\n ...prev,\n lastUpdatedMs: now,\n loading: false,\n error: e,\n errorUpdatedMs: now,\n }));\n }\n }\n },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n query.mount(queryKey);\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n query.unmount(queryKey);\n };\n }, [execute, query, queryKey]);\n\n return useMemo(() => {\n return {\n ...queryStateValue,\n lastNonEmptyData,\n // This works only if the user-given queryFn supports abort. If not,\n // this function doesn't do anything, since we don't have any means to\n // abort the running queryFn.\n abortCurrentQuery: (reason?: unknown) => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: () => {\n void execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number) => {\n const now = Date.now();\n setQueryStateValue((prev) => ({\n ...prev,\n data,\n dataUpdatedMs: dataUpdatedMs ?? now,\n lastUpdatedMs: now,\n loading: false,\n }));\n },\n deleteData: () => {\n setQueryState((prev) => {\n const clone = { ...prev };\n delete clone[queryKey];\n return clone;\n });\n },\n } satisfies UseQueryResult<TData>;\n }, [\n execute,\n lastNonEmptyData,\n query,\n queryKey,\n queryStateValue,\n setQueryState,\n setQueryStateValue,\n ]);\n}\n","/**\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 /** Returns true if there is a backing store. */\n public hasStore(): boolean {\n return Boolean(this.storageAdapter);\n }\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n public async setInStore(value: T): Promise<void> {\n return await this.storageAdapter?.set(STORAGE_KEY, value);\n }\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n public async getFromStore(): Promise<T | undefined> {\n return await this.storageAdapter?.get(STORAGE_KEY);\n }\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\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.setInStore(next);\n }\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\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 stored = await this.getFromStore();\n const value = stored !== undefined ? stored : this.defaultValue;\n\n pubSubStore.set(this.pubSubKey, value);\n\n this.initDone = true;\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\n/** Options to configure a pre-built store adapter. */\nexport type StoreOptions = {\n /** Choose which pre-built store adapter to use. */\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 /** Returns true if the given value supposed to be of type T is valid. */\n isValid?: (u: unknown) => boolean;\n};\n\n/** Either use a pre-built store, or a custom one you provide. */\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\n// In SSR (Server-Side Rendering) mode, we never want to use our storage\n// adapters for anything.\nconst IS_NOT_BROWSER = typeof window === \"undefined\";\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 const isValid = store.isValid;\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 (IS_NOT_BROWSER) 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 (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const value = adapter.get<T>(key);\n\n if (isValid && !isValid(value)) {\n console.warn(\n `localStorage adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`,\n );\n adapter.delete(key);\n return undefined;\n }\n\n return value;\n },\n delete: (key: string): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.delete(key);\n },\n clear: (): void => {\n if (IS_NOT_BROWSER) 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 const isValid = store.isValid;\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 (IS_NOT_BROWSER) 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 (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = await kvStore.get<T>(fullKey);\n\n if (isValid && !isValid(value)) {\n console.warn(\n `indexedDb adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`,\n );\n await kvStore.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n delete: async (key: string): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (IS_NOT_BROWSER) 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","/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n","import isEqual from \"lodash/isEqual\";\nimport { useMemo, useState } from \"react\";\n\n/**\n * Provides a stable value for T based on deep equality. The deep equality is\n * determined by the `isEqual()` function in lodash.\n */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (state === value || isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"],"mappings":"AAoFA,OAAS,cAAAA,MAAkB,oCAC3B,OAAOC,MAAiB,gBACxB,OAEE,eAAAC,EACA,aAAAC,EACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QClDP,OAAS,cAAAC,MAAkB,oCAC3B,OAAmC,wBAAAC,MAA4B,QC5C/D,OAAS,WAAAC,MAAe,8BACxB,OAAS,cAAAC,MAAkB,iCAgC3B,IAAMC,EAAiB,OAAO,OAAW,IAElC,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,C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U,CAE5B,GAAGA,EACH,cAAe0C,EACf,QAAS,GACT,MAAO7C,EACP,eAAgB6C,CAClB,EAAE,CACJ,CACF,CACF,EACA,CAACnB,EAAOjC,EAAU2C,EAAoBT,CAAU,CAClD,EAEA,OAAAe,EAAU,KACRV,EAAU,QAAU,GACpBN,EAAM,MAAMjC,CAAQ,EAEfkD,EAAQ,EAAK,EAEX,IAAM,CACXX,EAAU,QAAU,GACpBN,EAAM,QAAQjC,CAAQ,CACxB,GACC,CAACkD,EAASjB,EAAOjC,CAAQ,CAAC,EAEtByC,EAAQ,KACN,CACL,GAAGC,EACH,iBAAAI,EAIA,kBAAoBO,GAAqB,CACvC,IAAMC,EAAarB,EAAM,wBAAwBjC,CAAQ,EACzD,OAAAsD,GAAY,MAAMD,CAAM,EACjB,EAAQC,CACjB,EACA,QAAS,IAAM,CACRJ,EAAQ,EAAI,CACnB,EACA,QAAS,CAAC5C,EAAaL,IAA2B,CAChD,IAAMmD,EAAM,KAAK,IAAI,EACrBT,EAAoBjC,IAAU,CAC5B,GAAGA,EACH,KAAAJ,EACA,cAAeL,GAAiBmD,EAChC,cAAeA,EACf,QAAS,EACX,EAAE,CACJ,EACA,WAAY,IAAM,CAChBf,EAAe3B,GAAS,CACtB,IAAME,EAAQ,CAAE,GAAGF,CAAK,EACxB,cAAOE,EAAMZ,CAAQ,EACdY,CACT,CAAC,CACH,CACF,GACC,CACDsC,EACAJ,EACAb,EACAjC,EACA0C,EACAL,EACAM,CACF,CAAC,CACH","names":["MS_PER_DAY","getByteSize","useCallback","useEffect","useMemo","useRef","useState","MS_PER_DAY","useSyncExternalStore","kvStore","LocalStore","IS_NOT_BROWSER","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","isValid","adapter","key","value","keyPrefix","fullKey","SharedStateConfig","MS_PER_DAY","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","SharedStateConfig","lazyLoad","stored","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","stringifyDeterministicForKeys","params","cache","_","value","result","key","isEqual","useMemo","useState","useDeepMemo","value","state","setState","SharedQueryConfig","MS_PER_DAY","args","configureSharedQuery","config","SharedQuery","options","persistTo","sharedState","stringifyDeterministicForKeys","queryKey","dataUpdatedMs","cached","inflightQuery","promise","abortController","data","e","stateValue","entry","prev","key","clone","inflight","count","oldState","oldSize","oldByteSize","getByteSize","numToCut","bytesToCut","newState","needUpdate","deleteKeyIfNotMounted","expired","byteSize","entriesByTimeAscending","entry1","entry2","seenQueryNames","sharedQuery","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","queryState","setQueryState","useSharedState","isMounted","useRef","useMemo","queryStateValue","setQueryStateValue","useCallback","next","lastNonEmptyData","setLastNonEmptyData","useState","useEffect","execute","forceRefresh","now","reason","controller"]}
package/sharedQuery.mjs CHANGED
@@ -16,6 +16,7 @@ import { useSyncExternalStore } from "react";
16
16
  // src/storage.ts
17
17
  import { kvStore } from "@choksheak/ts-utils/kvStore";
18
18
  import { LocalStore } from "@choksheak/ts-utils/localStore";
19
+ var IS_NOT_BROWSER = typeof window === "undefined";
19
20
  function getStorageAdapter(options, defaultStoreExpiryMs) {
20
21
  const { store } = options ?? {};
21
22
  if (!store) {
@@ -23,6 +24,7 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
23
24
  }
24
25
  if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
25
26
  const expiryMs = store.expiryMs || defaultStoreExpiryMs;
27
+ const isValid = store.isValid;
26
28
  switch (store.persistTo) {
27
29
  case "localStorage": {
28
30
  const adapter = new LocalStore(store.key, {
@@ -30,40 +32,58 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
30
32
  });
31
33
  return {
32
34
  set: (key, value) => {
33
- if (typeof window === "undefined") return;
35
+ if (IS_NOT_BROWSER) return;
34
36
  adapter.set(key, value);
35
37
  },
36
38
  get: (key) => {
37
- if (typeof window === "undefined") return void 0;
38
- return adapter.get(key);
39
+ if (IS_NOT_BROWSER) return void 0;
40
+ const value = adapter.get(key);
41
+ if (isValid && !isValid(value)) {
42
+ console.warn(
43
+ `localStorage adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`
44
+ );
45
+ adapter.delete(key);
46
+ return void 0;
47
+ }
48
+ return value;
39
49
  },
40
50
  delete: (key) => {
41
- if (typeof window === "undefined") return;
51
+ if (IS_NOT_BROWSER) return;
42
52
  adapter.delete(key);
43
53
  },
44
54
  clear: () => {
45
- if (typeof window === "undefined") return;
55
+ if (IS_NOT_BROWSER) return;
46
56
  adapter.clear();
47
57
  }
48
58
  };
49
59
  }
50
60
  case "indexedDb": {
51
61
  const keyPrefix = store.key + ":";
62
+ const isValid2 = store.isValid;
52
63
  return {
53
64
  set: async (key, value) => {
54
- if (typeof window === "undefined") return;
65
+ if (IS_NOT_BROWSER) return;
55
66
  await kvStore.set(keyPrefix + key, value, expiryMs);
56
67
  },
57
68
  get: async (key) => {
58
- if (typeof window === "undefined") return void 0;
59
- return await kvStore.get(keyPrefix + key);
69
+ if (IS_NOT_BROWSER) return void 0;
70
+ const fullKey = keyPrefix + key;
71
+ const value = await kvStore.get(fullKey);
72
+ if (isValid2 && !isValid2(value)) {
73
+ console.warn(
74
+ `indexedDb adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`
75
+ );
76
+ await kvStore.delete(fullKey);
77
+ return void 0;
78
+ }
79
+ return value;
60
80
  },
61
81
  delete: async (key) => {
62
- if (typeof window === "undefined") return;
82
+ if (IS_NOT_BROWSER) return;
63
83
  await kvStore.delete(keyPrefix + key);
64
84
  },
65
85
  clear: async () => {
66
- if (typeof window === "undefined") return;
86
+ if (IS_NOT_BROWSER) return;
67
87
  await kvStore.clear();
68
88
  }
69
89
  };
@@ -161,39 +181,65 @@ var SharedState = class {
161
181
  setValueBounded;
162
182
  initStarted = false;
163
183
  initDone = false;
164
- // `subscribe` function required by useSyncExternalStore
184
+ /** `subscribe` function required by useSyncExternalStore. */
165
185
  subscribe(subscriber) {
166
186
  return pubSubStore.subscribe(this.pubSubKey, () => subscriber());
167
187
  }
168
- // Get the value of the shared state.
169
- // `getSnapshot` function — must return same ref if value unchanged
188
+ /** Returns true if there is a backing store. */
189
+ hasStore() {
190
+ return Boolean(this.storageAdapter);
191
+ }
192
+ /**
193
+ * Set a value directly into the store. Does nothing if there is no
194
+ * backing store.
195
+ *
196
+ * Warning: If you want to set the value properly, you should use
197
+ * `setValue()` instead which also updates the in-memory copy.
198
+ */
199
+ async setInStore(value) {
200
+ return await this.storageAdapter?.set(STORAGE_KEY, value);
201
+ }
202
+ /**
203
+ * Get a value directly from the store. Returns undefined if there is no
204
+ * backing store.
205
+ */
206
+ async getFromStore() {
207
+ return await this.storageAdapter?.get(STORAGE_KEY);
208
+ }
209
+ /**
210
+ * Get the value of the shared state.
211
+ * `getSnapshot` function — must return same ref if value unchanged.
212
+ * Note that this would return the default value if data init from store is
213
+ * not completed yet.
214
+ */
170
215
  getSnapshot() {
171
216
  return pubSubStore.get(this.pubSubKey);
172
217
  }
173
- // Set the value of the shared state.
218
+ /** Set the value of the shared state. */
174
219
  setValue(next) {
175
220
  if (typeof next === "function") {
176
221
  const prev = pubSubStore.get(this.pubSubKey);
177
222
  next = next(prev);
178
223
  }
179
224
  pubSubStore.set(this.pubSubKey, next);
180
- void this.storageAdapter?.set(STORAGE_KEY, next);
225
+ void this.setInStore(next);
181
226
  }
182
- // Remove the value of the shared state. Actually this just sets the value
183
- // back to the given default value.
227
+ /**
228
+ * Remove the value of the shared state. Actually this just sets the value
229
+ * back to the given default value.
230
+ */
184
231
  delete() {
185
232
  pubSubStore.set(this.pubSubKey, this.defaultValue);
186
233
  void this.storageAdapter?.set(STORAGE_KEY, this.defaultValue);
187
234
  }
188
- // Initial default handling
235
+ /** Initial default handling. */
189
236
  async initDefaultValueOnce() {
190
237
  if (this.initDone || this.initStarted) return;
191
238
  this.initStarted = true;
192
- const v = await this.storageAdapter?.get(STORAGE_KEY);
193
- const value = v !== void 0 ? v : this.defaultValue;
239
+ const stored = await this.getFromStore();
240
+ const value = stored !== void 0 ? stored : this.defaultValue;
194
241
  pubSubStore.set(this.pubSubKey, value);
195
242
  this.initDone = true;
196
- pubSubStore.set(this.pubSubKey, value);
197
243
  }
198
244
  };
199
245
  function sharedState(defaultValue, options) {
package/sharedState.cjs CHANGED
@@ -35,6 +35,7 @@ var import_react = require("react");
35
35
  // src/storage.ts
36
36
  var import_kvStore = require("@choksheak/ts-utils/kvStore");
37
37
  var import_localStore = require("@choksheak/ts-utils/localStore");
38
+ var IS_NOT_BROWSER = typeof window === "undefined";
38
39
  function getStorageAdapter(options, defaultStoreExpiryMs) {
39
40
  const { store } = options ?? {};
40
41
  if (!store) {
@@ -42,6 +43,7 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
42
43
  }
43
44
  if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
44
45
  const expiryMs = store.expiryMs || defaultStoreExpiryMs;
46
+ const isValid = store.isValid;
45
47
  switch (store.persistTo) {
46
48
  case "localStorage": {
47
49
  const adapter = new import_localStore.LocalStore(store.key, {
@@ -49,40 +51,58 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
49
51
  });
50
52
  return {
51
53
  set: (key, value) => {
52
- if (typeof window === "undefined") return;
54
+ if (IS_NOT_BROWSER) return;
53
55
  adapter.set(key, value);
54
56
  },
55
57
  get: (key) => {
56
- if (typeof window === "undefined") return void 0;
57
- return adapter.get(key);
58
+ if (IS_NOT_BROWSER) return void 0;
59
+ const value = adapter.get(key);
60
+ if (isValid && !isValid(value)) {
61
+ console.warn(
62
+ `localStorage adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`
63
+ );
64
+ adapter.delete(key);
65
+ return void 0;
66
+ }
67
+ return value;
58
68
  },
59
69
  delete: (key) => {
60
- if (typeof window === "undefined") return;
70
+ if (IS_NOT_BROWSER) return;
61
71
  adapter.delete(key);
62
72
  },
63
73
  clear: () => {
64
- if (typeof window === "undefined") return;
74
+ if (IS_NOT_BROWSER) return;
65
75
  adapter.clear();
66
76
  }
67
77
  };
68
78
  }
69
79
  case "indexedDb": {
70
80
  const keyPrefix = store.key + ":";
81
+ const isValid2 = store.isValid;
71
82
  return {
72
83
  set: async (key, value) => {
73
- if (typeof window === "undefined") return;
84
+ if (IS_NOT_BROWSER) return;
74
85
  await import_kvStore.kvStore.set(keyPrefix + key, value, expiryMs);
75
86
  },
76
87
  get: async (key) => {
77
- if (typeof window === "undefined") return void 0;
78
- return await import_kvStore.kvStore.get(keyPrefix + key);
88
+ if (IS_NOT_BROWSER) return void 0;
89
+ const fullKey = keyPrefix + key;
90
+ const value = await import_kvStore.kvStore.get(fullKey);
91
+ if (isValid2 && !isValid2(value)) {
92
+ console.warn(
93
+ `indexedDb adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`
94
+ );
95
+ await import_kvStore.kvStore.delete(fullKey);
96
+ return void 0;
97
+ }
98
+ return value;
79
99
  },
80
100
  delete: async (key) => {
81
- if (typeof window === "undefined") return;
101
+ if (IS_NOT_BROWSER) return;
82
102
  await import_kvStore.kvStore.delete(keyPrefix + key);
83
103
  },
84
104
  clear: async () => {
85
- if (typeof window === "undefined") return;
105
+ if (IS_NOT_BROWSER) return;
86
106
  await import_kvStore.kvStore.clear();
87
107
  }
88
108
  };
@@ -183,39 +203,65 @@ var SharedState = class {
183
203
  setValueBounded;
184
204
  initStarted = false;
185
205
  initDone = false;
186
- // `subscribe` function required by useSyncExternalStore
206
+ /** `subscribe` function required by useSyncExternalStore. */
187
207
  subscribe(subscriber) {
188
208
  return pubSubStore.subscribe(this.pubSubKey, () => subscriber());
189
209
  }
190
- // Get the value of the shared state.
191
- // `getSnapshot` function — must return same ref if value unchanged
210
+ /** Returns true if there is a backing store. */
211
+ hasStore() {
212
+ return Boolean(this.storageAdapter);
213
+ }
214
+ /**
215
+ * Set a value directly into the store. Does nothing if there is no
216
+ * backing store.
217
+ *
218
+ * Warning: If you want to set the value properly, you should use
219
+ * `setValue()` instead which also updates the in-memory copy.
220
+ */
221
+ async setInStore(value) {
222
+ return await this.storageAdapter?.set(STORAGE_KEY, value);
223
+ }
224
+ /**
225
+ * Get a value directly from the store. Returns undefined if there is no
226
+ * backing store.
227
+ */
228
+ async getFromStore() {
229
+ return await this.storageAdapter?.get(STORAGE_KEY);
230
+ }
231
+ /**
232
+ * Get the value of the shared state.
233
+ * `getSnapshot` function — must return same ref if value unchanged.
234
+ * Note that this would return the default value if data init from store is
235
+ * not completed yet.
236
+ */
192
237
  getSnapshot() {
193
238
  return pubSubStore.get(this.pubSubKey);
194
239
  }
195
- // Set the value of the shared state.
240
+ /** Set the value of the shared state. */
196
241
  setValue(next) {
197
242
  if (typeof next === "function") {
198
243
  const prev = pubSubStore.get(this.pubSubKey);
199
244
  next = next(prev);
200
245
  }
201
246
  pubSubStore.set(this.pubSubKey, next);
202
- void this.storageAdapter?.set(STORAGE_KEY, next);
247
+ void this.setInStore(next);
203
248
  }
204
- // Remove the value of the shared state. Actually this just sets the value
205
- // back to the given default value.
249
+ /**
250
+ * Remove the value of the shared state. Actually this just sets the value
251
+ * back to the given default value.
252
+ */
206
253
  delete() {
207
254
  pubSubStore.set(this.pubSubKey, this.defaultValue);
208
255
  void this.storageAdapter?.set(STORAGE_KEY, this.defaultValue);
209
256
  }
210
- // Initial default handling
257
+ /** Initial default handling. */
211
258
  async initDefaultValueOnce() {
212
259
  if (this.initDone || this.initStarted) return;
213
260
  this.initStarted = true;
214
- const v = await this.storageAdapter?.get(STORAGE_KEY);
215
- const value = v !== void 0 ? v : this.defaultValue;
261
+ const stored = await this.getFromStore();
262
+ const value = stored !== void 0 ? stored : this.defaultValue;
216
263
  pubSubStore.set(this.pubSubKey, value);
217
264
  this.initDone = true;
218
- pubSubStore.set(this.pubSubKey, value);
219
265
  }
220
266
  };
221
267
  function sharedState(defaultValue, options) {