snapshot of https://github.com/tauri-apps/plugins-workspace.git (v2, 2026-09-23; blobs > 131072B omitted)
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-23 17:17:10 +05:00
commit 9ad64ec987
1469 changed files with 115067 additions and 0 deletions

153
plugins/store/CHANGELOG.md Normal file
View File

@@ -0,0 +1,153 @@
# Changelog
## [2.4.5]
- [`c050e073`](https://github.com/tauri-apps/plugins-workspace/commit/c050e073b68205bae7389fb86958cb9331e1a3be) ([#3572](https://github.com/tauri-apps/plugins-workspace/pull/3572) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix `apply_pending_auto_save` can deadlock the store
## \[2.4.4]
- [`2ed6d6c1`](https://github.com/tauri-apps/plugins-workspace/commit/2ed6d6c1de4f5051b87cb6a2c5ac45320c444989) ([#3499](https://github.com/tauri-apps/plugins-workspace/pull/3499) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix `StoreOptions` requires `defaults` field
## \[2.4.3]
- [`964e13f1`](https://github.com/tauri-apps/plugins-workspace/commit/964e13f124ad1feeb93c10168b265dc4936f738c) ([#3395](https://github.com/tauri-apps/plugins-workspace/pull/3395) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix a deadlock when calling `Store::set` while exiting (on `RunEvent::Exit`)
## \[2.4.2]
- [`eebfd2ed`](https://github.com/tauri-apps/plugins-workspace/commit/eebfd2ed3e4bae4ef195f20c992f01657a5f5121) ([#3157](https://github.com/tauri-apps/plugins-workspace/pull/3157) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Return an error instead of panic when the internally tracked resource id is invalid on creating new stores
## \[2.4.1]
- [`93426f85`](https://github.com/tauri-apps/plugins-workspace/commit/93426f85120f49beb9f40222bff45185a32d54a9) Fixed an issue that caused docs.rs builds to fail. No user facing changes.
## \[2.4.0]
- [`5ac8fbb1`](https://github.com/tauri-apps/plugins-workspace/commit/5ac8fbb1fa76714aa8cc9c0d74e0aebab12f9755) ([#2857](https://github.com/tauri-apps/plugins-workspace/pull/2857) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Allow setting defaults from the JavaScript API
- [`5ac8fbb1`](https://github.com/tauri-apps/plugins-workspace/commit/5ac8fbb1fa76714aa8cc9c0d74e0aebab12f9755) ([#2857](https://github.com/tauri-apps/plugins-workspace/pull/2857) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Add an new option `overrideDefaults` for creating/loading and reloading the store that overrides the store with the on-disk state, ignoring defaults
## \[2.3.0]
- [`f209b2f2`](https://github.com/tauri-apps/plugins-workspace/commit/f209b2f23cb29133c97ad5961fb46ef794dbe063) ([#2804](https://github.com/tauri-apps/plugins-workspace/pull/2804) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated tauri to 2.6
## \[2.2.1]
- [`f634e524`](https://github.com/tauri-apps/plugins-workspace/commit/f634e5248ebe428f8305a59f74c13fc15147fb8e) This is an "empty" release to update the plugins' source files on crates.io and docs.rs. This should fix docs.rs build failures for projects using tauri plugins as dependencies.
## \[2.2.0]
- [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
## \[2.1.0]
### feat
- [`8c67d44a`](https://github.com/tauri-apps/plugins-workspace/commit/8c67d44aef60b1427019538d8420787ef35bd3d5) ([#1860](https://github.com/tauri-apps/plugins-workspace/pull/1860) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) - Add `getStore`
- Add an option to use pre-stored (de)serialize functions (registered on rust)
- Add `LazyStore`
## \[2.0.1]
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
## \[2.0.0]
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
## \[2.0.0-rc.2]
- [`f12d3560`](https://github.com/tauri-apps/plugins-workspace/commit/f12d35609ab84f536c0f087665fdc1f978af3093) ([#1550](https://github.com/tauri-apps/plugins-workspace/pull/1550) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) **Breaking change**: Removed the `Store` constructor and added the `createStore` API.
## \[2.0.0-rc.1]
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
## \[2.0.0-rc.2]
- [`b9147758`](https://github.com/tauri-apps/plugins-workspace/commit/b914775898c2bee7ceb20bd17ee595005cd17a64) ([#1679](https://github.com/tauri-apps/plugins-workspace/pull/1679) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Explicitly set a minimum macOS version for the Swift package.
## \[2.0.0-rc.1]
### changes
- [`6b079cfd`](https://github.com/tauri-apps/plugins-workspace/commit/6b079cfdd107c94abc2c7300f6af00bac3ff4040) ([#1649](https://github.com/tauri-apps/plugins-workspace/pull/1649) by [@ahqsoftwares](https://github.com/tauri-apps/plugins-workspace/../../ahqsoftwares)) Remove targetSdk from build.kts files as it is deprecated and will be removed from DSL v9.0
## \[2.0.0-rc.0]
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
## \[2.0.0-beta.8]
- [`99d6ac0f`](https://github.com/tauri-apps/plugins-workspace/commit/99d6ac0f9506a6a4a1aa59c728157190a7441af6) ([#1606](https://github.com/tauri-apps/plugins-workspace/pull/1606) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) The JS packages now specify the *minimum* `@tauri-apps/api` version instead of a single exact version.
- [`6de87966`](https://github.com/tauri-apps/plugins-workspace/commit/6de87966ecc00ad9d91c25be452f1f46bd2b7e1f) ([#1597](https://github.com/tauri-apps/plugins-workspace/pull/1597) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Update to tauri beta.25.
## \[2.0.0-beta.7]
- [`22a17980`](https://github.com/tauri-apps/plugins-workspace/commit/22a17980ff4f6f8c40adb1b8f4ffc6dae2fe7e30) ([#1537](https://github.com/tauri-apps/plugins-workspace/pull/1537) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri beta.24.
## \[2.0.0-beta.6]
- [`76daee7a`](https://github.com/tauri-apps/plugins-workspace/commit/76daee7aafece34de3092c86e531cf9eb1138989) ([#1512](https://github.com/tauri-apps/plugins-workspace/pull/1512) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update to tauri beta.23.
## \[2.0.0-beta.5]
- [`9013854f`](https://github.com/tauri-apps/plugins-workspace/commit/9013854f42a49a230b9dbb9d02774765528a923f)([#1382](https://github.com/tauri-apps/plugins-workspace/pull/1382)) Update to tauri beta.22.
## \[2.0.0-beta.4]
- [`430bd6f4`](https://github.com/tauri-apps/plugins-workspace/commit/430bd6f4f379bee5d232ae6b098ae131db7f178a)([#1363](https://github.com/tauri-apps/plugins-workspace/pull/1363)) Update to tauri beta.20.
## \[2.0.0-beta.3]
- [`bd1ed590`](https://github.com/tauri-apps/plugins-workspace/commit/bd1ed5903ffcce5500310dac1e59e8c67674ef1e)([#1237](https://github.com/tauri-apps/plugins-workspace/pull/1237)) Update to tauri beta.17.
## \[2.0.0-beta.5]
- [`bb51a41`](https://github.com/tauri-apps/plugins-workspace/commit/bb51a41d67ebf989e8aedf10c4b1a7f9514d1bdf)([#1168](https://github.com/tauri-apps/plugins-workspace/pull/1168)) **Breaking Change:** All apis that return paths to the frontend will now remove the `\\?\` UNC prefix on Windows.
## \[2.0.0-beta.4]
- [`a04ea2f`](https://github.com/tauri-apps/plugins-workspace/commit/a04ea2f38294d5a3987578283badc8eec87a7752)([#1071](https://github.com/tauri-apps/plugins-workspace/pull/1071)) The global API script is now only added to the binary when the `withGlobalTauri` config is true.
## \[2.0.0-beta.3]
- [`79691e9`](https://github.com/tauri-apps/plugins-workspace/commit/79691e93e04b820e44dce1c7d91b8865fa6ccb14)([#1040](https://github.com/tauri-apps/plugins-workspace/pull/1040)) Fix `with_store` and `StoreCollection` changed to private in #1011
## \[2.0.0-beta.2]
- [`99bea25`](https://github.com/tauri-apps/plugins-workspace/commit/99bea2559c2c0648c2519c50a18cd124dacef57b)([#1005](https://github.com/tauri-apps/plugins-workspace/pull/1005)) Update to tauri beta.8.
## \[2.0.0-beta.1]
- [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
## \[2.0.0-beta.0]
- [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
## \[2.0.0-alpha.5]
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.13.
## \[2.0.0-alpha.4]
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.12.
## \[2.0.0-alpha.3]
- [`e438e0a`](https://github.com/tauri-apps/plugins-workspace/commit/e438e0a62d4b430a5159f05f13ecd397dd891a0d)([#676](https://github.com/tauri-apps/plugins-workspace/pull/676)) Update to @tauri-apps/api v2.0.0-alpha.11.
## \[2.0.0-alpha.2]
- [`5c13736`](https://github.com/tauri-apps/plugins-workspace/commit/5c137365c60790e8d4037d449e8237aa3fffdab0)([#673](https://github.com/tauri-apps/plugins-workspace/pull/673)) Update to @tauri-apps/api v2.0.0-alpha.9.
## \[2.0.0-alpha.2]
- [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
## \[2.0.0-alpha.1]
- [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
## \[2.0.0-alpha.0]
- [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!

43
plugins/store/Cargo.toml Normal file
View File

@@ -0,0 +1,43 @@
[package]
name = "tauri-plugin-store"
version = "2.4.5"
description = "Simple, persistent key-value store."
authors = { workspace = true }
license = { workspace = true }
edition = { workspace = true }
rust-version = { workspace = true }
repository = { workspace = true }
links = "tauri-plugin-store"
exclude = [
"/banner.png",
"/examples",
"/guest-js",
"/package.json",
"/rollup.config.js",
"/tsconfig.json",
]
[package.metadata.platforms.support]
windows = { level = "full", notes = "" }
linux = { level = "full", notes = "" }
macos = { level = "full", notes = "" }
android = { level = "full", notes = "" }
ios = { level = "full", notes = "" }
[build-dependencies]
tauri-plugin = { workspace = true, features = ["build"] }
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
tracing = { workspace = true }
thiserror = { workspace = true }
dunce = { workspace = true }
tokio = { version = "1", features = ["sync", "time", "macros"] }
[target.'cfg(target_os = "ios")'.dependencies]
tauri = { workspace = true, features = ["wry"] }
[dev-dependencies]
tauri = { workspace = true, features = ["wry"] }

View File

@@ -0,0 +1,20 @@
SPDXVersion: SPDX-2.1
DataLicense: CC0-1.0
PackageName: tauri
DataFormat: SPDXRef-1
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
PackageHomePage: https://tauri.app
PackageLicenseDeclared: Apache-2.0
PackageLicenseDeclared: MIT
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
and small desktop applications using a web frontend.
</text>
PackageComment: <text>The package includes the following libraries; see
Relationship information.
</text>
Created: 2019-05-20T09:00:00Z
PackageDownloadLocation: git://github.com/tauri-apps/tauri
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
Creator: Person: Daniel Thompson-Yvetot

View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

21
plugins/store/LICENSE_MIT Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 - Present Tauri Apps Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

157
plugins/store/README.md Normal file
View File

@@ -0,0 +1,157 @@
![plugin-store](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/store/banner.png)
Simple, persistent key-value store.
| Platform | Supported |
| -------- | --------- |
| Linux | ✓ |
| Windows | ✓ |
| macOS | ✓ |
| Android | ✓ |
| iOS | ✓ |
## Install
_This plugin requires a Rust version of at least **1.77.2**_
There are three general methods of installation that we can recommend.
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
2. Pull sources directly from Github using git tags / revision hashes (most secure)
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
Install the Core plugin by adding the following to your `Cargo.toml` file:
`src-tauri/Cargo.toml`
```toml
[dependencies]
tauri-plugin-store = "2.0.0"
# alternatively with Git:
tauri-plugin-store = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
```sh
pnpm add @tauri-apps/plugin-store
# or
npm add @tauri-apps/plugin-store
# or
yarn add @tauri-apps/plugin-store
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/lib.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_store::Builder::default().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```typescript
import { Store } from '@tauri-apps/plugin-store'
const store = await Store.load('settings.json')
await store.set('some-key', { value: 5 })
const val = await store.get<{ value: number }>('some-key')
if (val) {
console.log(val)
} else {
console.log('val is null')
}
```
### Persisting Values
Modifications made to the store are automatically saved by default
You can manually save a store with:
```javascript
await store.save()
```
Stores are loaded automatically when used from the JavaScript bindings.
However, you can also load them manually later like so:
```javascript
await store.load()
```
### LazyStore
There's also a high level API `LazyStore` which only loads the store on first access, note that the options will be ignored if a `Store` with that path has already been created
```typescript
import { LazyStore } from '@tauri-apps/plugin-store'
const store = new LazyStore('settings.json')
```
## Usage from Rust
You can also create `Store` instances directly in Rust:
```rust
use tauri_plugin_store::StoreExt;
use serde_json::json;
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_store::Builder::default().build())
.setup(|app| {
// This loads the store from disk
let store = app.store("app_data.json")?;
// Note that values must be serde_json::Value instances,
// otherwise, they will not be compatible with the JavaScript bindings.
store.set("a".to_string(), json!("b"));
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
### Frontend Interoperability
The store created from both Rust side and JavaScript side are stored in the app's resource table and can be accessed by both sides, you can access it by using the same path, with `getStore` and `LazyStore` in the JavaScript side and `get_store` and `store` in the Rust side
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Partners
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
</tr>
</tbody>
</table>
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.

23
plugins/store/SECURITY.md Normal file
View File

@@ -0,0 +1,23 @@
# Security Policy
**Do not report security vulnerabilities through public GitHub issues.**
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
Include as much of the following information:
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
- The location of the affected source code (tag/branch/commit or direct URL)
- Any special configuration required to reproduce the issue
- The distribution affected or used to help us with reproduction of the issue
- Step-by-step instructions to reproduce the issue
- Ideally a reproduction repository
- Impact of the issue, including how an attacker might exploit the issue
We prefer to receive reports in English.
## Contact
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).

View File

@@ -0,0 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_STORE__=function(t,e,a){"use strict";async function s(t,e){return await i.load(t,e)}class i extends a.Resource{constructor(t){super(t)}static async load(t,e){const s=await a.invoke("plugin:store|load",{path:t,options:e});return new i(s)}static async get(t){return await a.invoke("plugin:store|get_store",{path:t}).then(t=>t?new i(t):null)}async set(t,e){await a.invoke("plugin:store|set",{rid:this.rid,key:t,value:e})}async get(t){const[e,s]=await a.invoke("plugin:store|get",{rid:this.rid,key:t});return s?e:void 0}async has(t){return await a.invoke("plugin:store|has",{rid:this.rid,key:t})}async delete(t){return await a.invoke("plugin:store|delete",{rid:this.rid,key:t})}async clear(){await a.invoke("plugin:store|clear",{rid:this.rid})}async reset(){await a.invoke("plugin:store|reset",{rid:this.rid})}async keys(){return await a.invoke("plugin:store|keys",{rid:this.rid})}async values(){return await a.invoke("plugin:store|values",{rid:this.rid})}async entries(){return await a.invoke("plugin:store|entries",{rid:this.rid})}async length(){return await a.invoke("plugin:store|length",{rid:this.rid})}async reload(t){await a.invoke("plugin:store|reload",{rid:this.rid,...t})}async save(){await a.invoke("plugin:store|save",{rid:this.rid})}async onKeyChange(t,a){return await e.listen("store://change",e=>{e.payload.resourceId===this.rid&&e.payload.key===t&&a(e.payload.exists?e.payload.value:void 0)})}async onChange(t){return await e.listen("store://change",e=>{e.payload.resourceId===this.rid&&t(e.payload.key,e.payload.exists?e.payload.value:void 0)})}}return t.LazyStore=class{get store(){return this._store||(this._store=s(this.path,this.options)),this._store}constructor(t,e){this.path=t,this.options=e}async init(){await this.store}async set(t,e){return(await this.store).set(t,e)}async get(t){return(await this.store).get(t)}async has(t){return(await this.store).has(t)}async delete(t){return(await this.store).delete(t)}async clear(){await(await this.store).clear()}async reset(){await(await this.store).reset()}async keys(){return(await this.store).keys()}async values(){return(await this.store).values()}async entries(){return(await this.store).entries()}async length(){return(await this.store).length()}async reload(t){await(await this.store).reload(t)}async save(){await(await this.store).save()}async onKeyChange(t,e){return(await this.store).onKeyChange(t,e)}async onChange(t){return(await this.store).onChange(t)}async close(){this._store&&await(await this._store).close()}},t.Store=i,t.getStore=async function(t){return await i.get(t)},t.load=s,t}({},window.__TAURI__.event,window.__TAURI__.core);Object.defineProperty(window.__TAURI__,"store",{value:__TAURI_PLUGIN_STORE__})}

BIN
plugins/store/banner.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

26
plugins/store/build.rs Normal file
View File

@@ -0,0 +1,26 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
const COMMANDS: &[&str] = &[
"load",
"get_store",
"set",
"get",
"has",
"delete",
"clear",
"reset",
"keys",
"values",
"entries",
"length",
"reload",
"save",
];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.build();
}

View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
#dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,3 @@
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}

View File

@@ -0,0 +1,7 @@
# Tauri + Vanilla TS
This template should help get you started developing with Tauri in vanilla HTML, CSS and Typescript.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)

View File

@@ -0,0 +1,54 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="/src/styles.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri App</title>
<script type="module" src="/src/main.ts" defer></script>
<style>
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.typescript:hover {
filter: drop-shadow(0 0 2em #2d79c7);
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to Tauri!</h1>
<div class="row">
<a href="https://vitejs.dev" target="_blank">
<img src="/src/assets/vite.svg" class="logo vite" alt="Vite logo" />
</a>
<a href="https://tauri.app" target="_blank">
<img
src="/src/assets/tauri.svg"
class="logo tauri"
alt="Tauri logo"
/>
</a>
<a href="https://www.typescriptlang.org/docs" target="_blank">
<img
src="/src/assets/typescript.svg"
class="logo typescript"
alt="typescript logo"
/>
</a>
</div>
<p>Click on the Tauri logo to learn more about the framework</p>
<!-- <form class="row" id="greet-form">
<input id="greet-input" placeholder="Enter a name..." />
<button type="submit">Greet</button>
</form> -->
<p id="greet-msg"></p>
</div>
</body>
</html>

View File

@@ -0,0 +1,15 @@
{
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"devDependencies": {
"@tauri-apps/cli": "2.11.4",
"typescript": "^6.0.3",
"vite": "^8.0.16"
}
}

View File

@@ -0,0 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
/target/
gen/schemas

View File

@@ -0,0 +1,19 @@
[package]
name = "app_settings_manager"
version = "0.0.0"
description = "A Tauri App"
authors = ["you"]
license = ""
repository = ""
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { workspace = true }
[dependencies]
tauri = { workspace = true, features = ["wry", "common-controls-v6", "x11"] }
serde = { workspace = true }
serde_json = { workspace = true }
tauri-plugin-store = { path = "../../../" }

View File

@@ -0,0 +1,7 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
fn main() {
tauri_build::build()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -0,0 +1,5 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub mod settings;

View File

@@ -0,0 +1,30 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri_plugin_store::Store;
#[derive(Debug, Clone)]
pub struct AppSettings {
pub launch_at_login: bool,
pub theme: String,
}
impl<R: tauri::Runtime> From<&Store<R>> for AppSettings {
fn from(store: &Store<R>) -> Self {
let launch_at_login = store
.get("appSettings.launchAtLogin")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let theme = store
.get("appSettings.theme")
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_else(|| "dark".to_owned());
AppSettings {
launch_at_login,
theme,
}
}
}

View File

@@ -0,0 +1,41 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use serde_json::json;
use tauri::Listener;
use tauri_plugin_store::StoreExt;
mod app;
use app::settings::AppSettings;
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_store::Builder::new().build())
.setup(|app| {
// Init store and load it from disk
let store = app.store("settings.json")?;
app.listen("store://change", |event| {
dbg!(event);
});
let app_settings = AppSettings::from(store.as_ref());
let theme = app_settings.theme;
let launch_at_login = app_settings.launch_at_login;
println!("theme {theme}");
println!("launch_at_login {launch_at_login}");
store.set(
"appSettings",
json!({ "theme": theme, "launchAtLogin": launch_at_login }),
);
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@@ -0,0 +1,34 @@
{
"productName": "app",
"version": "0.1.0",
"identifier": "com.tauri.app-settings-manager",
"build": {
"devUrl": "http://localhost:1420",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"title": "app",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false
}
],
"security": {
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: http://tauri.localhost 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

View File

@@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="512.000000pt" height="512.000000pt" viewBox="0 0 512.000000 512.000000"
preserveAspectRatio="xMidYMid meet">
<g transform="translate(0.000000,512.000000) scale(0.100000,-0.100000)"
fill="#2D79C7" stroke="none">
<path d="M430 5109 c-130 -19 -248 -88 -325 -191 -53 -71 -83 -147 -96 -247
-6 -49 -9 -813 -7 -2166 l3 -2090 22 -65 c54 -159 170 -273 328 -323 l70 -22
2140 0 2140 0 66 23 c160 55 272 169 322 327 l22 70 0 2135 0 2135 -22 70
c-49 157 -155 265 -319 327 l-59 23 -2115 1 c-1163 1 -2140 -2 -2170 -7z
m3931 -2383 c48 -9 120 -26 160 -39 l74 -23 3 -237 c1 -130 0 -237 -2 -237 -3
0 -26 14 -53 30 -61 38 -197 84 -310 106 -110 20 -293 15 -368 -12 -111 -39
-175 -110 -175 -193 0 -110 97 -197 335 -300 140 -61 309 -146 375 -189 30
-20 87 -68 126 -107 119 -117 164 -234 164 -426 0 -310 -145 -518 -430 -613
-131 -43 -248 -59 -445 -60 -243 -1 -405 24 -577 90 l-68 26 0 242 c0 175 -3
245 -12 254 -9 9 -9 12 0 12 7 0 12 -4 12 -9 0 -17 139 -102 223 -138 136 -57
233 -77 382 -76 145 0 224 19 295 68 75 52 100 156 59 242 -41 84 -135 148
-374 253 -367 161 -522 300 -581 520 -23 86 -23 253 -1 337 73 275 312 448
682 492 109 13 401 6 506 -13z m-1391 -241 l0 -205 -320 0 -320 0 0 -915 0
-915 -255 0 -255 0 0 915 0 915 -320 0 -320 0 0 205 0 205 895 0 895 0 0 -205z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,9 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
window.addEventListener('DOMContentLoaded', () => {
document.querySelector('#greet-form')?.addEventListener('submit', (e) => {
e.preventDefault()
})
})

View File

@@ -0,0 +1,109 @@
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,21 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig(async () => ({
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true
},
// 3. to make use of `TAURI_DEBUG` and other env variables
// https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
envPrefix: ['VITE_', 'TAURI_']
}))

View File

@@ -0,0 +1,933 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/**
* Simple, persistent key-value store.
*
* A store is persisted to a file inside the application data directory and is shared with the
* Rust side of the application, which can read and write the same store through its own API.
*
* @module
*/
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import { invoke, Resource } from '@tauri-apps/api/core'
interface ChangePayload<T> {
path: string
resourceId?: number
key: string
value: T
exists: boolean
}
/**
* Options to create a store
*/
export type StoreOptions = {
/**
* Default value of the store
*/
defaults?: { [key: string]: unknown }
/**
* Auto save on modification with debounce duration in milliseconds, it's 100ms by default, pass in `false` to disable it
*/
autoSave?: boolean | number
/**
* Name of a serialize function registered in the rust side plugin builder
*/
serializeFnName?: string
/**
* Name of a deserialize function registered in the rust side plugin builder
*/
deserializeFnName?: string
/**
* Force create a new store with default values even if it already exists.
*/
createNew?: boolean
/**
* When creating the store, override the store with the on-disk state if it exists, ignoring defaults
*/
overrideDefaults?: boolean
}
/**
* Create a new Store or load the existing store with the path.
*
* If the file at the given path does not exist yet, the store is created in memory with the
* configured defaults and the file is only written on the first save.
*
* @example
* ```typescript
* import { load } from '@tauri-apps/plugin-store';
* const store = await load('store.json');
* ```
*
* @param path Path to save the store in `app_data_dir`
* @param options Store configuration options
* @returns A promise resolving to the loaded store.
*
* @since 2.1.0
*/
export async function load(
path: string,
options?: StoreOptions
): Promise<Store> {
return await Store.load(path, options)
}
/**
* Gets an already loaded store.
*
* If the store is not loaded, returns `null`. In this case you must {@link Store.load load} it.
*
* This function is more useful when you already know the store is loaded
* and just need to access its instance. Prefer {@link Store.load} otherwise.
*
* @example
* ```typescript
* import { getStore } from '@tauri-apps/plugin-store';
* const store = await getStore('store.json');
* ```
*
* @param path Path of the store.
* @returns A promise resolving to the store instance, or `null` if it is not loaded.
*
* @since 2.1.0
*/
export async function getStore(path: string): Promise<Store | null> {
return await Store.get(path)
}
/**
* A lazy loaded key-value store persisted by the backend layer.
*
* The underlying {@linkcode Store} is only created or loaded when one of the methods of this
* class is called for the first time, and every call afterwards reuses that same instance.
*
* @since 2.1.0
*/
export class LazyStore implements IStore {
private _store?: Promise<Store>
private get store(): Promise<Store> {
if (!this._store) {
this._store = load(this.path, this.options)
}
return this._store
}
/**
* Creates a handle to the store at the given path without loading it yet.
*
* Note that the options are not applied if someone else already created the store
*
* @param path Path to save the store in `app_data_dir`
* @param options Store configuration options
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* ```
*/
constructor(
private readonly path: string,
private readonly options?: StoreOptions
) {}
/**
* Init/load the store if it's not loaded already
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* await store.init();
* ```
*/
async init(): Promise<void> {
await this.store
}
/**
* Inserts a key-value pair into the store, loading it first if needed.
*
* Delegates to {@linkcode Store.set} on the underlying store.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* await store.set('some-key', { value: 5 });
* ```
*
* @param key The key to insert the value at.
* @param value The value to store, which must be serializable to JSON.
*/
async set(key: string, value: unknown): Promise<void> {
return (await this.store).set(key, value)
}
/**
* Returns the value for the given `key` or `undefined` if the key does not exist.
*
* Delegates to {@linkcode Store.get} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const value = await store.get<{ value: number }>('some-key');
* ```
*
* @param key The key to read the value of.
* @returns A promise resolving to the stored value, or `undefined` if the key does not exist.
*/
async get<T>(key: string): Promise<T | undefined> {
return (await this.store).get<T>(key)
}
/**
* Returns `true` if the given `key` exists in the store.
*
* Delegates to {@linkcode Store.has} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const exists = await store.has('some-key');
* ```
*
* @param key The key to check.
* @returns A promise resolving to `true` if the key exists in the store.
*/
async has(key: string): Promise<boolean> {
return (await this.store).has(key)
}
/**
* Removes a key-value pair from the store.
*
* Delegates to {@linkcode Store.delete} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const removed = await store.delete('some-key');
* ```
*
* @param key The key to remove.
* @returns A promise resolving to `true` if the key existed and was removed.
*/
async delete(key: string): Promise<boolean> {
return (await this.store).delete(key)
}
/**
* Clears the store, removing all key-value pairs.
*
* Note: To clear the storage and reset it to its `default` value, use {@linkcode reset} instead.
* Delegates to {@linkcode Store.clear} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* await store.clear();
* ```
*/
async clear(): Promise<void> {
await (await this.store).clear()
}
/**
* Resets the store to its `default` value.
*
* If no default value has been set, this method behaves identical to {@linkcode clear}.
* Delegates to {@linkcode Store.reset} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json', { defaults: { 'some-key': 0 } });
* await store.reset();
* ```
*/
async reset(): Promise<void> {
await (await this.store).reset()
}
/**
* Returns a list of all keys in the store.
*
* Delegates to {@linkcode Store.keys} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const keys = await store.keys();
* ```
*
* @returns A promise resolving to the list of keys, in arbitrary order.
*/
async keys(): Promise<string[]> {
return (await this.store).keys()
}
/**
* Returns a list of all values in the store.
*
* Delegates to {@linkcode Store.values} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const values = await store.values();
* ```
*
* @returns A promise resolving to the list of values, in arbitrary order.
*/
async values<T>(): Promise<T[]> {
return (await this.store).values<T>()
}
/**
* Returns a list of all entries in the store.
*
* Delegates to {@linkcode Store.entries} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const entries = await store.entries();
* ```
*
* @returns A promise resolving to the list of key-value pairs, in arbitrary order.
*/
async entries<T>(): Promise<Array<[key: string, value: T]>> {
return (await this.store).entries<T>()
}
/**
* Returns the number of key-value pairs in the store.
*
* Delegates to {@linkcode Store.length} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const length = await store.length();
* ```
*
* @returns A promise resolving to the number of key-value pairs in the store.
*/
async length(): Promise<number> {
return (await this.store).length()
}
/**
* Attempts to load the on-disk state at the store's `path` into memory.
*
* Delegates to {@linkcode Store.reload} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* await store.reload({ ignoreDefaults: true });
* ```
*
* @param options Options to change how the on-disk state is merged into the store.
*/
async reload(options?: ReloadOptions): Promise<void> {
await (await this.store).reload(options)
}
/**
* Saves the store to disk at the store's `path`.
*
* Delegates to {@linkcode Store.save} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* await store.save();
* ```
*/
async save(): Promise<void> {
await (await this.store).save()
}
/**
* Listen to changes on a store key.
*
* Delegates to {@linkcode Store.onKeyChange} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const unlisten = await store.onKeyChange<{ value: number }>('some-key', (value) => {
* console.log(value);
* });
* ```
*
* @param key The key to watch for changes.
* @param cb Callback invoked with the new value, or `undefined` when the key was removed.
* @returns A promise resolving to a function to unlisten to the event.
*/
async onKeyChange<T>(
key: string,
cb: (value: T | undefined) => void
): Promise<UnlistenFn> {
return (await this.store).onKeyChange<T>(key, cb)
}
/**
* Listen to changes on the store.
*
* Delegates to {@linkcode Store.onChange} on the underlying store, loading it first if needed.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* const unlisten = await store.onChange<{ value: number }>((key, value) => {
* console.log(key, value);
* });
* ```
*
* @param cb Callback invoked with the changed key and its new value, which is `undefined` when the key was removed.
* @returns A promise resolving to a function to unlisten to the event.
*/
async onChange<T>(
cb: (key: string, value: T | undefined) => void
): Promise<UnlistenFn> {
return (await this.store).onChange<T>(cb)
}
/**
* Close the store and cleans up this resource from memory.
* **You should not call any method on this object anymore and should drop any reference to it.**
*
* Delegates to {@linkcode Store.close} on the underlying store.
* If the store was never loaded, this method does nothing.
*
* @example
* ```typescript
* import { LazyStore } from '@tauri-apps/plugin-store';
* const store = new LazyStore('store.json');
* await store.close();
* ```
*/
async close(): Promise<void> {
if (this._store) {
await (await this._store).close()
}
}
}
/**
* A key-value store persisted by the backend layer.
*
* The values are kept in memory and written to the store's file on {@linkcode Store.save},
* and automatically after every modification unless auto save is disabled with
* {@linkcode StoreOptions.autoSave}.
*
* @since 2.0.0
*/
export class Store extends Resource implements IStore {
private constructor(rid: number) {
super(rid)
}
/**
* Create a new Store or load the existing store with the path.
*
* If the file at the given path does not exist yet, the store is created in memory with the
* configured defaults and the file is only written on the first save.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* ```
*
* @param path Path to save the store in `app_data_dir`
* @param options Store configuration options
* @returns A promise resolving to the loaded store.
*/
static async load(path: string, options?: StoreOptions): Promise<Store> {
const rid = await invoke<number>('plugin:store|load', {
path,
options
})
return new Store(rid)
}
/**
* Gets an already loaded store.
*
* If the store is not loaded, returns `null`. In this case you must {@link Store.load load} it.
*
* This function is more useful when you already know the store is loaded
* and just need to access its instance. Prefer {@link Store.load} otherwise.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* let store = await Store.get('store.json');
* if (!store) {
* store = await Store.load('store.json');
* }
* ```
*
* @param path Path of the store.
* @returns A promise resolving to the store instance, or `null` if it is not loaded.
*/
static async get(path: string): Promise<Store | null> {
return await invoke<number | null>('plugin:store|get_store', { path }).then(
(rid) => (rid ? new Store(rid) : null)
)
}
/**
* Inserts a key-value pair into the store.
*
* A change event is emitted for the key and, unless auto save is disabled, the store is
* scheduled to be written to disk.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* await store.set('some-key', { value: 5 });
* ```
*
* @param key The key to insert the value at.
* @param value The value to store, which must be serializable to JSON.
*/
async set(key: string, value: unknown): Promise<void> {
await invoke('plugin:store|set', {
rid: this.rid,
key,
value
})
}
/**
* Returns the value for the given `key` or `undefined` if the key does not exist.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const value = await store.get<{ value: number }>('some-key');
* ```
*
* @param key The key to read the value of.
* @returns A promise resolving to the stored value, or `undefined` if the key does not exist.
*/
async get<T>(key: string): Promise<T | undefined> {
const [value, exists] = await invoke<[T, boolean]>('plugin:store|get', {
rid: this.rid,
key
})
return exists ? value : undefined
}
/**
* Returns `true` if the given `key` exists in the store.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const exists = await store.has('some-key');
* ```
*
* @param key The key to check.
* @returns A promise resolving to `true` if the key exists in the store.
*/
async has(key: string): Promise<boolean> {
return await invoke('plugin:store|has', {
rid: this.rid,
key
})
}
/**
* Removes a key-value pair from the store.
*
* A change event is emitted when the key existed and, unless auto save is disabled, the store
* is scheduled to be written to disk.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const removed = await store.delete('some-key');
* ```
*
* @param key The key to remove.
* @returns A promise resolving to `true` if the key existed and was removed.
*/
async delete(key: string): Promise<boolean> {
return await invoke('plugin:store|delete', {
rid: this.rid,
key
})
}
/**
* Clears the store, removing all key-value pairs.
*
* Note: To clear the storage and reset it to its `default` value, use {@linkcode reset} instead.
* A change event is emitted for every removed key.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* await store.clear();
* ```
*/
async clear(): Promise<void> {
await invoke('plugin:store|clear', { rid: this.rid })
}
/**
* Resets the store to its `default` value.
*
* If no default value has been set, this method behaves identical to {@linkcode clear}.
* A change event is emitted for every key whose value changed.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json', { defaults: { 'some-key': 0 } });
* await store.reset();
* ```
*/
async reset(): Promise<void> {
await invoke('plugin:store|reset', { rid: this.rid })
}
/**
* Returns a list of all keys in the store.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const keys = await store.keys();
* ```
*
* @returns A promise resolving to the list of keys, in arbitrary order.
*/
async keys(): Promise<string[]> {
return await invoke('plugin:store|keys', { rid: this.rid })
}
/**
* Returns a list of all values in the store.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const values = await store.values();
* ```
*
* @returns A promise resolving to the list of values, in arbitrary order.
*/
async values<T>(): Promise<T[]> {
return await invoke('plugin:store|values', { rid: this.rid })
}
/**
* Returns a list of all entries in the store.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const entries = await store.entries();
* ```
*
* @returns A promise resolving to the list of key-value pairs, in arbitrary order.
*/
async entries<T>(): Promise<Array<[key: string, value: T]>> {
return await invoke('plugin:store|entries', { rid: this.rid })
}
/**
* Returns the number of key-value pairs in the store.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const length = await store.length();
* ```
*
* @returns A promise resolving to the number of key-value pairs in the store.
*/
async length(): Promise<number> {
return await invoke('plugin:store|length', { rid: this.rid })
}
/**
* Attempts to load the on-disk state at the store's `path` into memory.
*
* This method is useful if the on-disk state was edited by the user and you want to synchronize the changes.
*
* Note:
* - This method loads the data and merges it with the current store,
* this behavior will be changed to resetting to default first and then merging with the on-disk state in v3,
* to fully match the store with the on-disk state, set {@linkcode ReloadOptions | ignoreDefaults} to `true`
* - This method does not emit change events.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* await store.reload({ ignoreDefaults: true });
* ```
*
* @param options Options to change how the on-disk state is merged into the store.
*/
async reload(options?: ReloadOptions): Promise<void> {
await invoke('plugin:store|reload', { rid: this.rid, ...options })
}
/**
* Saves the store to disk at the store's `path`.
*
* Any pending auto save is cancelled, so the store is written exactly once by this call.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json', { autoSave: false });
* await store.set('some-key', { value: 5 });
* await store.save();
* ```
*/
async save(): Promise<void> {
await invoke('plugin:store|save', { rid: this.rid })
}
/**
* Listen to changes on a store key.
*
* The callback is only invoked for changes made to this store instance.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const unlisten = await store.onKeyChange<{ value: number }>('some-key', (value) => {
* console.log(value);
* });
* ```
*
* @param key The key to watch for changes.
* @param cb Callback invoked with the new value, or `undefined` when the key was removed.
* @returns A promise resolving to a function to unlisten to the event.
*
* @since 2.0.0
*/
async onKeyChange<T>(
key: string,
cb: (value: T | undefined) => void
): Promise<UnlistenFn> {
return await listen<ChangePayload<T>>('store://change', (event) => {
if (event.payload.resourceId === this.rid && event.payload.key === key) {
cb(event.payload.exists ? event.payload.value : undefined)
}
})
}
/**
* Listen to changes on the store.
*
* The callback is only invoked for changes made to this store instance.
*
* @example
* ```typescript
* import { Store } from '@tauri-apps/plugin-store';
* const store = await Store.load('store.json');
* const unlisten = await store.onChange<{ value: number }>((key, value) => {
* console.log(key, value);
* });
* ```
*
* @param cb Callback invoked with the changed key and its new value, which is `undefined` when the key was removed.
* @returns A promise resolving to a function to unlisten to the event.
*
* @since 2.0.0
*/
async onChange<T>(
cb: (key: string, value: T | undefined) => void
): Promise<UnlistenFn> {
return await listen<ChangePayload<T>>('store://change', (event) => {
if (event.payload.resourceId === this.rid) {
cb(
event.payload.key,
event.payload.exists ? event.payload.value : undefined
)
}
})
}
}
interface IStore {
/**
* Inserts a key-value pair into the store.
*
* @param key
* @param value
* @returns
*/
set(key: string, value: unknown): Promise<void>
/**
* Returns the value for the given `key` or `undefined` if the key does not exist.
*
* @param key
* @returns
*/
get<T>(key: string): Promise<T | undefined>
/**
* Returns `true` if the given `key` exists in the store.
*
* @param key
* @returns
*/
has(key: string): Promise<boolean>
/**
* Removes a key-value pair from the store.
*
* @param key
* @returns
*/
delete(key: string): Promise<boolean>
/**
* Clears the store, removing all key-value pairs.
*
* Note: To clear the storage and reset it to its `default` value, use {@linkcode reset} instead.
* @returns
*/
clear(): Promise<void>
/**
* Resets the store to its `default` value.
*
* If no default value has been set, this method behaves identical to {@linkcode clear}.
* @returns
*/
reset(): Promise<void>
/**
* Returns a list of all keys in the store.
*
* @returns
*/
keys(): Promise<string[]>
/**
* Returns a list of all values in the store.
*
* @returns
*/
values<T>(): Promise<T[]>
/**
* Returns a list of all entries in the store.
*
* @returns
*/
entries<T>(): Promise<Array<[key: string, value: T]>>
/**
* Returns the number of key-value pairs in the store.
*
* @returns
*/
length(): Promise<number>
/**
* Attempts to load the on-disk state at the store's `path` into memory.
*
* This method is useful if the on-disk state was edited by the user and you want to synchronize the changes.
*
* Note:
* - This method loads the data and merges it with the current store,
* this behavior will be changed to resetting to default first and then merging with the on-disk state in v3,
* to fully match the store with the on-disk state, set {@linkcode ReloadOptions | ignoreDefaults} to `true`
* - This method does not emit change events.
*
* @returns
*/
reload(options?: ReloadOptions): Promise<void>
/**
* Saves the store to disk at the store's `path`.
* @returns
*/
save(): Promise<void>
/**
* Listen to changes on a store key.
* @param key
* @param cb
* @returns A promise resolving to a function to unlisten to the event.
*
* @since 2.0.0
*/
onKeyChange<T>(
key: string,
cb: (value: T | undefined) => void
): Promise<UnlistenFn>
/**
* Listen to changes on the store.
* @param cb
* @returns A promise resolving to a function to unlisten to the event.
*
* @since 2.0.0
*/
onChange<T>(
cb: (key: string, value: T | undefined) => void
): Promise<UnlistenFn>
/**
* Close the store and cleans up this resource from memory.
* **You should not call any method on this object anymore and should drop any reference to it.**
*/
close(): Promise<void>
}
/**
* Options to change how a store is reloaded from its on-disk state.
*/
export type ReloadOptions = {
/**
* To fully match the store with the on-disk state, ignoring defaults
*/
ignoreDefaults?: boolean
}

View File

@@ -0,0 +1,30 @@
{
"name": "@tauri-apps/plugin-store",
"version": "2.4.5",
"description": "Simple, persistent key-value store.",
"license": "MIT OR Apache-2.0",
"authors": [
"Tauri Programme within The Commons Conservancy"
],
"repository": "https://github.com/tauri-apps/plugins-workspace",
"type": "module",
"types": "./dist-js/index.d.ts",
"main": "./dist-js/index.cjs",
"module": "./dist-js/index.js",
"exports": {
"types": "./dist-js/index.d.ts",
"import": "./dist-js/index.js",
"require": "./dist-js/index.cjs"
},
"scripts": {
"build": "rollup -c"
},
"files": [
"dist-js",
"README.md",
"LICENSE"
],
"dependencies": {
"@tauri-apps/api": "^2.11.0"
}
}

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-clear"
description = "Enables the clear command without any pre-configured scope."
commands.allow = ["clear"]
[[permission]]
identifier = "deny-clear"
description = "Denies the clear command without any pre-configured scope."
commands.deny = ["clear"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-delete"
description = "Enables the delete command without any pre-configured scope."
commands.allow = ["delete"]
[[permission]]
identifier = "deny-delete"
description = "Denies the delete command without any pre-configured scope."
commands.deny = ["delete"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-entries"
description = "Enables the entries command without any pre-configured scope."
commands.allow = ["entries"]
[[permission]]
identifier = "deny-entries"
description = "Denies the entries command without any pre-configured scope."
commands.deny = ["entries"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-get"
description = "Enables the get command without any pre-configured scope."
commands.allow = ["get"]
[[permission]]
identifier = "deny-get"
description = "Denies the get command without any pre-configured scope."
commands.deny = ["get"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-get-store"
description = "Enables the get_store command without any pre-configured scope."
commands.allow = ["get_store"]
[[permission]]
identifier = "deny-get-store"
description = "Denies the get_store command without any pre-configured scope."
commands.deny = ["get_store"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-has"
description = "Enables the has command without any pre-configured scope."
commands.allow = ["has"]
[[permission]]
identifier = "deny-has"
description = "Denies the has command without any pre-configured scope."
commands.deny = ["has"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-keys"
description = "Enables the keys command without any pre-configured scope."
commands.allow = ["keys"]
[[permission]]
identifier = "deny-keys"
description = "Denies the keys command without any pre-configured scope."
commands.deny = ["keys"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-length"
description = "Enables the length command without any pre-configured scope."
commands.allow = ["length"]
[[permission]]
identifier = "deny-length"
description = "Denies the length command without any pre-configured scope."
commands.deny = ["length"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-load"
description = "Enables the load command without any pre-configured scope."
commands.allow = ["load"]
[[permission]]
identifier = "deny-load"
description = "Denies the load command without any pre-configured scope."
commands.deny = ["load"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-reload"
description = "Enables the reload command without any pre-configured scope."
commands.allow = ["reload"]
[[permission]]
identifier = "deny-reload"
description = "Denies the reload command without any pre-configured scope."
commands.deny = ["reload"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-reset"
description = "Enables the reset command without any pre-configured scope."
commands.allow = ["reset"]
[[permission]]
identifier = "deny-reset"
description = "Denies the reset command without any pre-configured scope."
commands.deny = ["reset"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-save"
description = "Enables the save command without any pre-configured scope."
commands.allow = ["save"]
[[permission]]
identifier = "deny-save"
description = "Denies the save command without any pre-configured scope."
commands.deny = ["save"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-set"
description = "Enables the set command without any pre-configured scope."
commands.allow = ["set"]
[[permission]]
identifier = "deny-set"
description = "Denies the set command without any pre-configured scope."
commands.deny = ["set"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-values"
description = "Enables the values command without any pre-configured scope."
commands.allow = ["values"]
[[permission]]
identifier = "deny-values"
description = "Denies the values command without any pre-configured scope."
commands.deny = ["values"]

View File

@@ -0,0 +1,399 @@
## Default Permission
This permission set configures what kind of
operations are available from the store plugin.
#### Granted Permissions
All operations are enabled by default.
#### This default permission set includes the following:
- `allow-load`
- `allow-get-store`
- `allow-set`
- `allow-get`
- `allow-has`
- `allow-delete`
- `allow-clear`
- `allow-reset`
- `allow-keys`
- `allow-values`
- `allow-entries`
- `allow-length`
- `allow-reload`
- `allow-save`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`store:allow-clear`
</td>
<td>
Enables the clear command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-clear`
</td>
<td>
Denies the clear command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-delete`
</td>
<td>
Enables the delete command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-delete`
</td>
<td>
Denies the delete command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-entries`
</td>
<td>
Enables the entries command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-entries`
</td>
<td>
Denies the entries command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-get`
</td>
<td>
Enables the get command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-get`
</td>
<td>
Denies the get command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-get-store`
</td>
<td>
Enables the get_store command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-get-store`
</td>
<td>
Denies the get_store command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-has`
</td>
<td>
Enables the has command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-has`
</td>
<td>
Denies the has command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-keys`
</td>
<td>
Enables the keys command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-keys`
</td>
<td>
Denies the keys command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-length`
</td>
<td>
Enables the length command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-length`
</td>
<td>
Denies the length command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-load`
</td>
<td>
Enables the load command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-load`
</td>
<td>
Denies the load command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-reload`
</td>
<td>
Enables the reload command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-reload`
</td>
<td>
Denies the reload command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-reset`
</td>
<td>
Enables the reset command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-reset`
</td>
<td>
Denies the reset command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-save`
</td>
<td>
Enables the save command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-save`
</td>
<td>
Denies the save command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-set`
</td>
<td>
Enables the set command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-set`
</td>
<td>
Denies the set command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:allow-values`
</td>
<td>
Enables the values command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`store:deny-values`
</td>
<td>
Denies the values command without any pre-configured scope.
</td>
</tr>
</table>

View File

@@ -0,0 +1,28 @@
"$schema" = "schemas/schema.json"
[default]
description = """
This permission set configures what kind of
operations are available from the store plugin.
#### Granted Permissions
All operations are enabled by default.
"""
permissions = [
"allow-load",
"allow-get-store",
"allow-set",
"allow-get",
"allow-has",
"allow-delete",
"allow-clear",
"allow-reset",
"allow-keys",
"allow-values",
"allow-entries",
"allow-length",
"allow-reload",
"allow-save",
]

View File

@@ -0,0 +1,474 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "PermissionFile",
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
"type": "object",
"properties": {
"default": {
"description": "The default permission set for the plugin",
"anyOf": [
{
"$ref": "#/definitions/DefaultPermission"
},
{
"type": "null"
}
]
},
"set": {
"description": "A list of permissions sets defined",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionSet"
}
},
"permission": {
"description": "A list of inlined permissions",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/Permission"
}
}
},
"definitions": {
"DefaultPermission": {
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
"type": "object",
"required": [
"permissions"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"description": {
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"PermissionSet": {
"description": "A set of direct permissions grouped together under a new name.",
"type": "object",
"required": [
"description",
"identifier",
"permissions"
],
"properties": {
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does.",
"type": "string"
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionKind"
}
}
}
},
"Permission": {
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
"type": "object",
"required": [
"identifier"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"commands": {
"description": "Allowed or denied commands when using this permission.",
"default": {
"allow": [],
"deny": []
},
"allOf": [
{
"$ref": "#/definitions/Commands"
}
]
},
"scope": {
"description": "Allowed or denied scoped when using this permission.",
"allOf": [
{
"$ref": "#/definitions/Scopes"
}
]
},
"platforms": {
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Target"
}
}
}
},
"Commands": {
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
"type": "object",
"properties": {
"allow": {
"description": "Allowed command.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
},
"deny": {
"description": "Denied command, which takes priority.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Scopes": {
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
"type": "object",
"properties": {
"allow": {
"description": "Data that defines what is allowed by the scope.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
},
"deny": {
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
}
}
},
"Value": {
"description": "All supported ACL values.",
"anyOf": [
{
"description": "Represents a null JSON value.",
"type": "null"
},
{
"description": "Represents a [`bool`].",
"type": "boolean"
},
{
"description": "Represents a valid ACL [`Number`].",
"allOf": [
{
"$ref": "#/definitions/Number"
}
]
},
{
"description": "Represents a [`String`].",
"type": "string"
},
{
"description": "Represents a list of other [`Value`]s.",
"type": "array",
"items": {
"$ref": "#/definitions/Value"
}
},
{
"description": "Represents a map of [`String`] keys to [`Value`]s.",
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/Value"
}
}
]
},
"Number": {
"description": "A valid ACL number.",
"anyOf": [
{
"description": "Represents an [`i64`].",
"type": "integer",
"format": "int64"
},
{
"description": "Represents a [`f64`].",
"type": "number",
"format": "double"
}
]
},
"Target": {
"description": "Platform target.",
"oneOf": [
{
"description": "MacOS.",
"type": "string",
"enum": [
"macOS"
]
},
{
"description": "Windows.",
"type": "string",
"enum": [
"windows"
]
},
{
"description": "Linux.",
"type": "string",
"enum": [
"linux"
]
},
{
"description": "Android.",
"type": "string",
"enum": [
"android"
]
},
{
"description": "iOS.",
"type": "string",
"enum": [
"iOS"
]
}
]
},
"PermissionKind": {
"type": "string",
"oneOf": [
{
"description": "Enables the clear command without any pre-configured scope.",
"type": "string",
"const": "allow-clear",
"markdownDescription": "Enables the clear command without any pre-configured scope."
},
{
"description": "Denies the clear command without any pre-configured scope.",
"type": "string",
"const": "deny-clear",
"markdownDescription": "Denies the clear command without any pre-configured scope."
},
{
"description": "Enables the delete command without any pre-configured scope.",
"type": "string",
"const": "allow-delete",
"markdownDescription": "Enables the delete command without any pre-configured scope."
},
{
"description": "Denies the delete command without any pre-configured scope.",
"type": "string",
"const": "deny-delete",
"markdownDescription": "Denies the delete command without any pre-configured scope."
},
{
"description": "Enables the entries command without any pre-configured scope.",
"type": "string",
"const": "allow-entries",
"markdownDescription": "Enables the entries command without any pre-configured scope."
},
{
"description": "Denies the entries command without any pre-configured scope.",
"type": "string",
"const": "deny-entries",
"markdownDescription": "Denies the entries command without any pre-configured scope."
},
{
"description": "Enables the get command without any pre-configured scope.",
"type": "string",
"const": "allow-get",
"markdownDescription": "Enables the get command without any pre-configured scope."
},
{
"description": "Denies the get command without any pre-configured scope.",
"type": "string",
"const": "deny-get",
"markdownDescription": "Denies the get command without any pre-configured scope."
},
{
"description": "Enables the get_store command without any pre-configured scope.",
"type": "string",
"const": "allow-get-store",
"markdownDescription": "Enables the get_store command without any pre-configured scope."
},
{
"description": "Denies the get_store command without any pre-configured scope.",
"type": "string",
"const": "deny-get-store",
"markdownDescription": "Denies the get_store command without any pre-configured scope."
},
{
"description": "Enables the has command without any pre-configured scope.",
"type": "string",
"const": "allow-has",
"markdownDescription": "Enables the has command without any pre-configured scope."
},
{
"description": "Denies the has command without any pre-configured scope.",
"type": "string",
"const": "deny-has",
"markdownDescription": "Denies the has command without any pre-configured scope."
},
{
"description": "Enables the keys command without any pre-configured scope.",
"type": "string",
"const": "allow-keys",
"markdownDescription": "Enables the keys command without any pre-configured scope."
},
{
"description": "Denies the keys command without any pre-configured scope.",
"type": "string",
"const": "deny-keys",
"markdownDescription": "Denies the keys command without any pre-configured scope."
},
{
"description": "Enables the length command without any pre-configured scope.",
"type": "string",
"const": "allow-length",
"markdownDescription": "Enables the length command without any pre-configured scope."
},
{
"description": "Denies the length command without any pre-configured scope.",
"type": "string",
"const": "deny-length",
"markdownDescription": "Denies the length command without any pre-configured scope."
},
{
"description": "Enables the load command without any pre-configured scope.",
"type": "string",
"const": "allow-load",
"markdownDescription": "Enables the load command without any pre-configured scope."
},
{
"description": "Denies the load command without any pre-configured scope.",
"type": "string",
"const": "deny-load",
"markdownDescription": "Denies the load command without any pre-configured scope."
},
{
"description": "Enables the reload command without any pre-configured scope.",
"type": "string",
"const": "allow-reload",
"markdownDescription": "Enables the reload command without any pre-configured scope."
},
{
"description": "Denies the reload command without any pre-configured scope.",
"type": "string",
"const": "deny-reload",
"markdownDescription": "Denies the reload command without any pre-configured scope."
},
{
"description": "Enables the reset command without any pre-configured scope.",
"type": "string",
"const": "allow-reset",
"markdownDescription": "Enables the reset command without any pre-configured scope."
},
{
"description": "Denies the reset command without any pre-configured scope.",
"type": "string",
"const": "deny-reset",
"markdownDescription": "Denies the reset command without any pre-configured scope."
},
{
"description": "Enables the save command without any pre-configured scope.",
"type": "string",
"const": "allow-save",
"markdownDescription": "Enables the save command without any pre-configured scope."
},
{
"description": "Denies the save command without any pre-configured scope.",
"type": "string",
"const": "deny-save",
"markdownDescription": "Denies the save command without any pre-configured scope."
},
{
"description": "Enables the set command without any pre-configured scope.",
"type": "string",
"const": "allow-set",
"markdownDescription": "Enables the set command without any pre-configured scope."
},
{
"description": "Denies the set command without any pre-configured scope.",
"type": "string",
"const": "deny-set",
"markdownDescription": "Denies the set command without any pre-configured scope."
},
{
"description": "Enables the values command without any pre-configured scope.",
"type": "string",
"const": "allow-values",
"markdownDescription": "Enables the values command without any pre-configured scope."
},
{
"description": "Denies the values command without any pre-configured scope.",
"type": "string",
"const": "deny-values",
"markdownDescription": "Denies the values command without any pre-configured scope."
},
{
"description": "This permission set configures what kind of\noperations are available from the store plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n\n#### This default permission set includes:\n\n- `allow-load`\n- `allow-get-store`\n- `allow-set`\n- `allow-get`\n- `allow-has`\n- `allow-delete`\n- `allow-clear`\n- `allow-reset`\n- `allow-keys`\n- `allow-values`\n- `allow-entries`\n- `allow-length`\n- `allow-reload`\n- `allow-save`",
"type": "string",
"const": "default",
"markdownDescription": "This permission set configures what kind of\noperations are available from the store plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n\n#### This default permission set includes:\n\n- `allow-load`\n- `allow-get-store`\n- `allow-set`\n- `allow-get`\n- `allow-has`\n- `allow-delete`\n- `allow-clear`\n- `allow-reset`\n- `allow-keys`\n- `allow-values`\n- `allow-entries`\n- `allow-length`\n- `allow-reload`\n- `allow-save`"
}
]
}
}
}

View File

@@ -0,0 +1,7 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { createConfig } from '../../shared/rollup.config.js'
export default createConfig()

View File

@@ -0,0 +1,47 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Serialize, Serializer};
/// Alias for a [`Result`](std::result::Result) with the error type [`Error`].
pub type Result<T> = std::result::Result<T, Error>;
/// The error types.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
/// The store contents could not be serialized by the configured [`SerializeFn`](crate::SerializeFn).
#[error("Failed to serialize store. {0}")]
Serialize(Box<dyn std::error::Error + Send + Sync>),
/// The store contents could not be deserialized by the configured [`DeserializeFn`](crate::DeserializeFn).
#[error("Failed to deserialize store. {0}")]
Deserialize(Box<dyn std::error::Error + Send + Sync>),
/// JSON error.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// IO error.
#[error(transparent)]
Io(#[from] std::io::Error),
// /// Store already exists
// #[error("Store at \"{0}\" already exists")]
// AlreadyExists(PathBuf),
/// Serialize function not found
#[error("Serialize Function \"{0}\" not found")]
SerializeFunctionNotFound(String),
/// Deserialize function not found
#[error("Deserialize Function \"{0}\" not found")]
DeserializeFunctionNotFound(String),
/// Some Tauri API failed
#[error(transparent)]
Tauri(#[from] tauri::Error),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}

483
plugins/store/src/lib.rs Normal file
View File

@@ -0,0 +1,483 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Simple, persistent key-value store.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
)]
pub use error::{Error, Result};
use serde::{Deserialize, Serialize};
pub use serde_json::Value as JsonValue;
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, RwLock},
time::Duration,
};
pub use store::{resolve_store_path, DeserializeFn, SerializeFn, Store, StoreBuilder};
use tauri::{
plugin::{self, TauriPlugin},
AppHandle, Manager, ResourceId, RunEvent, Runtime, State,
};
mod error;
mod store;
#[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")]
struct ChangePayload<'a> {
path: &'a Path,
resource_id: Option<u32>,
key: &'a str,
value: Option<&'a JsonValue>,
exists: bool,
}
#[derive(Debug)]
struct StoreState {
stores: Arc<RwLock<HashMap<PathBuf, ResourceId>>>,
serialize_fns: HashMap<String, SerializeFn>,
deserialize_fns: HashMap<String, DeserializeFn>,
default_serialize: SerializeFn,
default_deserialize: DeserializeFn,
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum AutoSave {
DebounceDuration(u64),
Bool(bool),
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct LoadStoreOptions {
defaults: Option<HashMap<String, JsonValue>>,
auto_save: Option<AutoSave>,
serialize_fn_name: Option<String>,
deserialize_fn_name: Option<String>,
#[serde(default)]
create_new: bool,
#[serde(default)]
override_defaults: bool,
}
fn builder<R: Runtime>(
app: AppHandle<R>,
store_state: State<'_, StoreState>,
path: PathBuf,
options: Option<LoadStoreOptions>,
) -> Result<StoreBuilder<R>> {
let mut builder = app.store_builder(path);
let Some(options) = options else {
return Ok(builder);
};
if let Some(defaults) = options.defaults {
builder = builder.defaults(defaults);
}
if let Some(auto_save) = options.auto_save {
match auto_save {
AutoSave::DebounceDuration(duration) => {
builder = builder.auto_save(Duration::from_millis(duration));
}
AutoSave::Bool(false) => {
builder = builder.disable_auto_save();
}
_ => {}
}
}
if let Some(serialize_fn_name) = options.serialize_fn_name {
let serialize_fn = store_state
.serialize_fns
.get(&serialize_fn_name)
.ok_or_else(|| crate::Error::SerializeFunctionNotFound(serialize_fn_name))?;
builder = builder.serialize(*serialize_fn);
}
if let Some(deserialize_fn_name) = options.deserialize_fn_name {
let deserialize_fn = store_state
.deserialize_fns
.get(&deserialize_fn_name)
.ok_or_else(|| crate::Error::DeserializeFunctionNotFound(deserialize_fn_name))?;
builder = builder.deserialize(*deserialize_fn);
}
if options.create_new {
builder = builder.create_new();
}
if options.override_defaults {
builder = builder.override_defaults();
}
Ok(builder)
}
#[tauri::command]
async fn load<R: Runtime>(
app: AppHandle<R>,
store_state: State<'_, StoreState>,
path: PathBuf,
options: Option<LoadStoreOptions>,
) -> Result<ResourceId> {
let builder = builder(app, store_state, path, options)?;
let (_, rid) = builder.build_inner()?;
Ok(rid)
}
#[tauri::command]
async fn get_store<R: Runtime>(
app: AppHandle<R>,
store_state: State<'_, StoreState>,
path: PathBuf,
) -> Result<Option<ResourceId>> {
let stores = store_state.stores.read().unwrap();
Ok(stores.get(&resolve_store_path(&app, path)?).copied())
}
#[tauri::command]
async fn set<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
key: String,
value: JsonValue,
) -> Result<()> {
let store = app.resources_table().get::<Store<R>>(rid)?;
store.set(key, value);
Ok(())
}
#[tauri::command]
async fn get<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
key: String,
) -> Result<(Option<JsonValue>, bool)> {
let store = app.resources_table().get::<Store<R>>(rid)?;
let value = store.get(key);
let exists = value.is_some();
Ok((value, exists))
}
#[tauri::command]
async fn has<R: Runtime>(app: AppHandle<R>, rid: ResourceId, key: String) -> Result<bool> {
let store = app.resources_table().get::<Store<R>>(rid)?;
Ok(store.has(key))
}
#[tauri::command]
async fn delete<R: Runtime>(app: AppHandle<R>, rid: ResourceId, key: String) -> Result<bool> {
let store = app.resources_table().get::<Store<R>>(rid)?;
Ok(store.delete(key))
}
#[tauri::command]
async fn clear<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<()> {
let store = app.resources_table().get::<Store<R>>(rid)?;
store.clear();
Ok(())
}
#[tauri::command]
async fn reset<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<()> {
let store = app.resources_table().get::<Store<R>>(rid)?;
store.reset();
Ok(())
}
#[tauri::command]
async fn keys<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<Vec<String>> {
let store = app.resources_table().get::<Store<R>>(rid)?;
Ok(store.keys())
}
#[tauri::command]
async fn values<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<Vec<JsonValue>> {
let store = app.resources_table().get::<Store<R>>(rid)?;
Ok(store.values())
}
#[tauri::command]
async fn entries<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
) -> Result<Vec<(String, JsonValue)>> {
let store = app.resources_table().get::<Store<R>>(rid)?;
Ok(store.entries())
}
#[tauri::command]
async fn length<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<usize> {
let store = app.resources_table().get::<Store<R>>(rid)?;
Ok(store.length())
}
#[tauri::command]
async fn reload<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
ignore_defaults: Option<bool>,
) -> Result<()> {
let store = app.resources_table().get::<Store<R>>(rid)?;
if ignore_defaults.unwrap_or_default() {
store.reload_ignore_defaults()
} else {
store.reload()
}
}
#[tauri::command]
async fn save<R: Runtime>(app: AppHandle<R>, rid: ResourceId) -> Result<()> {
let store = app.resources_table().get::<Store<R>>(rid)?;
store.save()
}
/// Extension trait to access the store APIs on a [`Manager`] such as `App`, `AppHandle`,
/// `WebviewWindow` or `Window`.
///
/// The plugin must be registered with [`Builder::build`] for these methods to work,
/// as they rely on the state it manages.
pub trait StoreExt<R: Runtime> {
/// Create a store or load an existing store with default settings at the given path.
///
/// If the store is already loaded, its instance is automatically returned.
///
/// # Examples
///
/// ```
/// use tauri_plugin_store::StoreExt;
///
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = app.store("my-store")?;
/// Ok(())
/// });
/// ```
fn store(&self, path: impl AsRef<Path>) -> Result<Arc<Store<R>>>;
/// Get a store builder.
///
/// The builder can be used to configure the store.
/// To use the default settings see [`Self::store`].
///
/// # Examples
///
/// ```
/// use tauri_plugin_store::StoreExt;
/// use std::time::Duration;
///
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = app.store_builder("users.json").auto_save(Duration::from_secs(1)).build()?;
/// Ok(())
/// });
/// ```
fn store_builder(&self, path: impl AsRef<Path>) -> StoreBuilder<R>;
/// Get a handle of an already loaded store.
///
/// If the store is not loaded or does not exist, it returns `None`.
///
/// Note that using this function can cause race conditions if you fallback to creating or loading the store,
/// so you should consider using [`Self::store`] if you are not sure if the store is loaded or not.
///
/// # Examples
///
/// ```
/// use tauri_plugin_store::StoreExt;
///
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = if let Some(s) = app.get_store("store.json") {
/// s
/// } else {
/// // this is not thread safe; if another thread is doing the same load/create,
/// // there will be a race condition; in this case we could remove the get_store
/// // and only run app.store() as it will return the existing store if it has been loaded
/// app.store("store.json")?
/// };
/// Ok(())
/// });
/// ```
fn get_store(&self, path: impl AsRef<Path>) -> Option<Arc<Store<R>>>;
}
impl<R: Runtime, T: Manager<R>> StoreExt<R> for T {
fn store(&self, path: impl AsRef<Path>) -> Result<Arc<Store<R>>> {
StoreBuilder::new(self.app_handle(), path).build()
}
fn store_builder(&self, path: impl AsRef<Path>) -> StoreBuilder<R> {
StoreBuilder::new(self.app_handle(), path)
}
fn get_store(&self, path: impl AsRef<Path>) -> Option<Arc<Store<R>>> {
let collection = self.state::<StoreState>();
let stores = collection.stores.read().unwrap();
stores
.get(&resolve_store_path(self.app_handle(), path.as_ref()).ok()?)
.and_then(|rid| self.resources_table().get(*rid).ok())
}
}
fn default_serialize(
cache: &HashMap<String, JsonValue>,
) -> std::result::Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
Ok(serde_json::to_vec_pretty(&cache)?)
}
fn default_deserialize(
bytes: &[u8],
) -> std::result::Result<HashMap<String, JsonValue>, Box<dyn std::error::Error + Send + Sync>> {
serde_json::from_slice(bytes).map_err(Into::into)
}
/// Builder for the store plugin.
///
/// It is used to register custom serialize and deserialize functions the frontend can select by
/// name when loading a store, and to change the functions used by default (pretty printed JSON).
///
/// # Examples
///
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build());
/// ```
pub struct Builder {
serialize_fns: HashMap<String, SerializeFn>,
deserialize_fns: HashMap<String, DeserializeFn>,
default_serialize: SerializeFn,
default_deserialize: DeserializeFn,
}
impl Default for Builder {
fn default() -> Self {
Self {
serialize_fns: Default::default(),
deserialize_fns: Default::default(),
default_serialize,
default_deserialize,
}
}
}
impl Builder {
/// Creates a new builder using the default serialize and deserialize functions,
/// which read and write pretty printed JSON.
///
/// This is the same as [`Builder::default`].
pub fn new() -> Self {
Self::default()
}
/// Register a serialize function to access it from the JavaScript side
///
/// # Examples
///
/// ```
/// fn no_pretty_json(
/// cache: &std::collections::HashMap<String, serde_json::Value>,
/// ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
/// Ok(serde_json::to_vec(&cache)?)
/// }
///
/// tauri::Builder::default()
/// .plugin(
/// tauri_plugin_store::Builder::default()
/// .register_serialize_fn("no-pretty-json".to_owned(), no_pretty_json)
/// .build(),
/// );
/// ```
pub fn register_serialize_fn(mut self, name: String, serialize_fn: SerializeFn) -> Self {
self.serialize_fns.insert(name, serialize_fn);
self
}
/// Register a deserialize function to access it from the JavaScript side
pub fn register_deserialize_fn(mut self, name: String, deserialize_fn: DeserializeFn) -> Self {
self.deserialize_fns.insert(name, deserialize_fn);
self
}
/// Use this serialize function for stores by default
///
/// # Examples
///
/// ```
/// fn no_pretty_json(
/// cache: &std::collections::HashMap<String, serde_json::Value>,
/// ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
/// Ok(serde_json::to_vec(&cache)?)
/// }
///
/// tauri::Builder::default()
/// .plugin(
/// tauri_plugin_store::Builder::default()
/// .default_serialize_fn(no_pretty_json)
/// .build(),
/// );
/// ```
pub fn default_serialize_fn(mut self, serialize_fn: SerializeFn) -> Self {
self.default_serialize = serialize_fn;
self
}
/// Use this deserialize function for stores by default
pub fn default_deserialize_fn(mut self, deserialize_fn: DeserializeFn) -> Self {
self.default_deserialize = deserialize_fn;
self
}
/// Builds the plugin.
///
/// # Examples
///
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.bin").build()?;
/// Ok(())
/// });
/// ```
pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
plugin::Builder::new("store")
.invoke_handler(tauri::generate_handler![
load, get_store, set, get, has, delete, clear, reset, keys, values, length,
entries, reload, save,
])
.setup(move |app_handle, _api| {
app_handle.manage(StoreState {
stores: Arc::new(RwLock::new(HashMap::new())),
serialize_fns: self.serialize_fns,
deserialize_fns: self.deserialize_fns,
default_serialize: self.default_serialize,
default_deserialize: self.default_deserialize,
});
Ok(())
})
.on_event(|app_handle, event| {
if let RunEvent::Exit = event {
let collection = app_handle.state::<StoreState>();
let stores = collection.stores.read().unwrap();
for (path, rid) in stores.iter() {
if let Ok(store) = app_handle.resources_table().get::<Store<R>>(*rid) {
if let Err(err) = store.save() {
tracing::error!("failed to save store {path:?} with error {err:?}");
}
}
}
}
})
.build()
}
}

638
plugins/store/src/store.rs Normal file
View File

@@ -0,0 +1,638 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{ChangePayload, StoreState};
use serde_json::Value as JsonValue;
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex},
time::Duration,
};
use tauri::{path::BaseDirectory, AppHandle, Emitter, Manager, Resource, ResourceId, Runtime};
use tokio::{
select,
sync::mpsc::{unbounded_channel, UnboundedSender},
time::sleep,
};
/// Function used to serialize the store cache to the bytes written to the store file.
///
/// The default implementation writes pretty printed JSON.
pub type SerializeFn =
fn(&HashMap<String, JsonValue>) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>>;
/// Function used to deserialize the bytes read from the store file into the store cache.
///
/// The default implementation parses JSON.
pub type DeserializeFn =
fn(&[u8]) -> Result<HashMap<String, JsonValue>, Box<dyn std::error::Error + Send + Sync>>;
/// Resolves the path of a store file, relative to the app data directory
/// ([`BaseDirectory::AppData`]).
///
/// This is the path the [`Store`] created with the given `path` reads from and writes to.
///
/// # Errors
///
/// Returns an error if the app data directory cannot be resolved.
pub fn resolve_store_path<R: Runtime>(
app: &AppHandle<R>,
path: impl AsRef<Path>,
) -> crate::Result<PathBuf> {
Ok(dunce::simplified(&app.path().resolve(path, BaseDirectory::AppData)?).to_path_buf())
}
/// Builds a [`Store`]
pub struct StoreBuilder<R: Runtime> {
app: AppHandle<R>,
path: PathBuf,
defaults: Option<HashMap<String, JsonValue>>,
serialize_fn: SerializeFn,
deserialize_fn: DeserializeFn,
auto_save: Option<Duration>,
create_new: bool,
override_defaults: bool,
}
impl<R: Runtime> StoreBuilder<R> {
/// Creates a new [`StoreBuilder`].
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let builder = tauri_plugin_store::StoreBuilder::new(app, "store.bin");
/// Ok(())
/// });
/// ```
pub fn new<M: Manager<R>, P: AsRef<Path>>(manager: &M, path: P) -> Self {
let app = manager.app_handle().clone();
let state = app.state::<StoreState>();
let serialize_fn = state.default_serialize;
let deserialize_fn = state.default_deserialize;
Self {
app,
path: path.as_ref().to_path_buf(),
defaults: None,
serialize_fn,
deserialize_fn,
auto_save: Some(Duration::from_millis(100)),
create_new: false,
override_defaults: false,
}
}
/// Inserts a default key-value pair.
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let mut defaults = std::collections::HashMap::new();
/// defaults.insert("foo".to_string(), "bar".into());
///
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.bin")
/// .defaults(defaults)
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn defaults(mut self, defaults: HashMap<String, JsonValue>) -> Self {
self.defaults = Some(defaults);
self
}
/// Inserts multiple default key-value pairs.
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.bin")
/// .default("foo".to_string(), "bar")
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn default(mut self, key: impl Into<String>, value: impl Into<JsonValue>) -> Self {
let key = key.into();
let value = value.into();
self.defaults
.get_or_insert(HashMap::new())
.insert(key, value);
self
}
/// Defines a custom serialization function.
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.json")
/// .serialize(|cache| serde_json::to_vec(&cache).map_err(Into::into))
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn serialize(mut self, serialize: SerializeFn) -> Self {
self.serialize_fn = serialize;
self
}
/// Defines a custom deserialization function
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.json")
/// .deserialize(|bytes| serde_json::from_slice(&bytes).map_err(Into::into))
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn deserialize(mut self, deserialize: DeserializeFn) -> Self {
self.deserialize_fn = deserialize;
self
}
/// Auto save on modified with a debounce duration
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.json")
/// .auto_save(std::time::Duration::from_millis(100))
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn auto_save(mut self, debounce_duration: Duration) -> Self {
self.auto_save = Some(debounce_duration);
self
}
/// Disable auto save on modified with a debounce duration.
pub fn disable_auto_save(mut self) -> Self {
self.auto_save = None;
self
}
/// Force create a new store with default values even if it already exists.
pub fn create_new(mut self) -> Self {
self.create_new = true;
self
}
/// Override the store values when creating the store, ignoring defaults.
pub fn override_defaults(mut self) -> Self {
self.override_defaults = true;
self
}
pub(crate) fn build_inner(mut self) -> crate::Result<(Arc<Store<R>>, ResourceId)> {
let stores = self.app.state::<StoreState>().stores.clone();
let mut stores = stores.write().unwrap();
self.path = resolve_store_path(&self.app, self.path)?;
if self.create_new {
if let Some(rid) = stores.remove(&self.path) {
let _ = self.app.resources_table().take::<Store<R>>(rid);
}
} else if let Some(rid) = stores.get(&self.path) {
// The resource id we stored can be invalid due to
// the resource table getting modified by an external source
// (e.g. `App::cleanup_before_exit` > `manager.resources_table.clear()`)
return Ok((self.app.resources_table().get(*rid)?, *rid));
}
// if stores.contains_key(&self.path) {
// return Err(crate::Error::AlreadyExists(self.path));
// }
let mut store_inner = StoreInner::new(
self.app.clone(),
self.path.clone(),
self.defaults.take(),
self.serialize_fn,
self.deserialize_fn,
);
if !self.create_new {
if self.override_defaults {
let _ = store_inner.load_ignore_defaults();
} else {
let _ = store_inner.load();
}
}
let store = Store {
auto_save: self.auto_save,
auto_save_debounce_sender: Arc::new(Mutex::new(None)),
store: Arc::new(Mutex::new(store_inner)),
};
let store = Arc::new(store);
let rid = self.app.resources_table().add_arc(store.clone());
stores.insert(self.path, rid);
Ok((store, rid))
}
/// Load the existing store with the same path or creates a new [`Store`].
///
/// If a store with the same path has already been loaded its instance is returned.
///
/// # Examples
/// ```
/// tauri::Builder::default()
/// .plugin(tauri_plugin_store::Builder::default().build())
/// .setup(|app| {
/// let store = tauri_plugin_store::StoreBuilder::new(app, "store.json").build();
/// Ok(())
/// });
/// ```
pub fn build(self) -> crate::Result<Arc<Store<R>>> {
let (store, _) = self.build_inner()?;
Ok(store)
}
}
enum AutoSaveMessage {
Reset,
Cancel,
}
#[derive(Clone)]
struct StoreInner<R: Runtime> {
app: AppHandle<R>,
path: PathBuf,
cache: HashMap<String, JsonValue>,
defaults: Option<HashMap<String, JsonValue>>,
serialize_fn: SerializeFn,
deserialize_fn: DeserializeFn,
}
impl<R: Runtime> StoreInner<R> {
fn new(
app: AppHandle<R>,
path: PathBuf,
defaults: Option<HashMap<String, JsonValue>>,
serialize_fn: SerializeFn,
deserialize_fn: DeserializeFn,
) -> Self {
Self {
app,
path,
cache: defaults.clone().unwrap_or_default(),
defaults,
serialize_fn,
deserialize_fn,
}
}
/// Saves the store to disk at the store's `path`.
pub fn save(&self) -> crate::Result<()> {
fs::create_dir_all(self.path.parent().expect("invalid store path"))?;
let bytes = (self.serialize_fn)(&self.cache).map_err(crate::Error::Serialize)?;
fs::write(&self.path, bytes)?;
Ok(())
}
/// Update the store from the on-disk state
///
/// Note: This method loads the data and merges it with the current store
pub fn load(&mut self) -> crate::Result<()> {
let bytes = fs::read(&self.path)?;
self.cache
.extend((self.deserialize_fn)(&bytes).map_err(crate::Error::Deserialize)?);
Ok(())
}
/// Load the store from the on-disk state, ignoring defaults
pub fn load_ignore_defaults(&mut self) -> crate::Result<()> {
let bytes = fs::read(&self.path)?;
self.cache = (self.deserialize_fn)(&bytes).map_err(crate::Error::Deserialize)?;
Ok(())
}
/// Inserts a key-value pair into the store.
pub fn set(&mut self, key: impl Into<String>, value: impl Into<JsonValue>) {
let key = key.into();
let value = value.into();
self.cache.insert(key.clone(), value.clone());
let _ = self.emit_change_event(&key, Some(&value));
}
/// Returns a reference to the value corresponding to the key.
pub fn get(&self, key: impl AsRef<str>) -> Option<&JsonValue> {
self.cache.get(key.as_ref())
}
/// Returns `true` if the given `key` exists in the store.
pub fn has(&self, key: impl AsRef<str>) -> bool {
self.cache.contains_key(key.as_ref())
}
/// Removes a key-value pair from the store.
pub fn delete(&mut self, key: impl AsRef<str>) -> bool {
let flag = self.cache.remove(key.as_ref()).is_some();
if flag {
let _ = self.emit_change_event(key.as_ref(), None);
}
flag
}
/// Clears the store, removing all key-value pairs.
///
/// Note: To clear the storage and reset it to its `default` value, use [`reset`](Self::reset) instead.
pub fn clear(&mut self) {
let keys: Vec<String> = self.cache.keys().cloned().collect();
self.cache.clear();
for key in &keys {
let _ = self.emit_change_event(key, None);
}
}
/// Resets the store to its `default` value.
///
/// If no default value has been set, this method behaves identical to [`clear`](Self::clear).
pub fn reset(&mut self) {
if let Some(defaults) = &self.defaults {
for (key, value) in &self.cache {
if defaults.get(key) != Some(value) {
let _ = self.emit_change_event(key, defaults.get(key));
}
}
for (key, value) in defaults {
if !self.cache.contains_key(key) {
let _ = self.emit_change_event(key, Some(value));
}
}
self.cache.clone_from(defaults);
} else {
self.clear()
}
}
/// An iterator visiting all keys in arbitrary order.
pub fn keys(&self) -> impl Iterator<Item = &String> {
self.cache.keys()
}
/// An iterator visiting all values in arbitrary order.
pub fn values(&self) -> impl Iterator<Item = &JsonValue> {
self.cache.values()
}
/// An iterator visiting all key-value pairs in arbitrary order.
pub fn entries(&self) -> impl Iterator<Item = (&String, &JsonValue)> {
self.cache.iter()
}
/// Returns the number of elements in the store.
pub fn len(&self) -> usize {
self.cache.len()
}
/// Returns true if the store contains no elements.
pub fn is_empty(&self) -> bool {
self.cache.is_empty()
}
fn emit_change_event(&self, key: &str, value: Option<&JsonValue>) -> crate::Result<()> {
let state = self.app.state::<StoreState>();
let stores = state.stores.read().unwrap();
let exists = value.is_some();
self.app.emit(
"store://change",
ChangePayload {
path: &self.path,
resource_id: stores.get(&self.path).copied(),
key,
value,
exists,
},
)?;
Ok(())
}
}
impl<R: Runtime> std::fmt::Debug for StoreInner<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Store")
.field("path", &self.path)
.field("cache", &self.cache)
.finish()
}
}
/// A key-value store, persisted to a file resolved with [`resolve_store_path`].
///
/// The values are kept in memory and written to disk on [`Store::save`], and also automatically
/// after each modification unless auto save has been disabled with
/// [`StoreBuilder::disable_auto_save`]. Any pending auto save is applied when the store is dropped.
///
/// Create or load one with [`StoreExt::store`](crate::StoreExt::store) or [`StoreBuilder`].
/// It is a [`Resource`], so it is also reachable from the frontend by its [`ResourceId`];
/// closing that resource unregisters the store, meaning the next load creates a new instance.
pub struct Store<R: Runtime> {
auto_save: Option<Duration>,
auto_save_debounce_sender: Arc<Mutex<Option<UnboundedSender<AutoSaveMessage>>>>,
store: Arc<Mutex<StoreInner<R>>>,
}
impl<R: Runtime> Resource for Store<R> {
fn close(self: Arc<Self>) {
let store = self.store.lock().unwrap();
let state = store.app.state::<StoreState>();
let mut stores = state.stores.write().unwrap();
stores.remove(&store.path);
}
}
impl<R: Runtime> Store<R> {
// /// Do something with the inner store,
// /// useful for batching some work if you need higher performance
// pub fn with_store<T>(&self, f: impl FnOnce(&mut StoreInner<R>) -> T) -> T {
// let mut store = self.store.lock().unwrap();
// f(&mut store)
// }
/// Inserts a key-value pair into the store.
pub fn set(&self, key: impl Into<String>, value: impl Into<JsonValue>) {
self.store.lock().unwrap().set(key.into(), value.into());
let _ = self.trigger_auto_save();
}
/// Returns the value for the given `key` or `None` if the key does not exist.
pub fn get(&self, key: impl AsRef<str>) -> Option<JsonValue> {
self.store.lock().unwrap().get(key).cloned()
}
/// Returns `true` if the given `key` exists in the store.
pub fn has(&self, key: impl AsRef<str>) -> bool {
self.store.lock().unwrap().has(key)
}
/// Removes a key-value pair from the store.
pub fn delete(&self, key: impl AsRef<str>) -> bool {
let deleted = self.store.lock().unwrap().delete(key);
if deleted {
let _ = self.trigger_auto_save();
}
deleted
}
/// Clears the store, removing all key-value pairs.
///
/// Note: To clear the storage and reset it to its `default` value, use [`reset`](Self::reset) instead.
pub fn clear(&self) {
self.store.lock().unwrap().clear();
let _ = self.trigger_auto_save();
}
/// Resets the store to its `default` value.
///
/// If no default value has been set, this method behaves identical to [`clear`](Self::clear).
pub fn reset(&self) {
self.store.lock().unwrap().reset();
let _ = self.trigger_auto_save();
}
/// Returns a list of all keys in the store.
pub fn keys(&self) -> Vec<String> {
self.store.lock().unwrap().keys().cloned().collect()
}
/// Returns a list of all values in the store.
pub fn values(&self) -> Vec<JsonValue> {
self.store.lock().unwrap().values().cloned().collect()
}
/// Returns a list of all key-value pairs in the store.
pub fn entries(&self) -> Vec<(String, JsonValue)> {
self.store
.lock()
.unwrap()
.entries()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect()
}
/// Returns the number of elements in the store.
pub fn length(&self) -> usize {
self.store.lock().unwrap().len()
}
/// Returns true if the store contains no elements.
pub fn is_empty(&self) -> bool {
self.store.lock().unwrap().is_empty()
}
/// Update the store from the on-disk state
///
/// Note:
/// - This method loads the data and merges it with the current store,
/// this behavior will be changed to resetting to default first and then merging with the on-disk state in v3,
/// to fully match the store with the on-disk state,
/// use [`reload_ignore_defaults`](Self::reload_ignore_defaults) instead
/// - This method does not emit change events
pub fn reload(&self) -> crate::Result<()> {
self.store.lock().unwrap().load()
}
/// Load the store from the on-disk state, ignoring defaults
///
/// Note: This method does not emit change events
pub fn reload_ignore_defaults(&self) -> crate::Result<()> {
self.store.lock().unwrap().load_ignore_defaults()
}
/// Saves the store to disk at the store's `path`.
pub fn save(&self) -> crate::Result<()> {
if let Some(sender) = self.auto_save_debounce_sender.lock().unwrap().take() {
let _ = sender.send(AutoSaveMessage::Cancel);
}
self.store.lock().unwrap().save()
}
/// Removes the store from the resource table
pub fn close_resource(&self) {
let store = self.store.lock().unwrap();
let app = store.app.clone();
let state = app.state::<StoreState>();
let stores = state.stores.read().unwrap();
if let Some(rid) = stores.get(&store.path).copied() {
drop(store);
drop(stores);
let _ = app.resources_table().close(rid);
}
}
fn trigger_auto_save(&self) -> crate::Result<()> {
let Some(auto_save_delay) = self.auto_save else {
return Ok(());
};
if auto_save_delay.is_zero() {
return self.save();
}
let mut auto_save_debounce_sender = self.auto_save_debounce_sender.lock().unwrap();
if let Some(ref sender) = *auto_save_debounce_sender {
let _ = sender.send(AutoSaveMessage::Reset);
return Ok(());
}
let (sender, mut receiver) = unbounded_channel();
auto_save_debounce_sender.replace(sender);
drop(auto_save_debounce_sender);
let store = self.store.clone();
let auto_save_debounce_sender = self.auto_save_debounce_sender.clone();
tauri::async_runtime::spawn(async move {
loop {
select! {
should_cancel = receiver.recv() => {
if matches!(should_cancel, Some(AutoSaveMessage::Cancel) | None) {
return;
}
}
_ = sleep(auto_save_delay) => {
auto_save_debounce_sender.lock().unwrap().take();
let _ = store.lock().unwrap().save();
return;
}
};
}
});
Ok(())
}
fn apply_pending_auto_save(&self) {
// Cancel and save if auto save is pending
let auto_save_debounce_sender = self.auto_save_debounce_sender.lock().unwrap().take();
if let Some(sender) = auto_save_debounce_sender {
let _ = sender.send(AutoSaveMessage::Cancel);
let _ = self.save();
};
}
}
impl<R: Runtime> Drop for Store<R> {
fn drop(&mut self) {
self.apply_pending_auto_save();
}
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "guest-js"
},
"include": ["guest-js/*.ts"]
}