{"name":"@solid-primitives/storage","version":"4.0.0","description":"Primitive that provides reactive wrappers for storage access","author":{"name":"Alex Lohr","email":"alex.lohr@logmein.com"},"contributors":[{"name":"Tom Pichaud","email":"dev.tompichaud@icloud.com"}],"license":"MIT","homepage":"https://primitives.solidjs.community/package/storage","repository":{"type":"git","url":"git+https://github.com/solidjs-community/solid-primitives.git"},"primitive":{"name":"storage","stage":3,"list":["makePersisted","cookieStorage","tauriStorage","multiplexStorage","storageSync","messageSync","wsSync","multiplexSync","addClearMethod","addWithOptionsMethod","makeObjectStorage"],"category":"Browser APIs"},"private":false,"sideEffects":false,"type":"module","main":"./dist/index/index.cjs","module":"./dist/index/index.js","types":"./dist/index/index.d.ts","browser":{},"exports":{".":{"import":{"types":"./dist/index/index.d.ts","default":"./dist/index/index.js"},"require":{"types":"./dist/index/index.d.cts","default":"./dist/index/index.cjs"}},"./tauri":{"import":{"types":"./dist/tauri/index.d.ts","default":"./dist/tauri/index.js"},"require":{"types":"./dist/tauri/index.d.cts","default":"./dist/tauri/index.cjs"}}},"typesVersions":{"*":{"tauri":["./dist/tauri/index.d.ts"]}},"keywords":["localStorage","sessionStorage","cookies","solid","primitives"],"dependencies":{"@solid-primitives/utils":"^6.2.3"},"peerDependencies":{"@tauri-apps/plugin-store":"*","solid-js":"^1.6.12"},"peerDependenciesMeta":{"solid-start":{"optional":true},"@tauri-apps/plugin-store":{"optional":true}},"devDependencies":{"solid-js":"^1.8.15"},"scripts":{"dev":"tsx ../../scripts/dev.ts","build":"tsx ../../scripts/build.ts","vitest":"vitest -c ../../configs/vitest.config.ts","test":"pnpm run vitest","test:ssr":"pnpm run vitest --mode ssr"},"_id":"@solid-primitives/storage@4.0.0","bugs":{"url":"https://github.com/solidjs-community/solid-primitives/issues"},"_integrity":"sha512-Lq5otUGZw4tfv8OcBxU1r/ZkO38ibH5IqVLhF8sk7tObI8Hs5dRLxwKDIuk9hG03qeOZzH72Fc1NQij+UAQWaw==","_resolved":"/tmp/8574b8a02e33533aeea9e500046d895f/solid-primitives-storage-4.0.0.tgz","_from":"file:solid-primitives-storage-4.0.0.tgz","_nodeVersion":"18.20.4","_npmVersion":"10.7.0","dist":{"integrity":"sha512-Lq5otUGZw4tfv8OcBxU1r/ZkO38ibH5IqVLhF8sk7tObI8Hs5dRLxwKDIuk9hG03qeOZzH72Fc1NQij+UAQWaw==","shasum":"907cff187df796ed029c63097a7f7ee80b9633b2","tarball":"http://registry-npm.ywwl.com/@solid-primitives/storage/download/@solid-primitives/storage-4.0.0.tgz","fileCount":13,"unpackedSize":51168,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCNwpaaGH7Vx0XZBH/ED2RFj8jSiktWmomA2atDOQ7vUgIgZR3IOuIXnLJoXU12AYDQfjZSsCvzp7bqapagoSLs7A0="}],"size":12614,"noattachment":false,"key":"/@solid-primitives/storage/-/@solid-primitives/storage-4.0.0.tgz"},"_npmUser":{"name":"thetarnav.","email":"gthetarnav@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/storage_4.0.0_1723374953273_0.6658517408281031"},"_hasShrinkwrap":false,"readme":"<p>\n  <img width=\"100%\" src=\"https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=Storage\" alt=\"Solid Primitives Storage\">\n</p>\n\n# @solid-primitives/storage\n\n[![turborepo](https://img.shields.io/badge/built%20with-turborepo-cc00ff.svg?style=for-the-badge&logo=turborepo)](https://turborepo.org/)\n[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/storage?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/storage)\n[![size](https://img.shields.io/npm/v/@solid-primitives/storage?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/storage)\n[![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)\n\nCreates a primitive to reactively access both synchronous and asynchronous persistent storage APIs similar\nto `localStorage`.\n\n## Installation\n\n```\nnpm install @solid-primitives/storage\n# or\nyarn add @solid-primitives/storage\n```\n\n## How to use it\n\n`makePersisted` allows you to persist a signal or store in any synchronous or asynchronous Storage API:\n\n```ts\nconst [signal, setSignal] = makePersisted(createSignal(\"initial\"), {storage: sessionStorage});\nconst [store, setStore] = makePersisted(createStore({test: true}), {name: \"testing\"});\ntype PersistedOptions<Type, StorageOptions> = {\n  // localStorage is default\n  storage?: Storage | StorageWithOptions | AsyncStorage | AsyncStorageWithOptions | LocalForage,\n  // only required for storage APIs with options\n  storageOptions?: StorageOptions,\n  // key in the storage API\n  name?: \"...\",\n  // JSON.stringify is the default\n  serialize?: (value: Type) => value.toString(),\n  // JSON.parse is the default\n  deserialize?: (value: string) => Type(value),\n  // sync API (see below)\n  sync?: PersistenceSyncAPI\n};\n```\n\n- if no storage is given in options, `localStorage` is used\n- if no name is given in options, a unique identifier from `solid-js` will be the default\n- initial values of signals or stores are not persisted, so they can be safely changed\n- values persisted in asynchronous storage APIs will not overwrite already changed signals or stores\n- setting a persisted signal to undefined or null will remove the item from the storage\n- to use `makePersisted` with other state management APIs, you need some adapter that will project your API to either\n  the output of `createSignal` or `createStore`\n\n### Using `makePersisted` with resources\n\nInstead of wrapping the resource itself, it is far simpler to use the `storage` option of the resource to provide a\npersisted signal or [deep signal](../resource/#createdeepsignal):\n\n```ts\nconst [resource] = createResource(fetcher, { storage: makePersisted(createSignal()) });\n```\n\nIf you are using an asynchronous storage to persist the state of a resource, it might receive an update due to being\ninitialized from the storage before or after the fetcher resolved. If the initialization resolves after the fetcher, its\nresult is discarded not to overwrite more current data.\n\n### Different storage APIs\n\n#### LocalStorage, SessionStorage\n\nIn the browser, we already have `localStorage`, which persists values for the same hostname indefinitely,\nand `sessionStorage`, which does the same for the duration of the browser session, but loses persistence after closing\nthe browser.\n\n#### CookieStorage\n\nAs another storage, `cookieStorage` from this package can be used, which is a `localStorage`-like API to set cookies. It\nwill work in the browser and on solid-start, by parsing the `Cookie` and `Set-Cookie` header and altering\nthe `Set-Cookie` header. Using it in the server without solid-start will not cause errors, but reading and setting cookies\nwill not work, unless you supply `getRequestHeaders() => Headers` and `getResponseHeaders => Headers` to the options.\n\n```ts\n// for example, in express.js request and response headers can usually be accessed like this:\nconst cs = cookieStorage.withOptions({\n  getRequestHeaders: () => req.headers,\n  getResponseHeaders: () => res.headers,\n});\n```\n\n> Please mind that `cookieStorage` **doesn't care** about the path and domain when reading cookies. This might cause issues\n> when using multiple cookies with the same key, but different path or domain.\n\n`cookieStorage` has been augmented with the `.withOptions` method that binds options to the other methods. This allows you\nto use predefined options for your persisted state:\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), {\n  storage: cookieStorage.withOptions({ expires: new Date(+new Date() + 3e10) }),\n});\n```\n\n#### LocalForage\n\nLocalForage uses indexedDB or WebSQL if available to greatly increase the size of what can be stored. Just drop it in as a storage (only supported in the client):\n\n```ts\nimport { isServer } from \"solid-js/web\";\nimport { makePersisted } from \"@solid-primtives/storage\";\nimport localforage from \"localforage\";\n\nconst [state, setState] = makePersisted(createSignal(), {\n  storage: !isServer ? localforage : undefined,\n});\n```\n\nKeep in mind that it will only run on the client, so unless you have\n\n#### TauriStorage\n\n[Tauri](https://tauri.app) is a lightweight run-time for desktop (and soon also mobile) applications utilizing web front-end frameworks. While it supports `localStorage` and `sessionStorage`, it also has its own store plugin with the benefit of improved stability. To use it, install the required modules both on the side of JavaScript and Rust after setting up the project with the help of their command-line interface:\n\n```bash\nnpm run tauri add store\n```\n\nAlso, it requires a few permissions in `capabilities/default.json`:\n\n```js\n{\n  // other defaults\n  \"permissions\": [\n    // other permissions\n    \"store:allow-get\",\n    \"store:allow-set\",\n    \"store:allow-delete\",\n    \"store:allow-keys\",\n    \"store:allow-clear\"\n  ]\n}\n```\n\nLastly, initialize the plugin in the setup:\n\n```rs\nfn main() {\n    tauri::Builder::default()\n        // initialize store plugin:\n        .plugin(tauri_plugin_store::Builder::new().build())\n        .run(tauri::generate_context!())\n        .expect(\"error while running tauri application\");\n}\n```\n\nOnce these preparations are finished, `tauriStorage(name?: string)` can be used as another storage option. To fallback to localStorage if the app does not run within tauri, you can check for `window.__TAURI_INTERNALS__`:\n\n```ts\nimport { tauriStorage } from \"@solid-primitives/storage/tauri\";\n\nconst storage = window.__TAURI_INTERNALS__ ? tauriStorage() : localStorage;\n```\n\n#### Object storage\n\nThis package also provides a way to create a storage API wrapper for an object called `makeObjectStorage(object)`. This is especially useful as a server fallback if you want to store the data in your user session or database object:\n\n```ts\nconst [state, setState] = createPersisted(createSignal(), {\n  storage: globalThis.localStorage ?? makeObjectStorage(session.userState),\n});\n```\n\n#### Multiplexed storages\n\nYou may want to persist your state to multiple storages as a fallback solution (e.g. localStorage vs. cookieStorage so it\nworks offline and on the server).\n\nIn order to do so, you can use `multiplexStorage`:\n\n```ts\nconst [mode, setMode] = makePersisted(createSignal(\"dark\"), {\n  name: \"mode\",\n  storage: multiplexStorage(localStorage, cookieStorage),\n});\n```\n\nIf none of your storage APIs is asynchronous, the resulting API is synchronous, otherwise it is async. For the getItem\noperation, the first storage that returns a valid value will be the source of truth. So you need to await deletion and\nwriting before you can rely on the result in case of asynchronous storages.\n\n### Sync API\n\nThe storage API has an interesting functionality: if you set an item in one instance of the same page, other instances\nare notified of the change via the storage event so they can elect to automatically update.\n\n#### storageSync\n\nWith `storageSync`, you can use exactly this API in order to sync to external updates to the same storage.\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), { sync: storageSync });\n```\n\n#### messageSync\n\nWith `messageSync`, you can recreate the same functionality for other storages within the client using either the post message API\nor broadcast channel API. If no argument is given, it is using post message, otherwise provide the broadcast channel as argument\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), {\n  storage: customStorage,\n  sync: messageSync(),\n});\n```\n\n#### wsSync\n\nWith `wsSync`, you can create your synchronization API based on a web socket connection (either created yourself or by our\n`@solid-primitives/websocket` package); this allows synchronization between client and server.\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), { sync: wsSync(makeWs(...)) });\n```\n\n#### multiplexSync\n\nYou can also multiplex different synchronization APIs using multiplexSync:\n\n```ts\nconst [state, setState] = makePersisted(createSignal(), {\n  sync: multiplexSync(storageSync, wsSync(ws)),\n});\n```\n\n#### Custom synchronization API\n\nIf you want to create your own sync API, you can use the following pattern:\n\n```ts\nexport type PersistenceSyncData = {\n  key: string;\n  newValue: string | null | undefined;\n  timeStamp: number;\n  url?: string;\n};\n\nexport type PersistenceSyncCallback = (data: PersistenceSyncData) => void;\n\nexport type PersistenceSyncAPI = [\n  /** subscribes to sync */\n  subscribe: (subscriber: PersistenceSyncCallback) => void,\n  update: (key: string, value: string | null | undefined) => void,\n];\n```\n\nYou can use APIs like Pusher or a WebRTC data connection to synchronize your state.\n\n### Tools\n\nIf you want to build your own Storage and don't want to do a `.clear()` method yourself:\n\n```ts\nconst storageWithClearMethod = addClearMethod(storage_without_clear_method);\n```\n\nIf your storage API supports options and you want to add predefined options so it behaves like an API without options,\nyou can add a `.withOptions` method:\n\n```ts\nconst customStorage = addWithOptionsMethod(storage_supporting_options);\nconst boundCustomStorage = customStorage.withOptions(myOptions);\n```\n\n## Demo\n\n[Live Demo](https://primitives.solidjs.community/playground/storage) - [Sources](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage/dev)\n\n## Changelog\n\nSee [CHANGELOG.md](./CHANGELOG.md)\n","publish_time":1723374953462,"maintainers":[{"name":"thetarnav.","email":"gthetarnav@gmail.com"},{"name":"lexlohr","email":"alex.th.kloss.77@googlemail.com"},{"name":"davedbase","email":"dave.dibiase@gmail.com"}],"_cnpm_publish_time":1723374953462,"dist-tags":{"beta":"1.3.7-beta.0","latest":"4.4.0","next":"5.0.0-next.8"}}