diff --git a/packages/storage/README.md b/packages/storage/README.md index ff1e60c32..8b1cf4b35 100644 --- a/packages/storage/README.md +++ b/packages/storage/README.md @@ -9,7 +9,8 @@ [![size](https://img.shields.io/npm/v/@solid-primitives/storage?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/storage) [![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives#contribution-process) -Creates a primitive to reactively access both synchronous and asynchronous persistent storage APIs similar to `localStorage`. +Creates a primitive to reactively access both synchronous and asynchronous persistent storage APIs similar +to `localStorage`. ## Installation @@ -24,8 +25,8 @@ yarn add @solid-primitives/storage `makePersisted` allows you to persist a signal or store in any synchronous or asynchronous Storage API: ```ts -const [signal, setSignal] = makePersisted(createSignal("initial"), { storage: sessionStorage }); -const [store, setStore] = makePersisted(createStore({ test: true }), { name: "testing" }); +const [signal, setSignal] = makePersisted(createSignal("initial"), {storage: sessionStorage}); +const [store, setStore] = makePersisted(createStore({test: true}), {name: "testing"}); type PersistedOptions = { // localStorage is default storage?: Storage | StorageWithOptions | AsyncStorage | AsyncStorageWithOptions, @@ -45,35 +46,64 @@ type PersistedOptions = { - initial values of signals or stores are not persisted, so they can be safely changed - values persisted in asynchronous storage APIs will not overwrite already changed signals or stores - setting a persisted signal to undefined or null will remove the item from the storage -- to use `makePersisted` with other state management APIs, you need some adapter that will project your API to either the output of `createSignal` or `createStore` +- to use `makePersisted` with other state management APIs, you need some adapter that will project your API to either + the output of `createSignal` or `createStore` ### Using `makePersisted` with resources -Instead of wrapping the resource itself, it is far simpler to use the `storage` option of the resource to provide a persisted signal or [deep signal](../resource/#createdeepsignal): +Instead of wrapping the resource itself, it is far simpler to use the `storage` option of the resource to provide a +persisted signal or [deep signal](../resource/#createdeepsignal): ```ts -const [resource] = createResource(fetcher, { storage: makePersisted(createSignal()) }); +const [resource] = createResource(fetcher, {storage: makePersisted(createSignal())}); ``` -If you are using an asynchronous storage to persist the state of a resource, it might receive an update due to being initialized from the storage before or after the fetcher resolved. If the initialization resolves after the fetcher, its result is discarded not to overwrite more current data. +If you are using an asynchronous storage to persist the state of a resource, it might receive an update due to being +initialized from the storage before or after the fetcher resolved. If the initialization resolves after the fetcher, its +result is discarded not to overwrite more current data. ### Different storage APIs -In the browser, we already have `localStorage`, which persists values for the same hostname indefinitely, and `sessionStorage`, which does the same for the duration of the browser session, but loses persistence after closing the browser. +#### LocalStorage, SessionStorage -As another storage, `cookieStorage` from this package can be used, which is a `localStorage`-like API to set cookies. It will work in the browser and also allows reading cookies on solid-start. Using it in the server without solid-start will not cause errors (unless you are using stackblitz), but instead emit a warning message. You can also supply your own implementations of `cookieStorage._read(key)` and `cookieStorage._write(key, value, options)` if neither of those fit your need. +In the browser, we already have `localStorage`, which persists values for the same hostname indefinitely, +and `sessionStorage`, which does the same for the duration of the browser session, but loses persistence after closing +the browser. -If you are not using solid-start or are using stackblitz and want to use cookieStorage on the server, you can supply optional getRequest (either something like useRequest from solid-start or a function that returns the current request) and setCookie options. +#### CookieStorage -There is also [`localForage`](https://localforage.github.io/localForage/), which uses `IndexedDB`, `WebSQL` or `localStorage` to provide an asynchronous Storage API that can ideally store much more than the few Megabytes that are available in most browsers. +As another storage, `cookieStorage` from this package can be used, which is a `localStorage`-like API to set cookies. It +will work in the browser and on solid-start, by parsing the `Cookie` and `Set-Cookie` header and altering +the `Set-Cookie` header. Using it in the server without solid-start will not cause errors (unless +you are using stackblitz), but instead emit a warning message. You can also supply your own implementations +of `cookieStorage._read(key, options)` and `cookieStorage._write(key, value, options)` if neither of those fit your +need. + +If you are not using solid-start or are using stackblitz and want to use cookieStorage on the server, you can supply +optional `getRequest` (either something like useRequest from solid-start or a function that returns the current request) +and `setCookie` options. + +When you are using vite and solid-start you want to always provide the `useRequest` function from solid start to +the `getRequest` option, because of a technical limitation of vite. + +> Please mind that `cookieStorage` **doesn't care** about the path and domain when reading cookies. This might cause issues when using +> multiple cookies with the same key, but different path or domain. + +#### IndexedDB, WebSQL + +There is also [`localForage`](https://localforage.github.io/localForage/), which uses `IndexedDB`, `WebSQL` +or `localStorage` to provide an asynchronous Storage API that can ideally store much more than the few Megabytes that +are available in most browsers. --- ### Deprecated primitives: -The previous implementation proved to be confusing and cumbersome for most people who just wanted to persist their signals and stores, so they are now deprecated. +The previous implementation proved to be confusing and cumbersome for most people who just wanted to persist their +signals and stores, so they are now deprecated. -`createStorage` is meant to wrap any `localStorage`-like API to be as accessible as a [Solid Store](https://www.solidjs.com/docs/latest/api#createstore). The main differences are +`createStorage` is meant to wrap any `localStorage`-like API to be as accessible as +a [Solid Store](https://www.solidjs.com/docs/latest/api#createstore). The main differences are - that this store is persisted in whatever API is used, - that you can only use the topmost layer of the object and @@ -83,8 +113,11 @@ The previous implementation proved to be confusing and cumbersome for most peopl const [store, setStore, { remove: (key: string) => void; clear: () => void; - toJSON: () => ({ [key: string]: string }); -}] = createStorage({ api: sessionStorage, prefix: 'my-app' }); + toJSON: () => ({[key: string]: string +}) +; +}] += createStorage({api: sessionStorage, prefix: 'my-app'}); setStore('key', 'value'); store.key; // 'value' @@ -93,16 +126,19 @@ store.key; // 'value' The props object support the following parameters: `api` -: An array of or a single `localStorage`-like storage API; default will be `localStorage` if it exists; an empty array or no API will not throw an error, but only ever get `null` and not actually persist anything +: An array of or a single `localStorage`-like storage API; default will be `localStorage` if it exists; an empty array +or no API will not throw an error, but only ever get `null` and not actually persist anything `prefix` : A string that will be prefixed every key inside the API on set and get operations `serializer / deserializer` -: A set of function to filter the input and output; the `serializer` takes an arbitrary object and returns a string, e.g. `JSON.stringify`, whereas the `deserializer` takes a string and returns the requested object again. +: A set of function to filter the input and output; the `serializer` takes an arbitrary object and returns a string, +e.g. `JSON.stringify`, whereas the `deserializer` takes a string and returns the requested object again. `options` -: For APIs that support options as third argument in the `getItem` and `setItem` method (see helper type `StorageWithOptions`), you can add options they will receive on every operation. +: For APIs that support options as third argument in the `getItem` and `setItem` method (see helper +type `StorageWithOptions`), you can add options they will receive on every operation. --- @@ -118,7 +154,9 @@ createCookieStorage(); #### Asynchronous storage APIs -In case you have APIs that persist data on the server or via `ServiceWorker` in a [`CookieStore`](https://wicg.github.io/cookie-store/#CookieStore), you can wrap them into an asynchronous storage (`AsyncStorage` or `AsyncStorageWithOptions` API) and use them with `createAsyncStorage`: +In case you have APIs that persist data on the server or via `ServiceWorker` in +a [`CookieStore`](https://wicg.github.io/cookie-store/#CookieStore), you can wrap them into an asynchronous +storage (`AsyncStorage` or `AsyncStorageWithOptions` API) and use them with `createAsyncStorage`: ```ts type CookieStoreOptions = { @@ -144,36 +182,58 @@ const CookieStoreAPI: AsyncStorageWithOptions = { const all = await cookieStore.getAll(); return Object.keys(all)[index]; } -}); +} +) +; const [cookies, setCookie, { - remove: (key: string) => void; - clear: () => void; - toJSON: () => ({ [key: string]: string }); -}] = createAsyncStorage({ api: CookieStoreAPI, prefix: 'my-app', sync: false }); + remove: (key: string) => void; + clear: () => void; + toJSON: () => ({[key: string]: string +}) +; +}] += createAsyncStorage({api: CookieStoreAPI, prefix: 'my-app', sync: false}); await setStore('key', 'value'); await store.key; // 'value' ``` -It works exactly like a synchronous storage, with the exception that you have to `await` every single return value. Once the `CookieStore` API becomes more prevalent, we will integrate support out of the box. +It works exactly like a synchronous storage, with the exception that you have to `await` every single return value. Once +the `CookieStore` API becomes more prevalent, we will integrate support out of the box. If you cannot use `document.cookie`, you can overwrite the entry point using the following tuple: ```ts -import { cookieStorage } from '@solid-primitives/storage'; - -cookieStorage._cookies = [object: { [name: string]: CookieProxy }, name: string]; +import {cookieStorage} from '@solid-primitives/storage'; + +cookieStorage._cookies = [object +: +{ + [name +: + string +]: + CookieProxy +} +, +name: string +] +; ``` If you need to abstract an API yourself, you can use a getter and a setter: ```ts const CookieAbstraction = { - get cookie() { return myCookieJar.toString() } + get cookie() { + return myCookieJar.toString() + } set cookie(cookie) { const data = {}; - cookie.replace(/([^=]+)=(?:([^;]+);?)/g, (_, key, value) => { data[key] = value }); + cookie.replace(/([^=]+)=(?:([^;]+);?)/g, (_, key, value) => { + data[key] = value + }); myCookieJar.set(data); } } @@ -182,10 +242,11 @@ cookieStorage._cookies = [CookieAbstraction, 'cookie']; --- -`createStorageSignal` is meant for those cases when you only need to conveniently access a single value instead of full access to the storage API: +`createStorageSignal` is meant for those cases when you only need to conveniently access a single value instead of full +access to the storage API: ```ts -const [value, setValue] = createStorageSignal("value", { api: cookieStorage }); +const [value, setValue] = createStorageSignal("value", {api: cookieStorage}); setValue("value"); value(); // 'value' @@ -199,12 +260,15 @@ As a convenient additional method, you can also use `createCookieStorageSignal(k The properties of your `createStorage`/`createAsyncStorage`/`createStorageSignal` props are: -- `api`: the (synchronous or asynchronous) [Storage-like API](https://developer.mozilla.org/de/docs/Web/API/Web_Storage_API), default is `localStorage` +- `api`: the (synchronous or + asynchronous) [Storage-like API](https://developer.mozilla.org/de/docs/Web/API/Web_Storage_API), default + is `localStorage` - `deserializer` (optional): a `deserializer` or parser for the stored data - `serializer` (optional): a `serializer` or string converter for the stored data - `options` (optional): default options for the set-call of Storage-like API, if supported - `prefix` (optional): a prefix for the Storage keys -- `sync` (optional): if set to false, [event synchronization](https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent) is disabled +- `sync` (optional): if set to + false, [event synchronization](https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent) is disabled ### Tools diff --git a/packages/storage/src/cookies.ts b/packages/storage/src/cookies.ts index 837cf105a..b94c88334 100644 --- a/packages/storage/src/cookies.ts +++ b/packages/storage/src/cookies.ts @@ -1,10 +1,15 @@ -import { isServer } from "solid-js/web"; -import { StorageProps, StorageWithOptions, StorageSignalProps } from "./types.js"; -import { addClearMethod } from "./tools.js"; -import { createStorage, createStorageSignal } from "./storage.js"; -import type { PageEvent } from "solid-start"; +import {isServer} from "solid-js/web"; +import {StorageProps, StorageSignalProps, StorageWithOptions} from "./types.js"; +import {addClearMethod} from "./tools.js"; +import {createStorage, createStorageSignal} from "./storage.js"; +import type {PageEvent} from "solid-start"; -export type CookieOptions = { +export type CookieOptions = CookieProperties & { + getRequest?: (() => Request) | (() => PageEvent); + setCookie?: (key: string, value: string, options: CookieOptions) => void; +}; + +type CookieProperties = { domain?: string; expires?: Date | number | String; path?: string; @@ -12,29 +17,34 @@ export type CookieOptions = { httpOnly?: boolean; maxAge?: number; sameSite?: "None" | "Lax" | "Strict"; - getRequest?: (() => Request) | (() => PageEvent); - setCookie?: (key: string, value: string, options: CookieOptions) => void; -}; +} + +const cookiePropertyKeys = ["domain", "expires", "path", "secure", "httpOnly", "maxAge", "sameSite"] as const; -const serializeCookieOptions = (options?: CookieOptions) => { + +function serializeCookieOptions(options?: CookieOptions) { if (!options) { return ""; } let memo = ""; for (const key in options) { - if (!options.hasOwnProperty(key)) { + if (!cookiePropertyKeys.includes(key as keyof CookieProperties)) continue; - } - const value = options[key as keyof CookieOptions]; + + const value = options[key as keyof CookieProperties]; memo += value instanceof Date ? `; ${key}=${value.toUTCString()}` : typeof value === "boolean" - ? `; ${key}` - : `; ${key}=${value}`; + ? `; ${key}` + : `; ${key}=${value}`; } return memo; -}; +} + +function deserializeCookieOptions(cookie: string, key: string) { + return cookie.match(`(^|;)\\s*${key}\\s*=\\s*([^;]+)`)?.pop() ?? null; +} let useRequest: () => PageEvent | undefined; try { @@ -42,11 +52,9 @@ try { } catch (e) { useRequest = () => { // eslint-disable-next-line no-console - console.warn( - "It seems you attempt to use cookieStorage on the server without having solid-start installed", - ); + console.warn("It seems you attempt to use cookieStorage on the server without having solid-start installed or use vite."); return { - request: { headers: { get: () => "" } } as unknown as Request, + request: {headers: {get: () => ""}} as unknown as Request, } as unknown as PageEvent; }; } @@ -64,7 +72,7 @@ try { * httpOnly?: boolean; * maxAge?: number; * sameSite?: "None" | "Lax" | "Strict"; - * getRequest?: () => Request | () => PageEvent // (useRequest from solid-start) + * getRequest?: () => Request | () => PageEvent // useRequest from solid-start, vite users must pass the "useRequest" from "solid-start/server" function manually * setCookie?: (key, value, options) => void // set cookie on the server * }; * ``` @@ -73,42 +81,59 @@ try { export const cookieStorage: StorageWithOptions = addClearMethod({ _read: isServer ? (options?: CookieOptions) => { - const eventOrRequest = options?.getRequest?.() || useRequest(); - const request = - eventOrRequest && ("request" in eventOrRequest ? eventOrRequest.request : eventOrRequest); - return request?.headers.get("Cookie") || ""; + const eventOrRequest = options?.getRequest?.() || useRequest(); + const request = eventOrRequest && ("request" in eventOrRequest ? eventOrRequest.request : eventOrRequest); + let result = "" + if (eventOrRequest.responseHeaders) // Check if we really got a pageEvent + { + const responseHeaders = eventOrRequest.responseHeaders as Headers; + result += responseHeaders.get("Set-Cookie")?.split(",").map(cookie => !cookie.match(/\\w*\\s*=\\s*[^;]+/)).join(";") ?? ""; } + return `${result};${request?.headers?.get("Cookie") ?? ""}`; // because first cookie will be preferred we don't have to worry about duplicates + } : () => document.cookie, _write: isServer - ? (key: string, value: string, options?: CookieOptions) => + ? (key: string, value: string, options?: CookieOptions) => { + if (options?.setCookie) { options?.setCookie?.(key, value, options) + return + } + const pageEvent: PageEvent = options?.getRequest?.() || useRequest(); + if (!pageEvent.responseHeaders) // Check if we really got a pageEvent + return + const responseHeaders = pageEvent.responseHeaders as Headers; + const cookies = responseHeaders.get("Set-Cookie")?.split(",") + .filter((cookie) => !cookie.match(`\\s*${key}\\s*=`)) ?? []; + cookies.push(`${key}=${value}${serializeCookieOptions(options)}`) + responseHeaders.set("Set-Cookie", cookies.join(",")) + } : (key: string, value: string, options?: CookieOptions) => { - document.cookie = `${key}=${value}${serializeCookieOptions(options)}`; - }, + document.cookie = `${key}=${value}${serializeCookieOptions(options)}`; + }, getItem: (key: string, options?: CookieOptions) => - cookieStorage - ._read(options) - .match("(^|;)\\s*" + key + "\\s*=\\s*([^;]+)") - ?.pop() ?? null, + deserializeCookieOptions(cookieStorage._read(options), key), setItem: (key: string, value: string, options?: CookieOptions) => { - const oldValue = cookieStorage.getItem(key); + const oldValue = isServer ? cookieStorage.getItem(key, options) : null; cookieStorage._write(key, value, options); - const storageEvent = Object.assign(new Event("storage"), { - key, - oldValue, - newValue: value, - url: globalThis.document.URL, - storageArea: cookieStorage, - }); - window.dispatchEvent(storageEvent); + if (!isServer) { + // Storage events are only required on client when using multiple tabs + const storageEvent = Object.assign(new Event("storage"), { + key, + oldValue, + newValue: value, + url: globalThis.document.URL, + storageArea: cookieStorage, + }); + window.dispatchEvent(storageEvent); + } }, - removeItem: (key: string) => { - cookieStorage._write(key, "deleted", { expires: new Date(0) }); + removeItem: (key: string, options?: CookieOptions) => { + cookieStorage._write(key, "deleted", {...options, expires: new Date(0)}); }, - key: (index: number) => { + key: (index: number, options?: CookieOptions) => { let key: string | null = null; let count = 0; - cookieStorage._read().replace(/(?:^|;)\s*(.+?)\s*=\s*[^;]+/g, (_: string, found: string) => { + cookieStorage._read(options).replace(/(?:^|;)\s*(.+?)\s*=\s*[^;]+/g, (_: string, found: string) => { if (!key && found && count++ === index) { key = found; } @@ -116,14 +141,17 @@ export const cookieStorage: StorageWithOptions = addClearMethod({ }); return key; }, - get length() { + getLength: (options?: CookieOptions) => { let length = 0; - cookieStorage._read().replace(/(?:^|;)\s*.+?\s*=\s*[^;]+/g, (found: string) => { + cookieStorage._read(options).replace(/(?:^|;)\s*.+?\s*=\s*[^;]+/g, (found: string) => { length += found ? 1 : 0; return ""; }); return length; }, + get length() { + return this.getLength() + } }); /** @@ -132,7 +160,7 @@ export const cookieStorage: StorageWithOptions = addClearMethod({ */ export const createCookieStorage = >( props?: Omit, "api">, -) => createStorage({ ...props, api: cookieStorage } as any); +) => createStorage({...props, api: cookieStorage} as any); /** * creates a reactive signal, but bound to document.cookie @@ -146,4 +174,4 @@ export const createCookieStorageSignal = < key: string, initialValue?: T, props?: Omit, "api">, -) => createStorageSignal(key, initialValue, { ...props, api: cookieStorage } as any); +) => createStorageSignal(key, initialValue, {...props, api: cookieStorage} as any); diff --git a/packages/storage/src/persisted.ts b/packages/storage/src/persisted.ts index 25cc6f30a..57ec258ce 100644 --- a/packages/storage/src/persisted.ts +++ b/packages/storage/src/persisted.ts @@ -1,101 +1,189 @@ -import { createUniqueId, untrack } from "solid-js"; -import { reconcile } from "solid-js/store"; -import type { Accessor, Setter } from "solid-js"; -import type { Store, SetStoreFunction } from "solid-js/store"; -import type { StorageWithOptions, AsyncStorage, AsyncStorageWithOptions } from "./types.js"; +import type {Accessor, Setter, Signal} from "solid-js"; +import {createUniqueId, untrack} from "solid-js"; +import type {SetStoreFunction, Store} from "solid-js/store"; +import {reconcile} from "solid-js/store"; +import type {AsyncStorage, AsyncStorageWithOptions, StorageWithOptions} from "./types.js"; -export type PersistenceOptions = {}> = - | { - storage?: Storage | AsyncStorage; - name?: string; - serialize?: (data: T) => string; - deserialize?: (data: string) => T; - } - | { - storage: StorageWithOptions | AsyncStorageWithOptions; - storageOptions: O; - name?: string; - serialize?: (data: T) => string; - deserialize?: (data: string) => T; - }; +export type PersistenceBaseOptions = { + name?: string; + serialize?: (data: T) => string; + deserialize?: (data: string) => T; +} + +export type PersistenceOptions> = + PersistenceBaseOptions & ( + { + storage: StorageWithOptions | AsyncStorageWithOptions; + storageOptions: O; + } | + { storage?: Storage | AsyncStorage; }) -/* +/** * Persists a signal, store or similar API - * ```ts - * const [getter, setter] = makePersisted(createSignal("data"), options); - * const options = { - * storage: cookieStorage, // can be any synchronous or asynchronous storage - * storageOptions: { ... }, // for storages with options, otherwise not needed - * name: "solid-data", // optional - * serialize: (value: string) => value, // optional - * deserialize: (data: string) => data, // optional - * }; - * ``` - * Can be used with `createSignal` or `createStore`. The initial value from the storage will overwrite the initial value of the signal or store unless overwritten. Overwriting a signal with `null` or `undefined` will remove the item from the storage. + * ```ts + * const [getter, setter] = makePersisted(createSignal("data"), options); + * const options = { + * storage: cookieStorage, // can be any synchronous or asynchronous storage + * storageOptions: { ... }, // for storages with options, otherwise not needed + * name: "solid-data", // optional + * serialize: (value: string) => value, // optional + * deserialize: (data: string) => data, // optional + * }; + * ``` + * Can be used with `createSignal` or `createStore`. The initial value from the storage will overwrite the initial + * value of the signal or store unless overwritten. Overwriting a signal with `null` or `undefined` will remove the + * item from the storage. + * + * @param {Signal | [get: Store, set: SetStoreFunction]} signal - The signal or store to be persisted. + * @param {PersistenceOptions} options - The options for persistence. + * @returns {Signal | [get: Store, set: SetStoreFunction]} - The persisted signal or store. */ export function makePersisted( signal: [Accessor, Setter], - options?: PersistenceOptions, + options?: PersistenceOptions, ): [Accessor, Setter]; + + +/** + * Persists a signal, store or similar API + * ```ts + * const [getter, setter] = makePersisted(createSignal("data"), options); + * const options = { + * storage: cookieStorage, // can be any synchronous or asynchronous storage + * storageOptions: { ... }, // for storages with options, otherwise not needed + * name: "solid-data", // optional + * serialize: (value: string) => value, // optional + * deserialize: (data: string) => data, // optional + * }; + * ``` + * Can be used with `createSignal` or `createStore`. The initial value from the storage will overwrite the initial + * value of the signal or store unless overwritten. Overwriting a signal with `null` or `undefined` will remove the + * item from the storage. + * + * @param {Signal | [get: Store, set: SetStoreFunction]} signal - The signal or store to be persisted. + * @param {PersistenceOptions} options - The options for persistence. + * @returns {Signal | [get: Store, set: SetStoreFunction]} - The persisted signal or store. + */ export function makePersisted>( - signal: [Accessor, Setter], + signal: Signal, options: PersistenceOptions, -): [Accessor, Setter]; +): Signal; + +/** + * Persists a signal, store or similar API + * ```ts + * const [getter, setter] = makePersisted(createSignal("data"), options); + * const options = { + * storage: cookieStorage, // can be any synchronous or asynchronous storage + * storageOptions: { ... }, // for storages with options, otherwise not needed + * name: "solid-data", // optional + * serialize: (value: string) => value, // optional + * deserialize: (data: string) => data, // optional + * }; + * ``` + * Can be used with `createSignal` or `createStore`. The initial value from the storage will overwrite the initial + * value of the signal or store unless overwritten. Overwriting a signal with `null` or `undefined` will remove the + * item from the storage. + * + * @param {Signal | [get: Store, set: SetStoreFunction]} signal - The signal or store to be persisted. + * @param {PersistenceOptions} options - The options for persistence. + * @returns {Signal | [get: Store, set: SetStoreFunction]} - The persisted signal or store. + */ export function makePersisted( - signal: [Store, SetStoreFunction], - options?: PersistenceOptions, -): [Store, SetStoreFunction]; + signal: [get: Store, set: SetStoreFunction], + options?: PersistenceOptions, +): [get: Store, set: SetStoreFunction]; + +/** + * Persists a signal, store or similar API + * ```ts + * const [getter, setter] = makePersisted(createSignal("data"), options); + * const options = { + * storage: cookieStorage, // can be any synchronous or asynchronous storage + * storageOptions: { ... }, // for storages with options, otherwise not needed + * name: "solid-data", // optional + * serialize: (value: string) => value, // optional + * deserialize: (data: string) => data, // optional + * }; + * ``` + * Can be used with `createSignal` or `createStore`. The initial value from the storage will overwrite the initial + * value of the signal or store unless overwritten. Overwriting a signal with `null` or `undefined` will remove the + * item from the storage. + * + * @param {Signal | [get: Store, set: SetStoreFunction]} signal - The signal or store to be persisted. + * @param {PersistenceOptions} options - The options for persistence. + * @returns {Signal | [get: Store, set: SetStoreFunction]} - The persisted signal or store. + */ export function makePersisted>( - signal: [Store, SetStoreFunction], + signal: [get: Store, set: SetStoreFunction], options: PersistenceOptions, -): [Store, SetStoreFunction]; +): [get: Store, set: SetStoreFunction]; + + +/** + * Persists a signal, store or similar API + * ```ts + * const [getter, setter] = makePersisted(createSignal("data"), options); + * const options = { + * storage: cookieStorage, // can be any synchronous or asynchronous storage + * storageOptions: { ... }, // for storages with options, otherwise not needed + * name: "solid-data", // optional + * serialize: (value: string) => value, // optional + * deserialize: (data: string) => data, // optional + * }; + * ``` + * Can be used with `createSignal` or `createStore`. The initial value from the storage will overwrite the initial + * value of the signal or store unless overwritten. Overwriting a signal with `null` or `undefined` will remove the + * item from the storage. + * + * @param {Signal | [get: Store, set: SetStoreFunction]} signal - The signal or store to be persisted. + * @param {PersistenceOptions} options - The options for persistence. + * @returns {Signal | [get: Store, set: SetStoreFunction]} - The persisted signal or store. + */ export function makePersisted = {}>( - signal: [Accessor, Setter] | [Store, SetStoreFunction], + signal: Signal | [get: Store, set: SetStoreFunction], options: PersistenceOptions = {}, -): [Accessor, Setter] | [Store, SetStoreFunction] { +): Signal | [get: Store, set: SetStoreFunction] { const storage = options.storage || globalThis.localStorage; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!storage) { return signal; } - + const storageOptions = (options as unknown as { storageOptions: O }).storageOptions; const name = options.name || `storage-${createUniqueId()}`; const serialize: (data: T) => string = options.serialize || JSON.stringify.bind(JSON); const deserialize: (data: string) => T = options.deserialize || JSON.parse.bind(JSON); - const init = storage.getItem(name, (options as unknown as { storageOptions: O }).storageOptions); + const init = storage.getItem(name, storageOptions); const set = typeof signal[0] === "function" ? (data: string) => (signal[1] as any)(() => deserialize(data)) : (data: string) => (signal[1] as any)(reconcile(deserialize(data))); let unchanged = true; - if (init instanceof Promise) { + if (init instanceof Promise) init.then(data => unchanged && data && set(data)); - } else if (init) { + else if (init) set(init); - } return [ signal[0], typeof signal[0] === "function" ? (value?: T | ((prev: T) => T)) => { - const output = (signal[1] as Setter)(value as any); - value != null - ? // @ts-ignore - storage.setItem(name, serialize(output), options.storageOptions) - : storage.removeItem(name); - unchanged = false; - return output; - } + const output = (signal[1] as Setter)(value as any); + + if (value) + storage.setItem(name, serialize(output), storageOptions); + else + storage.removeItem(name, storageOptions); + unchanged = false; + return output; + } : (...args: any[]) => { - (signal[1] as any)(...args); - storage.setItem( - name, - serialize(untrack(() => signal[0] as any)), - // @ts-ignore - options.storageOptions, - ); - unchanged = false; - }, + (signal[1] as any)(...args); + const value = serialize(untrack(() => signal[0] as any)); + // @ts-ignore + storage.setItem(name, value, storageOptions); + unchanged = false; + }, ] as typeof signal; } diff --git a/packages/storage/src/types.ts b/packages/storage/src/types.ts index 6a232ce53..f058897bd 100644 --- a/packages/storage/src/types.ts +++ b/packages/storage/src/types.ts @@ -1,10 +1,11 @@ export type StorageWithOptions = { - clear: () => void; + clear: (options?: O) => void; getItem: (key: string, options?: O) => string | null; - getAll?: () => { [key: string]: any }; + getAll?: (options?: O) => { [key: string]: any }; setItem: (key: string, value: string, options?: O) => void; - removeItem: (key: string) => void; - key: (index: number) => string | null; + removeItem: (key: string, options?: O) => void; + key: (index: number, options?: O) => string | null; + getLength?: (options?: O) => number | undefined; readonly length: number | undefined; [key: string]: any; };