@matiastang/pinia-persisted-state 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +228 -0
- package/README.zh-CN.md +236 -0
- package/dist/favicon.ico +0 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.es.js +121 -0
- package/dist/index.es.js.map +1 -0
- package/dist/index.iife.js +2 -0
- package/dist/index.iife.js.map +1 -0
- package/dist/index.umd.js +2 -0
- package/dist/index.umd.js.map +1 -0
- package/dist/types/index.d.ts +44 -0
- package/package.json +77 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021-present matiastang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
**[English](./README.md)** | [中文](./README.zh-CN.md)
|
|
2
|
+
|
|
3
|
+
# pinia-persisted-state
|
|
4
|
+
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
|
|
7
|
+
## Introduction
|
|
8
|
+
|
|
9
|
+
Local persistence for `pinia` state.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
* `pnpm`
|
|
14
|
+
```sh
|
|
15
|
+
$ pnpm add @matiastang/pinia-persisted-state
|
|
16
|
+
```
|
|
17
|
+
* `yarn`
|
|
18
|
+
```sh
|
|
19
|
+
$ yarn add @matiastang/pinia-persisted-state
|
|
20
|
+
```
|
|
21
|
+
* `npm`
|
|
22
|
+
```sh
|
|
23
|
+
$ npm install @matiastang/pinia-persisted-state
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Setup
|
|
27
|
+
|
|
28
|
+
* Quick setup in `main.ts`:
|
|
29
|
+
```ts
|
|
30
|
+
// pinia state management
|
|
31
|
+
import { createPinia } from 'pinia'
|
|
32
|
+
import { createPersistedState, persistedConfig } from '@matiastang/pinia-persisted-state'
|
|
33
|
+
|
|
34
|
+
const app = createApp(App)
|
|
35
|
+
|
|
36
|
+
// pinia
|
|
37
|
+
const pinia = createPinia()
|
|
38
|
+
|
|
39
|
+
// Quick usage
|
|
40
|
+
pinia.use(createPersistedState)
|
|
41
|
+
// View default config
|
|
42
|
+
console.log(persistedConfig)
|
|
43
|
+
|
|
44
|
+
app.use(pinia)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
* Setup with custom config in `main.ts`:
|
|
48
|
+
```ts
|
|
49
|
+
// pinia state management
|
|
50
|
+
import { createPinia } from 'pinia'
|
|
51
|
+
import { createPersistedState, persistedConfig } from '@matiastang/pinia-persisted-state'
|
|
52
|
+
|
|
53
|
+
const app = createApp(App)
|
|
54
|
+
|
|
55
|
+
// pinia
|
|
56
|
+
const pinia = createPinia()
|
|
57
|
+
|
|
58
|
+
// Usage with config
|
|
59
|
+
pinia.use(
|
|
60
|
+
createPersistedState({
|
|
61
|
+
key: 'pinia-key',
|
|
62
|
+
})
|
|
63
|
+
)
|
|
64
|
+
// View config
|
|
65
|
+
console.log(persistedConfig)
|
|
66
|
+
|
|
67
|
+
app.use(pinia)
|
|
68
|
+
```
|
|
69
|
+
* `persistedConfig` is the config of `@matiastang/pinia-persisted-state`.
|
|
70
|
+
* `persistedConfig.key` is the localStorage key for state persistence, default value is `pinia-key`.
|
|
71
|
+
* `persistedConfig.customKey` is the localStorage key for `custom properties` persistence, default value is `pinia-custom-key`.
|
|
72
|
+
* `persistedConfig.customFilterKey` is the filter function that decides which store members are cached as custom properties (by default, keys prefixed with `$`, `_` or `set` are excluded).
|
|
73
|
+
|
|
74
|
+
## Usage
|
|
75
|
+
|
|
76
|
+
Once set up, all pinia states and their updates are saved to `storage`.
|
|
77
|
+
**Note**: `custom properties` and `state properties` are only synced to `storage` when they are assigned.
|
|
78
|
+
|
|
79
|
+
* Declare an `authUser Store` with initial values.
|
|
80
|
+
```ts
|
|
81
|
+
import { defineStore } from 'pinia'
|
|
82
|
+
|
|
83
|
+
interface State {
|
|
84
|
+
name: string
|
|
85
|
+
age: string
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export const useAuthUserStore = defineStore('user', {
|
|
89
|
+
state: (): State => ({
|
|
90
|
+
name: 'name',
|
|
91
|
+
age: 'age',
|
|
92
|
+
}),
|
|
93
|
+
actions: {
|
|
94
|
+
setName(name: string) {
|
|
95
|
+
this.name = name
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
})
|
|
99
|
+
```
|
|
100
|
+
* Declare `custom properties`
|
|
101
|
+
```ts
|
|
102
|
+
import 'pinia'
|
|
103
|
+
import { Ref } from 'vue'
|
|
104
|
+
|
|
105
|
+
declare module 'pinia' {
|
|
106
|
+
export interface PiniaCustomProperties {
|
|
107
|
+
// by using a setter we can allow both strings and refs
|
|
108
|
+
set userId(value: string | Ref<string>)
|
|
109
|
+
get userId(): string
|
|
110
|
+
|
|
111
|
+
// you can define simpler values too
|
|
112
|
+
simpleNumber: number
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
* Declare `state properties`
|
|
117
|
+
```ts
|
|
118
|
+
import 'pinia'
|
|
119
|
+
import { Ref } from 'vue'
|
|
120
|
+
|
|
121
|
+
declare module 'pinia' {
|
|
122
|
+
export interface PiniaCustomStateProperties<S> {
|
|
123
|
+
set hello(value: string | Ref<string>)
|
|
124
|
+
get hello(): string
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
* Use and inspect the state
|
|
129
|
+
```ts
|
|
130
|
+
import { useAuthUserStore } from '@/pinia/useAuthUserStore'
|
|
131
|
+
import { useTestStore } from '@/pinia/useTest'
|
|
132
|
+
|
|
133
|
+
const userStore = useAuthUserStore()
|
|
134
|
+
const testStore = useTestStore()
|
|
135
|
+
// output
|
|
136
|
+
console.log(
|
|
137
|
+
userStore.simpleNumber,
|
|
138
|
+
userStore.userId,
|
|
139
|
+
userStore.$state.hello,
|
|
140
|
+
testStore.simpleNumber,
|
|
141
|
+
testStore.userId,
|
|
142
|
+
testStore.$state.hello
|
|
143
|
+
)
|
|
144
|
+
```
|
|
145
|
+
* Inspect the `pinia-key` data saved in `storage` **(or the key you configured)**
|
|
146
|
+
```json
|
|
147
|
+
{
|
|
148
|
+
test: {data: "data"}
|
|
149
|
+
user: {name: "name", age: "age"}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
**Note**: `custom properties` and `state properties` are only declarations. Data appears after assignment.
|
|
153
|
+
```ts
|
|
154
|
+
userStore.userId = '001'
|
|
155
|
+
userStore.simpleNumber = 99
|
|
156
|
+
userStore.$state.hello = 'hello user'
|
|
157
|
+
|
|
158
|
+
testStore.userId = '002'
|
|
159
|
+
testStore.simpleNumber = 100
|
|
160
|
+
testStore.$state.hello = 'hello test'
|
|
161
|
+
```
|
|
162
|
+
```json
|
|
163
|
+
{
|
|
164
|
+
pinia-custom-key: {userId: "001", simpleNumber: 99}
|
|
165
|
+
test: {data: "data", hello: "hello test"}
|
|
166
|
+
user: {name: "name", age: "age", hello: "hello user"}
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
* As you can see, `custom properties` like `userId` and `simpleNumber` are updated identically through both `userStore` and `testStore` — they act as pinia global variables. Shared `state properties` like `hello` are controlled by each store itself. Since both stores share the same `hello` ref injected by a plugin, updating `context.store.$state.hello` updates it everywhere. Therefore you can write your own plugin placed after `@matiastang/pinia-persisted-state` to initialize or update `state properties` globally.
|
|
170
|
+
```ts
|
|
171
|
+
const userID = ref('000001')
|
|
172
|
+
const hello = ref('hello pinia')
|
|
173
|
+
// Custom base plugin, updates state
|
|
174
|
+
export function myPiniaPlugin(context: PiniaPluginContext) {
|
|
175
|
+
// custom properties can also be handled inside plugins
|
|
176
|
+
context.store.userId = userID
|
|
177
|
+
// assign
|
|
178
|
+
context.store.$state.hello = hello
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
```ts
|
|
182
|
+
// pinia state management
|
|
183
|
+
import { createPinia } from 'pinia'
|
|
184
|
+
import { myPiniaPlugin } from '@/pinia/plugin'
|
|
185
|
+
import { createPersistedState, persistedConfig } from '@matiastang/pinia-persisted-state'
|
|
186
|
+
|
|
187
|
+
const app = createApp(App)
|
|
188
|
+
|
|
189
|
+
// pinia
|
|
190
|
+
const pinia = createPinia()
|
|
191
|
+
|
|
192
|
+
// Quick usage
|
|
193
|
+
pinia.use(createPersistedState)
|
|
194
|
+
// View default config
|
|
195
|
+
console.log(persistedConfig)
|
|
196
|
+
// Plugin with state updates
|
|
197
|
+
pinia.use(myPiniaPlugin)
|
|
198
|
+
|
|
199
|
+
app.use(pinia)
|
|
200
|
+
```
|
|
201
|
+
The data in `storage` will be updated.
|
|
202
|
+
```json
|
|
203
|
+
{
|
|
204
|
+
pinia-custom-key: {userId: "002", simpleNumber: 99}
|
|
205
|
+
test: {data: "data", hello: "hello pinia"}
|
|
206
|
+
user: {name: "name", age: "age", hello: "hello pinia"}
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
In short: `@matiastang/pinia-persisted-state` persists the data inside your pinia stores.
|
|
210
|
+
|
|
211
|
+
## Testing
|
|
212
|
+
|
|
213
|
+
```sh
|
|
214
|
+
$ pnpm run typecheck # type check
|
|
215
|
+
$ pnpm test # unit / integration tests
|
|
216
|
+
$ pnpm run test:coverage # coverage report
|
|
217
|
+
$ pnpm run test:e2e # e2e tests (starts the demo app automatically)
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
See [specs/001-test-suite/quickstart.md](./specs/001-test-suite/quickstart.md) for details.
|
|
221
|
+
|
|
222
|
+
## Versions
|
|
223
|
+
|
|
224
|
+
See [CHANGELOG.md](./CHANGELOG.md).
|
|
225
|
+
|
|
226
|
+
## License
|
|
227
|
+
|
|
228
|
+
[MIT](./LICENSE) © matiastang
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
[English](./README.md) | **[中文](./README.zh-CN.md)**
|
|
2
|
+
|
|
3
|
+
<!--
|
|
4
|
+
* @Author: matiastang
|
|
5
|
+
* @Date: 2021-12-13 10:12:56
|
|
6
|
+
* @LastEditors: matiastang
|
|
7
|
+
* @LastEditTime: 2026-08-23
|
|
8
|
+
* @FilePath: /pinia-persisted-state/README.zh-CN.md
|
|
9
|
+
* @Description: 中文说明文档
|
|
10
|
+
-->
|
|
11
|
+
# pinia-persisted-state
|
|
12
|
+
|
|
13
|
+
[](./LICENSE)
|
|
14
|
+
|
|
15
|
+
## 说明
|
|
16
|
+
|
|
17
|
+
`pinia`状态的本地持久化。
|
|
18
|
+
|
|
19
|
+
## 安装
|
|
20
|
+
|
|
21
|
+
* `pnpm`导入
|
|
22
|
+
```sh
|
|
23
|
+
$ pnpm add @matiastang/pinia-persisted-state
|
|
24
|
+
```
|
|
25
|
+
* `yarn`导入
|
|
26
|
+
```sh
|
|
27
|
+
$ yarn add @matiastang/pinia-persisted-state
|
|
28
|
+
```
|
|
29
|
+
* `npm`
|
|
30
|
+
```sh
|
|
31
|
+
$ npm install @matiastang/pinia-persisted-state
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## 配置
|
|
35
|
+
|
|
36
|
+
* 在`main.ts`中如下便捷导入`@matiastang/pinia-persisted-state`:
|
|
37
|
+
```ts
|
|
38
|
+
// pinia状态管理
|
|
39
|
+
import { createPinia } from 'pinia'
|
|
40
|
+
import { createPersistedState, persistedConfig } from '@matiastang/pinia-persisted-state'
|
|
41
|
+
|
|
42
|
+
const app = createApp(App)
|
|
43
|
+
|
|
44
|
+
// pinia
|
|
45
|
+
const pinia = createPinia()
|
|
46
|
+
|
|
47
|
+
// 便捷使用
|
|
48
|
+
pinia.use(createPersistedState)
|
|
49
|
+
// 查看默认配置
|
|
50
|
+
console.log(persistedConfig)
|
|
51
|
+
|
|
52
|
+
app.use(pinia)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
* 在`main.ts`中如下带配置导入`@matiastang/pinia-persisted-state`:
|
|
56
|
+
```ts
|
|
57
|
+
// pinia状态管理
|
|
58
|
+
import { createPinia } from 'pinia'
|
|
59
|
+
import { createPersistedState, persistedConfig } from '@matiastang/pinia-persisted-state'
|
|
60
|
+
|
|
61
|
+
const app = createApp(App)
|
|
62
|
+
|
|
63
|
+
// pinia
|
|
64
|
+
const pinia = createPinia()
|
|
65
|
+
|
|
66
|
+
// 带配置使用
|
|
67
|
+
pinia.use(
|
|
68
|
+
createPersistedState({
|
|
69
|
+
key: 'pinia-key',
|
|
70
|
+
})
|
|
71
|
+
)
|
|
72
|
+
// 查看配置
|
|
73
|
+
console.log(persistedConfig)
|
|
74
|
+
|
|
75
|
+
app.use(pinia)
|
|
76
|
+
```
|
|
77
|
+
* `persistedConfig`为`@matiastang/pinia-persisted-state`的配置。
|
|
78
|
+
* `persistedConfig.key`是本地持久化`key`,默认值是`pinia-key`。
|
|
79
|
+
* `persistedConfig.customKey`是`custom properties`本地持久化`key`,默认值是`pinia-custom-key`。
|
|
80
|
+
* `persistedConfig.customFilterKey`是判定 store 成员是否缓存为`custom properties`的过滤函数,默认排除`$`、`_`、`set`前缀的属性。
|
|
81
|
+
|
|
82
|
+
## 使用
|
|
83
|
+
|
|
84
|
+
完成引入后,则`pinia`的所有状态及更新都将保存到`storage`中。
|
|
85
|
+
**注意**`custom properties`和`state properties`在赋值的时候才会同步到`storage`
|
|
86
|
+
|
|
87
|
+
* 声明`authUser Store`,带有初始化值。
|
|
88
|
+
```ts
|
|
89
|
+
import { defineStore } from 'pinia'
|
|
90
|
+
|
|
91
|
+
interface State {
|
|
92
|
+
name: string
|
|
93
|
+
age: string
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export const useAuthUserStore = defineStore('user', {
|
|
97
|
+
state: (): State => ({
|
|
98
|
+
name: 'name',
|
|
99
|
+
age: 'age',
|
|
100
|
+
}),
|
|
101
|
+
actions: {
|
|
102
|
+
setName(name: string) {
|
|
103
|
+
this.name = name
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
})
|
|
107
|
+
```
|
|
108
|
+
* 声明`custom properties`
|
|
109
|
+
```ts
|
|
110
|
+
import 'pinia'
|
|
111
|
+
import { Ref } from 'vue'
|
|
112
|
+
|
|
113
|
+
declare module 'pinia' {
|
|
114
|
+
export interface PiniaCustomProperties {
|
|
115
|
+
// by using a setter we can allow both strings and refs
|
|
116
|
+
set userId(value: string | Ref<string>)
|
|
117
|
+
get userId(): string
|
|
118
|
+
|
|
119
|
+
// you can define simpler values too
|
|
120
|
+
simpleNumber: number
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
* 声明`state properties`
|
|
125
|
+
```ts
|
|
126
|
+
import 'pinia'
|
|
127
|
+
import { Ref } from 'vue'
|
|
128
|
+
|
|
129
|
+
declare module 'pinia' {
|
|
130
|
+
export interface PiniaCustomStateProperties<S> {
|
|
131
|
+
set hello(value: string | Ref<string>)
|
|
132
|
+
get hello(): string
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
* 使用并查看状态
|
|
137
|
+
```ts
|
|
138
|
+
import { useAuthUserStore } from '@/pinia/useAuthUserStore'
|
|
139
|
+
import { useTestStore } from '@/pinia/useTest'
|
|
140
|
+
|
|
141
|
+
const userStore = useAuthUserStore()
|
|
142
|
+
const testStore = useTestStore()
|
|
143
|
+
// 输出
|
|
144
|
+
console.log(
|
|
145
|
+
userStore.simpleNumber,
|
|
146
|
+
userStore.userId,
|
|
147
|
+
userStore.$state.hello,
|
|
148
|
+
testStore.simpleNumber,
|
|
149
|
+
testStore.userId,
|
|
150
|
+
testStore.$state.hello
|
|
151
|
+
)
|
|
152
|
+
```
|
|
153
|
+
* 查看`storage`中保存的`pinia-key`数据**如果配置了key则是对应的数据**
|
|
154
|
+
```json
|
|
155
|
+
{
|
|
156
|
+
test: {data: "data"}
|
|
157
|
+
user: {name: "name", age: "age"}
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
**说明**`custom properties`和`state properties`中只是申明。所有需要赋值之后才能看到数据。
|
|
161
|
+
```ts
|
|
162
|
+
userStore.userId = '001'
|
|
163
|
+
userStore.simpleNumber = 99
|
|
164
|
+
userStore.$state.hello = 'hello user'
|
|
165
|
+
|
|
166
|
+
testStore.userId = '002'
|
|
167
|
+
testStore.simpleNumber = 100
|
|
168
|
+
testStore.$state.hello = 'hello test'
|
|
169
|
+
```
|
|
170
|
+
```json
|
|
171
|
+
{
|
|
172
|
+
pinia-custom-key: {userId: "001", simpleNumber: 99}
|
|
173
|
+
test: {data: "data", hello: "hello test"}
|
|
174
|
+
user: {name: "name", age: "age", hello: "hello user"}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
* 可以看到`userId`和`simpleNumber`这种`custom properties`使用`userStore`和`testStore`更新都是一样的,可以理解为`pinia`的全局变量。而`hello`这种共有`state properties`需要每个`store`自己控制。使用`context.store.$state.hello`可以修改所有`store`的`hello`熟悉。因此可以自己写一个插件放到`@matiastang/pinia-persisted-state`该插件之后,全量初始或更新`state properties`中的数据。
|
|
178
|
+
```ts
|
|
179
|
+
const userID = ref('000001')
|
|
180
|
+
const hello = ref('hello pinia')
|
|
181
|
+
// 自定义基础插件,更新状态
|
|
182
|
+
export function myPiniaPlugin(context: PiniaPluginContext) {
|
|
183
|
+
// 当然插件里面也可以处理custom properties
|
|
184
|
+
context.store.userId = userID
|
|
185
|
+
// 赋值
|
|
186
|
+
context.store.$state.hello = hello
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
```ts
|
|
190
|
+
// pinia状态管理
|
|
191
|
+
import { createPinia } from 'pinia'
|
|
192
|
+
import { myPiniaPlugin } from '@/pinia/plugin'
|
|
193
|
+
import { createPersistedState, persistedConfig } from '@matiastang/pinia-persisted-state'
|
|
194
|
+
|
|
195
|
+
const app = createApp(App)
|
|
196
|
+
|
|
197
|
+
// pinia
|
|
198
|
+
const pinia = createPinia()
|
|
199
|
+
|
|
200
|
+
// 便捷使用
|
|
201
|
+
pinia.use(createPersistedState)
|
|
202
|
+
// 查看默认配置
|
|
203
|
+
console.log(persistedConfig)
|
|
204
|
+
// 有状态更新的插件
|
|
205
|
+
pinia.use(myPiniaPlugin)
|
|
206
|
+
|
|
207
|
+
app.use(pinia)
|
|
208
|
+
```
|
|
209
|
+
`storage`中的数据将更新。
|
|
210
|
+
```json
|
|
211
|
+
{
|
|
212
|
+
pinia-custom-key: {userId: "002", simpleNumber: 99}
|
|
213
|
+
test: {data: "data", hello: "hello pinia"}
|
|
214
|
+
user: {name: "name", age: "age", hello: "hello pinia"}
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
有点儿说多了,只需要知道`@matiastang/pinia-persisted-state`将持久化存储`pinia`中的数据就行。
|
|
218
|
+
|
|
219
|
+
## 测试
|
|
220
|
+
|
|
221
|
+
```sh
|
|
222
|
+
$ pnpm run typecheck # 类型检查
|
|
223
|
+
$ pnpm test # 单元/集成测试
|
|
224
|
+
$ pnpm run test:coverage # 覆盖率报告
|
|
225
|
+
$ pnpm run test:e2e # 端到端测试(自动启动演示工程)
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
详细说明见 [specs/001-test-suite/quickstart.md](./specs/001-test-suite/quickstart.md)。
|
|
229
|
+
|
|
230
|
+
## 版本
|
|
231
|
+
|
|
232
|
+
版本更新记录见 [CHANGELOG.md](./CHANGELOG.md)。
|
|
233
|
+
|
|
234
|
+
## 许可证
|
|
235
|
+
|
|
236
|
+
[MIT](./LICENSE) © matiastang
|
package/dist/favicon.ico
ADDED
|
Binary file
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var d,O=((d=O||{}).LOCAL="localStorage",d.SESSION="sessionStorage",d);const S=t=>typeof t=="string"?t:t.key;class p extends Error{constructor(e){super(e),this.name="StorageSerializeError"}}const g="__matias_tag__",b="__matias_value__",v=new Set(["NaN","Infinity","-Infinity","undefined"]),y=t=>({[g]:t}),l=(t,e)=>({[g]:t,[b]:e}),a=(t,e)=>{if(t===null)return null;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isNaN(t)?y("NaN"):t===1/0?y("Infinity"):t===-1/0?y("-Infinity"):t;if(typeof t=="bigint")return l("BigInt",t.toString());if(t===void 0)return y("undefined");if(typeof t=="function"||typeof t=="symbol")throw new p("unsupported top-level value type: "+typeof t);if(t instanceof Date)return l("Date",t.getTime());if(t instanceof RegExp)return l("RegExp",{s:t.source,f:t.flags});if(t instanceof Map)return l("Map",Array.from(t.entries(),([r,n])=>[a(r,e),a(n,e)]));if(t instanceof Set)return l("Set",Array.from(t.values(),r=>a(r,e)));if(Array.isArray(t))return t.map(r=>typeof r=="function"||typeof r=="symbol"?null:a(r,e));const o=t;if(typeof o.toJSON=="function")return a(o.toJSON(),e);if(e.has(t))throw new p("circular reference detected");e.add(t);const i={};for(const r of Object.keys(o)){const n=o[r];typeof n!="function"&&typeof n!="symbol"&&(i[r]=a(n,e))}return e.delete(t),i},f=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(f);const e=(r=>{const n=r;if(typeof n[g]!="string")return null;const s=n[g];return v.has(s)||Object.prototype.hasOwnProperty.call(n,b)&&["Date","Map","Set","RegExp","BigInt"].includes(s)?s:null})(t);if(e==="undefined")return;if(e==="NaN")return NaN;if(e==="Infinity")return 1/0;if(e==="-Infinity")return-1/0;const o=t[b];if(e==="Date")return new Date(o);if(e==="RegExp"){const{s:r,f:n}=o;return new RegExp(r,n)}if(e==="BigInt")try{return BigInt(o)}catch{throw new p(`invalid BigInt payload: ${String(o)}`)}if(e==="Map")return new Map(o.map(([r,n])=>[f(r),f(n)]));if(e==="Set")return new Set(o.map(f));const i={};for(const r of Object.keys(t)){const n=f(t[r]);r==="__proto__"?Object.defineProperty(i,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):i[r]=n}return i},c=(t,e)=>{const o=S(t);if(e===void 0)return localStorage.removeItem(o),!0;try{return localStorage.setItem(o,(i=>JSON.stringify(a(i,new Set)))(e)),!0}catch(i){return console.warn(`matias-storage localStorage write ${o} value=${String(e)}:`,i instanceof p?i.message:i),!1}},w=t=>{const e=localStorage.getItem(S(t));if(e===null)return null;try{return(o=>f(JSON.parse(o)))(e)}catch(o){console.warn(`matias-storage localStorage read ${S(t)}:`,o instanceof p?o.message:o)}return null},_="https://www.npmjs.com/package/@matiastang/pinia-persisted-state";exports.persistedConfig={key:"pinia-key",customKey:"pinia-custom-key",customFilterKey:t=>!t.startsWith("$")&&!t.startsWith("_")&&!t.startsWith("set")};const h=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),N=(t,e)=>{const o=exports.persistedConfig.key,i=w(o);if(!h(i))return void c(o,{[e]:t});const r=i[e];if(r===void 0)return i[e]=t,void c(o,i);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const s=t[n];if(Object.prototype.hasOwnProperty.call(r,n)){const u=r[n];s!==u&&(t[n]=u)}}i[e]=t,c(o,i)},I=t=>{const e=t.store,o=Object.keys(e.$state),i=Object.keys(e).filter(n=>exports.persistedConfig.customFilterKey(n));let r={};for(let n=0;n<i.length;n++){const s=i[n];o.includes(s)||(Object.keys(r).length<=0?r={[s]:e[s]}:r[s]=e[s])}return r};function m(t){const e=exports.persistedConfig.key,o=exports.persistedConfig.customKey,i=t.store.$state,r=t.store.$id;r.trim()!==""?(N(i,r),t.store.$subscribe(()=>{const n=I(t),s=w(e);if(!h(s))return void(Object.keys(n).length>0?c(e,{[o]:{...n},[r]:i}):c(e,{[r]:i}));const u=s[o];s[o]=u?{...u,...n}:{...n},s[r]=i,c(e,s)},{detached:!0})):console.error("store id 不能为空,详情查看:",_)}exports.createPersistedState=function(t){return t&&(exports.persistedConfig={...exports.persistedConfig,...t}),m},exports.default=m,exports.piniaPersistedState=m;
|
|
2
|
+
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../node_modules/.pnpm/matias-storage@0.3.0/node_modules/matias-storage/dist/index.es.js","../src/plugin/index.ts"],"sourcesContent":["var i = ((e) => (e.LOCAL = \"localStorage\", e.SESSION = \"sessionStorage\", e))(i || {});\nconst I = Symbol(\"matias.storageKey\"), L = (e, t = i.LOCAL) => ({ key: e, storageType: t, [I]: void 0 }), s = (e) => typeof e == \"string\" ? e : e.key, m = (e, t) => t !== void 0 ? t : typeof e == \"string\" ? i.LOCAL : e.storageType;\nclass u extends Error {\n constructor(t) {\n super(t), this.name = \"StorageSerializeError\";\n }\n}\nconst y = \"__matias_tag__\", p = \"__matias_value__\", w = /* @__PURE__ */ new Set([\"NaN\", \"Infinity\", \"-Infinity\", \"undefined\"]), S = (e) => ({ [y]: e }), g = (e, t) => ({ [y]: e, [p]: t }), f = (e, t) => {\n if (e === null) return null;\n if (typeof e == \"string\" || typeof e == \"boolean\") return e;\n if (typeof e == \"number\") return Number.isNaN(e) ? S(\"NaN\") : e === 1 / 0 ? S(\"Infinity\") : e === -1 / 0 ? S(\"-Infinity\") : e;\n if (typeof e == \"bigint\") return g(\"BigInt\", e.toString());\n if (e === void 0) return S(\"undefined\");\n if (typeof e == \"function\" || typeof e == \"symbol\") throw new u(\"unsupported top-level value type: \" + typeof e);\n if (e instanceof Date) return g(\"Date\", e.getTime());\n if (e instanceof RegExp) return g(\"RegExp\", { s: e.source, f: e.flags });\n if (e instanceof Map) return g(\"Map\", Array.from(e.entries(), ([n, a]) => [f(n, t), f(a, t)]));\n if (e instanceof Set) return g(\"Set\", Array.from(e.values(), (n) => f(n, t)));\n if (Array.isArray(e)) return e.map((n) => typeof n == \"function\" || typeof n == \"symbol\" ? null : f(n, t));\n const r = e;\n if (typeof r.toJSON == \"function\") return f(r.toJSON(), t);\n if (t.has(e)) throw new u(\"circular reference detected\");\n t.add(e);\n const o = {};\n for (const n of Object.keys(r)) {\n const a = r[n];\n typeof a != \"function\" && typeof a != \"symbol\" && (o[n] = f(a, t));\n }\n return t.delete(e), o;\n}, d = (e) => JSON.stringify(f(e, /* @__PURE__ */ new Set())), c = (e) => {\n if (e === null || typeof e != \"object\") return e;\n if (Array.isArray(e)) return e.map(c);\n const t = ((n) => {\n const a = n;\n if (typeof a[y] != \"string\") return null;\n const l = a[y];\n return w.has(l) || Object.prototype.hasOwnProperty.call(a, p) && [\"Date\", \"Map\", \"Set\", \"RegExp\", \"BigInt\"].includes(l) ? l : null;\n })(e);\n if (t === \"undefined\") return;\n if (t === \"NaN\") return NaN;\n if (t === \"Infinity\") return 1 / 0;\n if (t === \"-Infinity\") return -1 / 0;\n const r = e[p];\n if (t === \"Date\") return new Date(r);\n if (t === \"RegExp\") {\n const { s: n, f: a } = r;\n return new RegExp(n, a);\n }\n if (t === \"BigInt\") try {\n return BigInt(r);\n } catch {\n throw new u(`invalid BigInt payload: ${String(r)}`);\n }\n if (t === \"Map\") return new Map(r.map(([n, a]) => [c(n), c(a)]));\n if (t === \"Set\") return new Set(r.map(c));\n const o = {};\n for (const n of Object.keys(e)) {\n const a = c(e[n]);\n n === \"__proto__\" ? Object.defineProperty(o, n, { value: a, enumerable: !0, writable: !0, configurable: !0 }) : o[n] = a;\n }\n return o;\n}, v = (e) => c(JSON.parse(e)), N = (e, t) => {\n const r = s(e);\n if (t === void 0) return localStorage.removeItem(r), !0;\n try {\n return localStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage localStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, O = (e) => {\n const t = localStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage localStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, b = (e) => {\n localStorage.removeItem(s(e));\n}, _ = () => {\n localStorage.clear();\n}, h = (e, t) => {\n const r = s(e);\n if (t === void 0) return sessionStorage.removeItem(r), !0;\n try {\n return sessionStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage sessionStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, R = (e) => {\n const t = sessionStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage sessionStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, A = (e) => {\n sessionStorage.removeItem(s(e));\n}, E = () => {\n sessionStorage.clear();\n};\nfunction $(e, t, r) {\n const o = m(e, r), n = s(e);\n return o === i.SESSION ? h(n, t) : N(n, t);\n}\nfunction x(e, t, r) {\n const o = typeof t == \"function\" ? t : r, n = m(e, typeof t == \"function\" ? void 0 : t), a = s(e), l = n === i.SESSION ? R(a) : O(a);\n return l === null ? null : o && !o(l) ? (console.warn(`matias-storage storage read ${a}: value failed the type guard, return null instead`), null) : l;\n}\nfunction j(e, t) {\n const r = m(e, t), o = s(e);\n r === i.SESSION ? A(o) : b(o);\n}\nconst B = (e = i.LOCAL) => {\n e === i.SESSION ? E() : _();\n};\nexport {\n i as WebStorageType,\n L as defineStorageKey,\n O as localStorageRead,\n b as localStorageRemove,\n _ as localStorageRemoveAll,\n N as localStorageWrite,\n s as resolveKeyString,\n m as resolveStorageType,\n R as sessionStorageRead,\n A as sessionStorageRemove,\n E as sessionStorageRemoveAll,\n h as sessionStorageWrite,\n x as storageRead,\n j as storageRemove,\n B as storageRemoveAll,\n $ as storageWrite\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * @Author: matiastang\n * @Date: 2022-02-09 17:17:20\n * @LastEditors: matiastang\n * @LastEditTime: 2024-07-16 18:28:21\n * @FilePath: /pinia-persisted-state/src/plugin/index.ts\n * @Description: pinia状态本地存储插件\n */\nimport type { PiniaPluginContext, PiniaCustomStateProperties, StateTree } from 'pinia'\nimport { localStorageRead, localStorageWrite } from 'matias-storage'\n\nconst NPMLINK = 'https://www.npmjs.com/package/@matiastang/pinia-persisted-state'\nconst PINIA_STORAGE_KEY = 'pinia-key'\nconst PINIA_STORAGE_CUSTOM_KEY = 'pinia-custom-key'\n\n/**\n * 需要对MapStoresCustomization类型进行扩展,不然将报错\n * Property 'suffix' does not exist on type 'MapStoresCustomization'.\n * [Id in `${Ids}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}`]: () => Store<Id extends `${infer RealId}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}` ? RealId : string, State, Getters, Actions>;\n */\ndeclare module 'pinia' {\n export interface MapStoresCustomization {\n suffix: string\n }\n}\n\n/**\n * 状态持久化config类型\n */\ninterface PersistedStateConfig {\n /**\n * 保存pinia的key\n */\n key?: string\n /**\n * 保存pinia custom properties的key\n */\n customKey?: string\n /**\n * 获取custom properties key 的过滤函数\n */\n customFilterKey?: (key: string) => boolean\n}\n\n/**\n * custom properties 类型\n */\ntype CustomPropertiesType = {\n [key: string]: StateTree & PiniaCustomStateProperties<StateTree>\n}\n\n/**\n * 状态持久化config\n */\nexport let persistedConfig: PersistedStateConfig = {\n key: PINIA_STORAGE_KEY,\n customKey: PINIA_STORAGE_CUSTOM_KEY,\n customFilterKey: (key: string) => {\n return !key.startsWith('$') && !key.startsWith('_') && !key.startsWith('set')\n },\n}\n\n/**\n * 判断本地数据是否为可用的记录对象(非null的非数组对象)\n * @param data\n * @returns\n */\nconst _isRecordObject = (\n data: unknown\n): data is StateTree & PiniaCustomStateProperties<StateTree> => {\n return typeof data === 'object' && data !== null && !Array.isArray(data)\n}\n\n/**\n * 本地存储数据差异化检测,更新\n * @param state\n * @param key\n * @returns\n */\nconst _localStateDiff = (\n state: StateTree & PiniaCustomStateProperties<StateTree>,\n stateKey: string\n) => {\n const persistedKey = persistedConfig.key\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或数据损坏/结构非法,均以初始值重建)\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n return\n }\n const localNameState = localState[stateKey]\n if (localNameState === undefined) {\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n return\n }\n // 差异查找更新\n for (const key in state) {\n if (Object.prototype.hasOwnProperty.call(state, key)) {\n const element = state[key]\n if (Object.prototype.hasOwnProperty.call(localNameState, key)) {\n const localElement = localNameState[key]\n if (element !== localElement) {\n state[key] = localElement\n }\n }\n }\n }\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n}\n\n/**\n * 获取custom properties\n * @param context\n * @returns\n */\nconst _contextCustomProperties = (context: PiniaPluginContext) => {\n const store = context.store\n const stateKeys = Object.keys(store.$state)\n const customKeys = Object.keys(store).filter((key) => {\n return persistedConfig.customFilterKey(key)\n })\n let customProperties = {} as CustomPropertiesType\n for (let i = 0; i < customKeys.length; i++) {\n const item = customKeys[i]\n if (!stateKeys.includes(item)) {\n if (Object.keys(customProperties).length <= 0) {\n customProperties = {\n [item]: store[item],\n }\n } else {\n customProperties[item] = store[item]\n }\n }\n }\n return customProperties\n}\n\n/**\n * pinia state 本地存储\n * @param context pinia context\n */\nexport function piniaPersistedState(context: PiniaPluginContext) {\n /**\n * FIXME: - 不能检测到customProperties和stateProperties,在调用customProperties和stateProperties之前\n */\n const persistedKey = persistedConfig.key\n const customKey = persistedConfig.customKey\n const state = context.store.$state\n const stateKey = context.store.$id\n if (stateKey.trim() === '') {\n console.error('store id 不能为空,详情查看:', NPMLINK)\n return\n }\n // 初始化检测更新\n _localStateDiff(state, stateKey)\n context.store.$subscribe(\n () => {\n const customProperties = _contextCustomProperties(context)\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或结构非法时重建)\n if (Object.keys(customProperties).length > 0) {\n localStorageWrite(persistedKey, {\n [customKey]: {\n ...customProperties,\n },\n [stateKey]: state,\n })\n } else {\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n }\n return\n }\n const localCustom = localState[customKey]\n if (localCustom) {\n localState[customKey] = {\n ...localCustom,\n ...customProperties,\n }\n } else {\n localState[customKey] = {\n ...customProperties,\n }\n }\n localState[stateKey] = state\n // 直接更新存储状态\n // FIXME: - 非状态更新也会调用,可能会有性能问题\n localStorageWrite(persistedKey, localState)\n },\n {\n detached: true,\n }\n )\n}\n\n/**\n * 带配置创建pinia state 本地存储\n * @param config\n * @returns\n */\nexport function createPersistedState(config?: PersistedStateConfig) {\n if (config) {\n persistedConfig = {\n ...persistedConfig,\n ...config,\n }\n }\n return piniaPersistedState\n}\n\nexport default piniaPersistedState\n"],"names":["e","i","LOCAL","SESSION","s","key","u","Error","t","super","this","name","y","p","w","Set","S","g","f","Number","isNaN","toString","Date","getTime","RegExp","source","flags","Map","Array","from","entries","n","a","values","isArray","map","r","toJSON","has","add","o","Object","keys","delete","c","l","prototype","hasOwnProperty","call","includes","NaN","BigInt","String","defineProperty","value","enumerable","writable","configurable","N","localStorage","removeItem","setItem","JSON","stringify","console","warn","message","O","getItem","parse","v","NPMLINK","persistedConfig","customKey","customFilterKey","startsWith","_isRecordObject","data","_localStateDiff","state","stateKey","persistedKey","localState","localStorageRead","localStorageWrite","localNameState","element","localElement","_contextCustomProperties","context","store","stateKeys","$state","customKeys","filter","customProperties","length","item","piniaPersistedState","$id","trim","$subscribe","localCustom","detached","error","config"],"mappings":"4GAAA,IAAUA,EAANC,IAAMD,EAAmEC,GAAK,CAAE,GAAjEC,MAAQ,eAAgBF,EAAEG,QAAU,iBAAkBH,GACpE,MAAqGI,EAAKJ,GAAaA,OAAAA,GAAK,SAAWA,EAAIA,EAAEK,IAClJ,MAAMC,UAAUC,KAAAA,CACd,YAAYC,EAAAA,CACVC,MAAMD,CAAIE,EAAAA,KAAKC,KAAO,uBACvB,CAEE,CAAA,MAACC,EAAI,iBAAkBC,EAAI,mBAAoBC,EAAoB,IAAIC,IAAI,CAAC,MAAO,WAAY,YAAa,WAAA,CAAA,EAAeC,EAAKhB,KAASY,CAACA,CAAIZ,EAAAA,CAAAA,GAAMiB,EAAI,CAACjB,EAAGQ,KAAO,CAAEI,CAACA,CAAAA,EAAIZ,EAAGa,CAACA,CAAAA,EAAIL,IAAMU,EAAI,CAAClB,EAAGQ,IACnM,CAAA,GAAIR,IAAM,KAAM,OAAO,KACvB,GAAWA,OAAAA,GAAK,iBAAmBA,GAAK,UAAW,OAAOA,EAC1D,GAAgB,OAALA,GAAK,SAAU,OAAOmB,OAAOC,MAAMpB,GAAKgB,EAAE,KAAA,EAAShB,IAAM,IAAQgB,EAAE,YAAchB,IAAM,KAASgB,EAAE,WAAehB,EAAAA,EAC5H,GAAWA,OAAAA,GAAK,SAAU,OAAOiB,EAAE,SAAUjB,EAAEqB,SA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ACtBZ,EAAWS,EAAQC,MAAMS,IAC3BnB,EAASoB,SAAW,IAKxBtB,EAAgBC,EAAOC,GACvBS,EAAQC,MAAMW,WACV,IAAA,CACU,MAAAN,EAAmBP,EAAyBC,CAC5CP,EAAAA,EAAaC,EACfF,CAEA,EAAA,GAAA,CAACL,EAAgBM,CAcjB,EAAA,OAAA,KAZIzC,OAAOC,KAAKqD,CAAkBC,EAAAA,OAAS,EACvCZ,EAAkBH,EAAc,CAC5BR,CAACA,CAAAA,EAAY,IACNsB,CAEPf,EAAAA,CAACA,CAAWD,EAAAA,CAAAA,CAAAA,EAGhBK,EAAkBH,EAAc,CAC5BD,CAACA,CAAAA,EAAWD,KAKlB,MAAAuB,EAAcpB,EAAWT,CAE3BS,EAAAA,EAAWT,GADX6B,EACwB,CAAA,GACjBA,KACAP,CAGiB,EAAA,CAAA,GACjBA,GAGXb,EAAWF,CAAAA,EAAYD,EAGvBK,EAAkBH,EAAcC,CAAU,CAAA,EAE9C,CACIqB,SAAAA,MA5CIvC,QAAAwC,MAAM,sBAAuBjC,CA+C7C,CAAA,8BAOO,SAA8BkC,EAO1B,CAAA,OANHA,IACkBjC,wBAAA,CACXA,GAAAA,QAAAA,mBACAiC,CAGJP,GAAAA,CACX","x_google_ignoreList":[0]}
|
package/dist/index.es.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
var m, O = ((m = O || {}).LOCAL = "localStorage", m.SESSION = "sessionStorage", m);
|
|
2
|
+
const S = (e) => typeof e == "string" ? e : e.key;
|
|
3
|
+
class p extends Error {
|
|
4
|
+
constructor(t) {
|
|
5
|
+
super(t), this.name = "StorageSerializeError";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
const d = "__matias_tag__", b = "__matias_value__", N = /* @__PURE__ */ new Set(["NaN", "Infinity", "-Infinity", "undefined"]), g = (e) => ({ [d]: e }), y = (e, t) => ({ [d]: e, [b]: t }), a = (e, t) => {
|
|
9
|
+
if (e === null) return null;
|
|
10
|
+
if (typeof e == "string" || typeof e == "boolean") return e;
|
|
11
|
+
if (typeof e == "number") return Number.isNaN(e) ? g("NaN") : e === 1 / 0 ? g("Infinity") : e === -1 / 0 ? g("-Infinity") : e;
|
|
12
|
+
if (typeof e == "bigint") return y("BigInt", e.toString());
|
|
13
|
+
if (e === void 0) return g("undefined");
|
|
14
|
+
if (typeof e == "function" || typeof e == "symbol") throw new p("unsupported top-level value type: " + typeof e);
|
|
15
|
+
if (e instanceof Date) return y("Date", e.getTime());
|
|
16
|
+
if (e instanceof RegExp) return y("RegExp", { s: e.source, f: e.flags });
|
|
17
|
+
if (e instanceof Map) return y("Map", Array.from(e.entries(), ([r, n]) => [a(r, t), a(n, t)]));
|
|
18
|
+
if (e instanceof Set) return y("Set", Array.from(e.values(), (r) => a(r, t)));
|
|
19
|
+
if (Array.isArray(e)) return e.map((r) => typeof r == "function" || typeof r == "symbol" ? null : a(r, t));
|
|
20
|
+
const o = e;
|
|
21
|
+
if (typeof o.toJSON == "function") return a(o.toJSON(), t);
|
|
22
|
+
if (t.has(e)) throw new p("circular reference detected");
|
|
23
|
+
t.add(e);
|
|
24
|
+
const i = {};
|
|
25
|
+
for (const r of Object.keys(o)) {
|
|
26
|
+
const n = o[r];
|
|
27
|
+
typeof n != "function" && typeof n != "symbol" && (i[r] = a(n, t));
|
|
28
|
+
}
|
|
29
|
+
return t.delete(e), i;
|
|
30
|
+
}, c = (e) => {
|
|
31
|
+
if (e === null || typeof e != "object") return e;
|
|
32
|
+
if (Array.isArray(e)) return e.map(c);
|
|
33
|
+
const t = ((r) => {
|
|
34
|
+
const n = r;
|
|
35
|
+
if (typeof n[d] != "string") return null;
|
|
36
|
+
const s = n[d];
|
|
37
|
+
return N.has(s) || Object.prototype.hasOwnProperty.call(n, b) && ["Date", "Map", "Set", "RegExp", "BigInt"].includes(s) ? s : null;
|
|
38
|
+
})(e);
|
|
39
|
+
if (t === "undefined") return;
|
|
40
|
+
if (t === "NaN") return NaN;
|
|
41
|
+
if (t === "Infinity") return 1 / 0;
|
|
42
|
+
if (t === "-Infinity") return -1 / 0;
|
|
43
|
+
const o = e[b];
|
|
44
|
+
if (t === "Date") return new Date(o);
|
|
45
|
+
if (t === "RegExp") {
|
|
46
|
+
const { s: r, f: n } = o;
|
|
47
|
+
return new RegExp(r, n);
|
|
48
|
+
}
|
|
49
|
+
if (t === "BigInt") try {
|
|
50
|
+
return BigInt(o);
|
|
51
|
+
} catch {
|
|
52
|
+
throw new p(`invalid BigInt payload: ${String(o)}`);
|
|
53
|
+
}
|
|
54
|
+
if (t === "Map") return new Map(o.map(([r, n]) => [c(r), c(n)]));
|
|
55
|
+
if (t === "Set") return new Set(o.map(c));
|
|
56
|
+
const i = {};
|
|
57
|
+
for (const r of Object.keys(e)) {
|
|
58
|
+
const n = c(e[r]);
|
|
59
|
+
r === "__proto__" ? Object.defineProperty(i, r, { value: n, enumerable: !0, writable: !0, configurable: !0 }) : i[r] = n;
|
|
60
|
+
}
|
|
61
|
+
return i;
|
|
62
|
+
}, f = (e, t) => {
|
|
63
|
+
const o = S(e);
|
|
64
|
+
if (t === void 0) return localStorage.removeItem(o), !0;
|
|
65
|
+
try {
|
|
66
|
+
return localStorage.setItem(o, ((i) => JSON.stringify(a(i, /* @__PURE__ */ new Set())))(t)), !0;
|
|
67
|
+
} catch (i) {
|
|
68
|
+
return console.warn(`matias-storage localStorage write ${o} value=${String(t)}:`, i instanceof p ? i.message : i), !1;
|
|
69
|
+
}
|
|
70
|
+
}, w = (e) => {
|
|
71
|
+
const t = localStorage.getItem(S(e));
|
|
72
|
+
if (t === null) return null;
|
|
73
|
+
try {
|
|
74
|
+
return ((o) => c(JSON.parse(o)))(t);
|
|
75
|
+
} catch (o) {
|
|
76
|
+
console.warn(`matias-storage localStorage read ${S(e)}:`, o instanceof p ? o.message : o);
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}, v = "https://www.npmjs.com/package/@matiastang/pinia-persisted-state";
|
|
80
|
+
let u = { key: "pinia-key", customKey: "pinia-custom-key", customFilterKey: (e) => !e.startsWith("$") && !e.startsWith("_") && !e.startsWith("set") };
|
|
81
|
+
const h = (e) => typeof e == "object" && e !== null && !Array.isArray(e), I = (e, t) => {
|
|
82
|
+
const o = u.key, i = w(o);
|
|
83
|
+
if (!h(i)) return void f(o, { [t]: e });
|
|
84
|
+
const r = i[t];
|
|
85
|
+
if (r === void 0) return i[t] = e, void f(o, i);
|
|
86
|
+
for (const n in e) if (Object.prototype.hasOwnProperty.call(e, n)) {
|
|
87
|
+
const s = e[n];
|
|
88
|
+
if (Object.prototype.hasOwnProperty.call(r, n)) {
|
|
89
|
+
const l = r[n];
|
|
90
|
+
s !== l && (e[n] = l);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
i[t] = e, f(o, i);
|
|
94
|
+
}, _ = (e) => {
|
|
95
|
+
const t = e.store, o = Object.keys(t.$state), i = Object.keys(t).filter((n) => u.customFilterKey(n));
|
|
96
|
+
let r = {};
|
|
97
|
+
for (let n = 0; n < i.length; n++) {
|
|
98
|
+
const s = i[n];
|
|
99
|
+
o.includes(s) || (Object.keys(r).length <= 0 ? r = { [s]: t[s] } : r[s] = t[s]);
|
|
100
|
+
}
|
|
101
|
+
return r;
|
|
102
|
+
};
|
|
103
|
+
function j(e) {
|
|
104
|
+
const t = u.key, o = u.customKey, i = e.store.$state, r = e.store.$id;
|
|
105
|
+
r.trim() !== "" ? (I(i, r), e.store.$subscribe(() => {
|
|
106
|
+
const n = _(e), s = w(t);
|
|
107
|
+
if (!h(s)) return void (Object.keys(n).length > 0 ? f(t, { [o]: { ...n }, [r]: i }) : f(t, { [r]: i }));
|
|
108
|
+
const l = s[o];
|
|
109
|
+
s[o] = l ? { ...l, ...n } : { ...n }, s[r] = i, f(t, s);
|
|
110
|
+
}, { detached: !0 })) : console.error("store id 不能为空,详情查看:", v);
|
|
111
|
+
}
|
|
112
|
+
function k(e) {
|
|
113
|
+
return e && (u = { ...u, ...e }), j;
|
|
114
|
+
}
|
|
115
|
+
export {
|
|
116
|
+
k as createPersistedState,
|
|
117
|
+
j as default,
|
|
118
|
+
u as persistedConfig,
|
|
119
|
+
j as piniaPersistedState
|
|
120
|
+
};
|
|
121
|
+
//# sourceMappingURL=index.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../node_modules/.pnpm/matias-storage@0.3.0/node_modules/matias-storage/dist/index.es.js","../src/plugin/index.ts"],"sourcesContent":["var i = ((e) => (e.LOCAL = \"localStorage\", e.SESSION = \"sessionStorage\", e))(i || {});\nconst I = Symbol(\"matias.storageKey\"), L = (e, t = i.LOCAL) => ({ key: e, storageType: t, [I]: void 0 }), s = (e) => typeof e == \"string\" ? e : e.key, m = (e, t) => t !== void 0 ? t : typeof e == \"string\" ? i.LOCAL : e.storageType;\nclass u extends Error {\n constructor(t) {\n super(t), this.name = \"StorageSerializeError\";\n }\n}\nconst y = \"__matias_tag__\", p = \"__matias_value__\", w = /* @__PURE__ */ new Set([\"NaN\", \"Infinity\", \"-Infinity\", \"undefined\"]), S = (e) => ({ [y]: e }), g = (e, t) => ({ [y]: e, [p]: t }), f = (e, t) => {\n if (e === null) return null;\n if (typeof e == \"string\" || typeof e == \"boolean\") return e;\n if (typeof e == \"number\") return Number.isNaN(e) ? S(\"NaN\") : e === 1 / 0 ? S(\"Infinity\") : e === -1 / 0 ? S(\"-Infinity\") : e;\n if (typeof e == \"bigint\") return g(\"BigInt\", e.toString());\n if (e === void 0) return S(\"undefined\");\n if (typeof e == \"function\" || typeof e == \"symbol\") throw new u(\"unsupported top-level value type: \" + typeof e);\n if (e instanceof Date) return g(\"Date\", e.getTime());\n if (e instanceof RegExp) return g(\"RegExp\", { s: e.source, f: e.flags });\n if (e instanceof Map) return g(\"Map\", Array.from(e.entries(), ([n, a]) => [f(n, t), f(a, t)]));\n if (e instanceof Set) return g(\"Set\", Array.from(e.values(), (n) => f(n, t)));\n if (Array.isArray(e)) return e.map((n) => typeof n == \"function\" || typeof n == \"symbol\" ? null : f(n, t));\n const r = e;\n if (typeof r.toJSON == \"function\") return f(r.toJSON(), t);\n if (t.has(e)) throw new u(\"circular reference detected\");\n t.add(e);\n const o = {};\n for (const n of Object.keys(r)) {\n const a = r[n];\n typeof a != \"function\" && typeof a != \"symbol\" && (o[n] = f(a, t));\n }\n return t.delete(e), o;\n}, d = (e) => JSON.stringify(f(e, /* @__PURE__ */ new Set())), c = (e) => {\n if (e === null || typeof e != \"object\") return e;\n if (Array.isArray(e)) return e.map(c);\n const t = ((n) => {\n const a = n;\n if (typeof a[y] != \"string\") return null;\n const l = a[y];\n return w.has(l) || Object.prototype.hasOwnProperty.call(a, p) && [\"Date\", \"Map\", \"Set\", \"RegExp\", \"BigInt\"].includes(l) ? l : null;\n })(e);\n if (t === \"undefined\") return;\n if (t === \"NaN\") return NaN;\n if (t === \"Infinity\") return 1 / 0;\n if (t === \"-Infinity\") return -1 / 0;\n const r = e[p];\n if (t === \"Date\") return new Date(r);\n if (t === \"RegExp\") {\n const { s: n, f: a } = r;\n return new RegExp(n, a);\n }\n if (t === \"BigInt\") try {\n return BigInt(r);\n } catch {\n throw new u(`invalid BigInt payload: ${String(r)}`);\n }\n if (t === \"Map\") return new Map(r.map(([n, a]) => [c(n), c(a)]));\n if (t === \"Set\") return new Set(r.map(c));\n const o = {};\n for (const n of Object.keys(e)) {\n const a = c(e[n]);\n n === \"__proto__\" ? Object.defineProperty(o, n, { value: a, enumerable: !0, writable: !0, configurable: !0 }) : o[n] = a;\n }\n return o;\n}, v = (e) => c(JSON.parse(e)), N = (e, t) => {\n const r = s(e);\n if (t === void 0) return localStorage.removeItem(r), !0;\n try {\n return localStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage localStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, O = (e) => {\n const t = localStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage localStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, b = (e) => {\n localStorage.removeItem(s(e));\n}, _ = () => {\n localStorage.clear();\n}, h = (e, t) => {\n const r = s(e);\n if (t === void 0) return sessionStorage.removeItem(r), !0;\n try {\n return sessionStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage sessionStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, R = (e) => {\n const t = sessionStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage sessionStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, A = (e) => {\n sessionStorage.removeItem(s(e));\n}, E = () => {\n sessionStorage.clear();\n};\nfunction $(e, t, r) {\n const o = m(e, r), n = s(e);\n return o === i.SESSION ? h(n, t) : N(n, t);\n}\nfunction x(e, t, r) {\n const o = typeof t == \"function\" ? t : r, n = m(e, typeof t == \"function\" ? void 0 : t), a = s(e), l = n === i.SESSION ? R(a) : O(a);\n return l === null ? null : o && !o(l) ? (console.warn(`matias-storage storage read ${a}: value failed the type guard, return null instead`), null) : l;\n}\nfunction j(e, t) {\n const r = m(e, t), o = s(e);\n r === i.SESSION ? A(o) : b(o);\n}\nconst B = (e = i.LOCAL) => {\n e === i.SESSION ? E() : _();\n};\nexport {\n i as WebStorageType,\n L as defineStorageKey,\n O as localStorageRead,\n b as localStorageRemove,\n _ as localStorageRemoveAll,\n N as localStorageWrite,\n s as resolveKeyString,\n m as resolveStorageType,\n R as sessionStorageRead,\n A as sessionStorageRemove,\n E as sessionStorageRemoveAll,\n h as sessionStorageWrite,\n x as storageRead,\n j as storageRemove,\n B as storageRemoveAll,\n $ as storageWrite\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * @Author: matiastang\n * @Date: 2022-02-09 17:17:20\n * @LastEditors: matiastang\n * @LastEditTime: 2024-07-16 18:28:21\n * @FilePath: /pinia-persisted-state/src/plugin/index.ts\n * @Description: pinia状态本地存储插件\n */\nimport type { PiniaPluginContext, PiniaCustomStateProperties, StateTree } from 'pinia'\nimport { localStorageRead, localStorageWrite } from 'matias-storage'\n\nconst NPMLINK = 'https://www.npmjs.com/package/@matiastang/pinia-persisted-state'\nconst PINIA_STORAGE_KEY = 'pinia-key'\nconst PINIA_STORAGE_CUSTOM_KEY = 'pinia-custom-key'\n\n/**\n * 需要对MapStoresCustomization类型进行扩展,不然将报错\n * Property 'suffix' does not exist on type 'MapStoresCustomization'.\n * [Id in `${Ids}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}`]: () => Store<Id extends `${infer RealId}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}` ? RealId : string, State, Getters, Actions>;\n */\ndeclare module 'pinia' {\n export interface MapStoresCustomization {\n suffix: string\n }\n}\n\n/**\n * 状态持久化config类型\n */\ninterface PersistedStateConfig {\n /**\n * 保存pinia的key\n */\n key?: string\n /**\n * 保存pinia custom properties的key\n */\n customKey?: string\n /**\n * 获取custom properties key 的过滤函数\n */\n customFilterKey?: (key: string) => boolean\n}\n\n/**\n * custom properties 类型\n */\ntype CustomPropertiesType = {\n [key: string]: StateTree & PiniaCustomStateProperties<StateTree>\n}\n\n/**\n * 状态持久化config\n */\nexport let persistedConfig: PersistedStateConfig = {\n key: PINIA_STORAGE_KEY,\n customKey: PINIA_STORAGE_CUSTOM_KEY,\n customFilterKey: (key: string) => {\n return !key.startsWith('$') && !key.startsWith('_') && !key.startsWith('set')\n },\n}\n\n/**\n * 判断本地数据是否为可用的记录对象(非null的非数组对象)\n * @param data\n * @returns\n */\nconst _isRecordObject = (\n data: unknown\n): data is StateTree & PiniaCustomStateProperties<StateTree> => {\n return typeof data === 'object' && data !== null && !Array.isArray(data)\n}\n\n/**\n * 本地存储数据差异化检测,更新\n * @param state\n * @param key\n * @returns\n */\nconst _localStateDiff = (\n state: StateTree & PiniaCustomStateProperties<StateTree>,\n stateKey: string\n) => {\n const persistedKey = persistedConfig.key\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或数据损坏/结构非法,均以初始值重建)\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n return\n }\n const localNameState = localState[stateKey]\n if (localNameState === undefined) {\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n return\n }\n // 差异查找更新\n for (const key in state) {\n if (Object.prototype.hasOwnProperty.call(state, key)) {\n const element = state[key]\n if (Object.prototype.hasOwnProperty.call(localNameState, key)) {\n const localElement = localNameState[key]\n if (element !== localElement) {\n state[key] = localElement\n }\n }\n }\n }\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n}\n\n/**\n * 获取custom properties\n * @param context\n * @returns\n */\nconst _contextCustomProperties = (context: PiniaPluginContext) => {\n const store = context.store\n const stateKeys = Object.keys(store.$state)\n const customKeys = Object.keys(store).filter((key) => {\n return persistedConfig.customFilterKey(key)\n })\n let customProperties = {} as CustomPropertiesType\n for (let i = 0; i < customKeys.length; i++) {\n const item = customKeys[i]\n if (!stateKeys.includes(item)) {\n if (Object.keys(customProperties).length <= 0) {\n customProperties = {\n [item]: store[item],\n }\n } else {\n customProperties[item] = store[item]\n }\n }\n }\n return customProperties\n}\n\n/**\n * pinia state 本地存储\n * @param context pinia context\n */\nexport function piniaPersistedState(context: PiniaPluginContext) {\n /**\n * FIXME: - 不能检测到customProperties和stateProperties,在调用customProperties和stateProperties之前\n */\n const persistedKey = persistedConfig.key\n const customKey = persistedConfig.customKey\n const state = context.store.$state\n const stateKey = context.store.$id\n if (stateKey.trim() === '') {\n console.error('store id 不能为空,详情查看:', NPMLINK)\n return\n }\n // 初始化检测更新\n _localStateDiff(state, stateKey)\n context.store.$subscribe(\n () => {\n const customProperties = _contextCustomProperties(context)\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或结构非法时重建)\n if (Object.keys(customProperties).length > 0) {\n localStorageWrite(persistedKey, {\n [customKey]: {\n ...customProperties,\n },\n [stateKey]: state,\n })\n } else {\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n }\n return\n }\n const localCustom = localState[customKey]\n if (localCustom) {\n localState[customKey] = {\n ...localCustom,\n ...customProperties,\n }\n } else {\n localState[customKey] = {\n ...customProperties,\n }\n }\n localState[stateKey] = state\n // 直接更新存储状态\n // FIXME: - 非状态更新也会调用,可能会有性能问题\n localStorageWrite(persistedKey, localState)\n },\n {\n detached: true,\n }\n )\n}\n\n/**\n * 带配置创建pinia state 本地存储\n * @param config\n * @returns\n */\nexport function createPersistedState(config?: PersistedStateConfig) {\n if (config) {\n persistedConfig = {\n ...persistedConfig,\n ...config,\n }\n }\n return piniaPersistedState\n}\n\nexport default piniaPersistedState\n"],"names":["e","i","LOCAL","SESSION","s","key","u","Error","t","super","this","name","y","p","w","Set","S","g","f","Number","isNaN","toString","Date","getTime","RegExp","source","flags","Map","Array","from","entries","n","a","values","isArray","map","r","toJSON","has","add","o","Object","keys","delete","c","l","prototype","hasOwnProperty","call","includes","NaN","BigInt","String","defineProperty","value","enumerable","writable","configurable","N","localStorage","removeItem","setItem","JSON","stringify","console","warn","message","O","getItem","parse","v","NPMLINK","persistedConfig","customKey","customFilterKey","startsWith","_isRecordObject","data","_localStateDiff","state","stateKey","persistedKey","localState","localStorageRead","localStorageWrite","localNameState","element","localElement","_contextCustomProperties","context","store","stateKeys","$state","customKeys","filter","customProperties","length","item","piniaPersistedState","$id","trim","$subscribe","localCustom","detached","error","createPersistedState","config"],"mappings":"AAAA,IAAUA,GAANC,MAAMD,IAAmEC,KAAK,CAAE,GAAjEC,QAAQ,gBAAgBF,EAAEG,UAAU,kBAAkBH;AACpE,MAAqGI,IAAKJ,CAAAA,MAAkB,OAALA,KAAK,WAAWA,IAAIA,EAAEK;AAClJ,MA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AkBH,GAAc,EAC5BD,CAACA,IAAWD,EAKlB,CAAA;AAAA,UAAAuB,IAAcpB,EAAWT,CAAAA;AAE3BS,MAAWT,CADX6B,IAAAA,IACwB,KACjBA,GACAP,GAAAA,EAAAA,IAGiB,KACjBA,EAGXb,GAAAA,EAAWF,CAAYD,IAAAA,GAGvBK,EAAkBH,GAAcC;EAAU,GAE9C,EACIqB,aA5CIvC,CAAAA,KAAAA,QAAAwC,MAAM,uBAAuBjC,CAAAA;AA+C7C;AAOO,SAASkC,EAAqBC;AAO1B,SANHA,MACkBlC,IAAA,EACXA,GAAAA,GAAAA,GACAkC,MAGJR;AACX;","x_google_ignoreList":[0]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var piniaPersistedState=function(a){"use strict";var m,v=((m=v||{}).LOCAL="localStorage",m.SESSION="sessionStorage",m);const S=e=>typeof e=="string"?e:e.key;class l extends Error{constructor(t){super(t),this.name="StorageSerializeError"}}const g="__matias_tag__",b="__matias_value__",_=new Set(["NaN","Infinity","-Infinity","undefined"]),d=e=>({[g]:e}),p=(e,t)=>({[g]:e,[b]:t}),f=(e,t)=>{if(e===null)return null;if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isNaN(e)?d("NaN"):e===1/0?d("Infinity"):e===-1/0?d("-Infinity"):e;if(typeof e=="bigint")return p("BigInt",e.toString());if(e===void 0)return d("undefined");if(typeof e=="function"||typeof e=="symbol")throw new l("unsupported top-level value type: "+typeof e);if(e instanceof Date)return p("Date",e.getTime());if(e instanceof RegExp)return p("RegExp",{s:e.source,f:e.flags});if(e instanceof Map)return p("Map",Array.from(e.entries(),([r,n])=>[f(r,t),f(n,t)]));if(e instanceof Set)return p("Set",Array.from(e.values(),r=>f(r,t)));if(Array.isArray(e))return e.map(r=>typeof r=="function"||typeof r=="symbol"?null:f(r,t));const o=e;if(typeof o.toJSON=="function")return f(o.toJSON(),t);if(t.has(e))throw new l("circular reference detected");t.add(e);const i={};for(const r of Object.keys(o)){const n=o[r];typeof n!="function"&&typeof n!="symbol"&&(i[r]=f(n,t))}return t.delete(e),i},c=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(c);const t=(r=>{const n=r;if(typeof n[g]!="string")return null;const s=n[g];return _.has(s)||Object.prototype.hasOwnProperty.call(n,b)&&["Date","Map","Set","RegExp","BigInt"].includes(s)?s:null})(e);if(t==="undefined")return;if(t==="NaN")return NaN;if(t==="Infinity")return 1/0;if(t==="-Infinity")return-1/0;const o=e[b];if(t==="Date")return new Date(o);if(t==="RegExp"){const{s:r,f:n}=o;return new RegExp(r,n)}if(t==="BigInt")try{return BigInt(o)}catch{throw new l(`invalid BigInt payload: ${String(o)}`)}if(t==="Map")return new Map(o.map(([r,n])=>[c(r),c(n)]));if(t==="Set")return new Set(o.map(c));const i={};for(const r of Object.keys(e)){const n=c(e[r]);r==="__proto__"?Object.defineProperty(i,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):i[r]=n}return i},u=(e,t)=>{const o=S(e);if(t===void 0)return localStorage.removeItem(o),!0;try{return localStorage.setItem(o,(i=>JSON.stringify(f(i,new Set)))(t)),!0}catch(i){return console.warn(`matias-storage localStorage write ${o} value=${String(t)}:`,i instanceof l?i.message:i),!1}},h=e=>{const t=localStorage.getItem(S(e));if(t===null)return null;try{return(o=>c(JSON.parse(o)))(t)}catch(o){console.warn(`matias-storage localStorage read ${S(e)}:`,o instanceof l?o.message:o)}return null},N="https://www.npmjs.com/package/@matiastang/pinia-persisted-state";a.persistedConfig={key:"pinia-key",customKey:"pinia-custom-key",customFilterKey:e=>!e.startsWith("$")&&!e.startsWith("_")&&!e.startsWith("set")};const O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=(e,t)=>{const o=a.persistedConfig.key,i=h(o);if(!O(i))return void u(o,{[t]:e});const r=i[t];if(r===void 0)return i[t]=e,void u(o,i);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];if(Object.prototype.hasOwnProperty.call(r,n)){const y=r[n];s!==y&&(e[n]=y)}}i[t]=e,u(o,i)},j=e=>{const t=e.store,o=Object.keys(t.$state),i=Object.keys(t).filter(n=>a.persistedConfig.customFilterKey(n));let r={};for(let n=0;n<i.length;n++){const s=i[n];o.includes(s)||(Object.keys(r).length<=0?r={[s]:t[s]}:r[s]=t[s])}return r};function w(e){const t=a.persistedConfig.key,o=a.persistedConfig.customKey,i=e.store.$state,r=e.store.$id;r.trim()!==""?(I(i,r),e.store.$subscribe(()=>{const n=j(e),s=h(t);if(!O(s))return void(Object.keys(n).length>0?u(t,{[o]:{...n},[r]:i}):u(t,{[r]:i}));const y=s[o];s[o]=y?{...y,...n}:{...n},s[r]=i,u(t,s)},{detached:!0})):console.error("store id 不能为空,详情查看:",N)}return a.createPersistedState=function(e){return e&&(a.persistedConfig={...a.persistedConfig,...e}),w},a.default=w,a.piniaPersistedState=w,Object.defineProperties(a,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),a}({});
|
|
2
|
+
//# sourceMappingURL=index.iife.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.iife.js","sources":["../node_modules/.pnpm/matias-storage@0.3.0/node_modules/matias-storage/dist/index.es.js","../src/plugin/index.ts"],"sourcesContent":["var i = ((e) => (e.LOCAL = \"localStorage\", e.SESSION = \"sessionStorage\", e))(i || {});\nconst I = Symbol(\"matias.storageKey\"), L = (e, t = i.LOCAL) => ({ key: e, storageType: t, [I]: void 0 }), s = (e) => typeof e == \"string\" ? e : e.key, m = (e, t) => t !== void 0 ? t : typeof e == \"string\" ? i.LOCAL : e.storageType;\nclass u extends Error {\n constructor(t) {\n super(t), this.name = \"StorageSerializeError\";\n }\n}\nconst y = \"__matias_tag__\", p = \"__matias_value__\", w = /* @__PURE__ */ new Set([\"NaN\", \"Infinity\", \"-Infinity\", \"undefined\"]), S = (e) => ({ [y]: e }), g = (e, t) => ({ [y]: e, [p]: t }), f = (e, t) => {\n if (e === null) return null;\n if (typeof e == \"string\" || typeof e == \"boolean\") return e;\n if (typeof e == \"number\") return Number.isNaN(e) ? S(\"NaN\") : e === 1 / 0 ? S(\"Infinity\") : e === -1 / 0 ? S(\"-Infinity\") : e;\n if (typeof e == \"bigint\") return g(\"BigInt\", e.toString());\n if (e === void 0) return S(\"undefined\");\n if (typeof e == \"function\" || typeof e == \"symbol\") throw new u(\"unsupported top-level value type: \" + typeof e);\n if (e instanceof Date) return g(\"Date\", e.getTime());\n if (e instanceof RegExp) return g(\"RegExp\", { s: e.source, f: e.flags });\n if (e instanceof Map) return g(\"Map\", Array.from(e.entries(), ([n, a]) => [f(n, t), f(a, t)]));\n if (e instanceof Set) return g(\"Set\", Array.from(e.values(), (n) => f(n, t)));\n if (Array.isArray(e)) return e.map((n) => typeof n == \"function\" || typeof n == \"symbol\" ? null : f(n, t));\n const r = e;\n if (typeof r.toJSON == \"function\") return f(r.toJSON(), t);\n if (t.has(e)) throw new u(\"circular reference detected\");\n t.add(e);\n const o = {};\n for (const n of Object.keys(r)) {\n const a = r[n];\n typeof a != \"function\" && typeof a != \"symbol\" && (o[n] = f(a, t));\n }\n return t.delete(e), o;\n}, d = (e) => JSON.stringify(f(e, /* @__PURE__ */ new Set())), c = (e) => {\n if (e === null || typeof e != \"object\") return e;\n if (Array.isArray(e)) return e.map(c);\n const t = ((n) => {\n const a = n;\n if (typeof a[y] != \"string\") return null;\n const l = a[y];\n return w.has(l) || Object.prototype.hasOwnProperty.call(a, p) && [\"Date\", \"Map\", \"Set\", \"RegExp\", \"BigInt\"].includes(l) ? l : null;\n })(e);\n if (t === \"undefined\") return;\n if (t === \"NaN\") return NaN;\n if (t === \"Infinity\") return 1 / 0;\n if (t === \"-Infinity\") return -1 / 0;\n const r = e[p];\n if (t === \"Date\") return new Date(r);\n if (t === \"RegExp\") {\n const { s: n, f: a } = r;\n return new RegExp(n, a);\n }\n if (t === \"BigInt\") try {\n return BigInt(r);\n } catch {\n throw new u(`invalid BigInt payload: ${String(r)}`);\n }\n if (t === \"Map\") return new Map(r.map(([n, a]) => [c(n), c(a)]));\n if (t === \"Set\") return new Set(r.map(c));\n const o = {};\n for (const n of Object.keys(e)) {\n const a = c(e[n]);\n n === \"__proto__\" ? Object.defineProperty(o, n, { value: a, enumerable: !0, writable: !0, configurable: !0 }) : o[n] = a;\n }\n return o;\n}, v = (e) => c(JSON.parse(e)), N = (e, t) => {\n const r = s(e);\n if (t === void 0) return localStorage.removeItem(r), !0;\n try {\n return localStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage localStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, O = (e) => {\n const t = localStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage localStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, b = (e) => {\n localStorage.removeItem(s(e));\n}, _ = () => {\n localStorage.clear();\n}, h = (e, t) => {\n const r = s(e);\n if (t === void 0) return sessionStorage.removeItem(r), !0;\n try {\n return sessionStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage sessionStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, R = (e) => {\n const t = sessionStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage sessionStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, A = (e) => {\n sessionStorage.removeItem(s(e));\n}, E = () => {\n sessionStorage.clear();\n};\nfunction $(e, t, r) {\n const o = m(e, r), n = s(e);\n return o === i.SESSION ? h(n, t) : N(n, t);\n}\nfunction x(e, t, r) {\n const o = typeof t == \"function\" ? t : r, n = m(e, typeof t == \"function\" ? void 0 : t), a = s(e), l = n === i.SESSION ? R(a) : O(a);\n return l === null ? null : o && !o(l) ? (console.warn(`matias-storage storage read ${a}: value failed the type guard, return null instead`), null) : l;\n}\nfunction j(e, t) {\n const r = m(e, t), o = s(e);\n r === i.SESSION ? A(o) : b(o);\n}\nconst B = (e = i.LOCAL) => {\n e === i.SESSION ? E() : _();\n};\nexport {\n i as WebStorageType,\n L as defineStorageKey,\n O as localStorageRead,\n b as localStorageRemove,\n _ as localStorageRemoveAll,\n N as localStorageWrite,\n s as resolveKeyString,\n m as resolveStorageType,\n R as sessionStorageRead,\n A as sessionStorageRemove,\n E as sessionStorageRemoveAll,\n h as sessionStorageWrite,\n x as storageRead,\n j as storageRemove,\n B as storageRemoveAll,\n $ as storageWrite\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * @Author: matiastang\n * @Date: 2022-02-09 17:17:20\n * @LastEditors: matiastang\n * @LastEditTime: 2024-07-16 18:28:21\n * @FilePath: /pinia-persisted-state/src/plugin/index.ts\n * @Description: pinia状态本地存储插件\n */\nimport type { PiniaPluginContext, PiniaCustomStateProperties, StateTree } from 'pinia'\nimport { localStorageRead, localStorageWrite } from 'matias-storage'\n\nconst NPMLINK = 'https://www.npmjs.com/package/@matiastang/pinia-persisted-state'\nconst PINIA_STORAGE_KEY = 'pinia-key'\nconst PINIA_STORAGE_CUSTOM_KEY = 'pinia-custom-key'\n\n/**\n * 需要对MapStoresCustomization类型进行扩展,不然将报错\n * Property 'suffix' does not exist on type 'MapStoresCustomization'.\n * [Id in `${Ids}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}`]: () => Store<Id extends `${infer RealId}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}` ? RealId : string, State, Getters, Actions>;\n */\ndeclare module 'pinia' {\n export interface MapStoresCustomization {\n suffix: string\n }\n}\n\n/**\n * 状态持久化config类型\n */\ninterface PersistedStateConfig {\n /**\n * 保存pinia的key\n */\n key?: string\n /**\n * 保存pinia custom properties的key\n */\n customKey?: string\n /**\n * 获取custom properties key 的过滤函数\n */\n customFilterKey?: (key: string) => boolean\n}\n\n/**\n * custom properties 类型\n */\ntype CustomPropertiesType = {\n [key: string]: StateTree & PiniaCustomStateProperties<StateTree>\n}\n\n/**\n * 状态持久化config\n */\nexport let persistedConfig: PersistedStateConfig = {\n key: PINIA_STORAGE_KEY,\n customKey: PINIA_STORAGE_CUSTOM_KEY,\n customFilterKey: (key: string) => {\n return !key.startsWith('$') && !key.startsWith('_') && !key.startsWith('set')\n },\n}\n\n/**\n * 判断本地数据是否为可用的记录对象(非null的非数组对象)\n * @param data\n * @returns\n */\nconst _isRecordObject = (\n data: unknown\n): data is StateTree & PiniaCustomStateProperties<StateTree> => {\n return typeof data === 'object' && data !== null && !Array.isArray(data)\n}\n\n/**\n * 本地存储数据差异化检测,更新\n * @param state\n * @param key\n * @returns\n */\nconst _localStateDiff = (\n state: StateTree & PiniaCustomStateProperties<StateTree>,\n stateKey: string\n) => {\n const persistedKey = persistedConfig.key\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或数据损坏/结构非法,均以初始值重建)\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n return\n }\n const localNameState = localState[stateKey]\n if (localNameState === undefined) {\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n return\n }\n // 差异查找更新\n for (const key in state) {\n if (Object.prototype.hasOwnProperty.call(state, key)) {\n const element = state[key]\n if (Object.prototype.hasOwnProperty.call(localNameState, key)) {\n const localElement = localNameState[key]\n if (element !== localElement) {\n state[key] = localElement\n }\n }\n }\n }\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n}\n\n/**\n * 获取custom properties\n * @param context\n * @returns\n */\nconst _contextCustomProperties = (context: PiniaPluginContext) => {\n const store = context.store\n const stateKeys = Object.keys(store.$state)\n const customKeys = Object.keys(store).filter((key) => {\n return persistedConfig.customFilterKey(key)\n })\n let customProperties = {} as CustomPropertiesType\n for (let i = 0; i < customKeys.length; i++) {\n const item = customKeys[i]\n if (!stateKeys.includes(item)) {\n if (Object.keys(customProperties).length <= 0) {\n customProperties = {\n [item]: store[item],\n }\n } else {\n customProperties[item] = store[item]\n }\n }\n }\n return customProperties\n}\n\n/**\n * pinia state 本地存储\n * @param context pinia context\n */\nexport function piniaPersistedState(context: PiniaPluginContext) {\n /**\n * FIXME: - 不能检测到customProperties和stateProperties,在调用customProperties和stateProperties之前\n */\n const persistedKey = persistedConfig.key\n const customKey = persistedConfig.customKey\n const state = context.store.$state\n const stateKey = context.store.$id\n if (stateKey.trim() === '') {\n console.error('store id 不能为空,详情查看:', NPMLINK)\n return\n }\n // 初始化检测更新\n _localStateDiff(state, stateKey)\n context.store.$subscribe(\n () => {\n const customProperties = _contextCustomProperties(context)\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或结构非法时重建)\n if (Object.keys(customProperties).length > 0) {\n localStorageWrite(persistedKey, {\n [customKey]: {\n ...customProperties,\n },\n [stateKey]: state,\n })\n } else {\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n }\n return\n }\n const localCustom = localState[customKey]\n if (localCustom) {\n localState[customKey] = {\n ...localCustom,\n ...customProperties,\n }\n } else {\n localState[customKey] = {\n ...customProperties,\n }\n }\n localState[stateKey] = state\n // 直接更新存储状态\n // FIXME: - 非状态更新也会调用,可能会有性能问题\n localStorageWrite(persistedKey, localState)\n },\n {\n detached: true,\n }\n )\n}\n\n/**\n * 带配置创建pinia state 本地存储\n * @param config\n * @returns\n */\nexport function createPersistedState(config?: PersistedStateConfig) {\n if (config) {\n persistedConfig = {\n ...persistedConfig,\n ...config,\n }\n }\n return piniaPersistedState\n}\n\nexport default piniaPersistedState\n"],"names":["e","i","LOCAL","SESSION","s","key","u","Error","t","super","this","name","y","p","w","Set","S","g","f","Number","isNaN","toString","Date","getTime","RegExp","source","flags","Map","Array","from","entries","n","a","values","isArray","map","r","toJSON","has","add","o","Object","keys","delete","c","l","prototype","hasOwnProperty","call","includes","NaN","BigInt","String","defineProperty","value","enumerable","writable","configurable","N","localStorage","removeItem","setItem","JSON","stringify","d","console","warn","message","O","getItem","parse","v","NPMLINK","persistedConfig","customKey","customFilterKey","startsWith","_isRecordObject","data","_localStateDiff","state","stateKey","persistedKey","localState","localStorageRead","localStorageWrite","localNameState","element","localElement","_contextCustomProperties","context","store","stateKeys","$state","customKeys","filter","customProperties","length","item","piniaPersistedState","$id","trim","$subscribe","localCustom","detached","error","config"],"mappings":"iDAAA,IAAUA,EAANC,IAAMD,EAAmEC,GAAK,CAAE,GAAjEC,MAAQ,eAAgBF,EAAEG,QAAU,iBAAkBH,GACpE,MAAqGI,EAAKJ,GAAkB,OAALA,GAAK,SAAWA,EAAIA,EAAEK,IAClJ,MAAMC,UAAUC,KACd,CAAA,YAAYC,EACVC,CAAAA,MAAMD,CAAIE,EAAAA,KAAKC,KAAO,uBACvB,EAEE,MAACC,EAAI,iBAAkBC,EAAI,mBAAoBC,EAAoB,IAAIC,IAAI,CAAC,MAAO,WAAY,YAAa,cAAeC,EAAKhB,KAASY,CAACA,CAAAA,EAAIZ,IAAMiB,EAAI,CAACjB,EAAGQ,KAAO,CAAEI,CAACA,CAAIZ,EAAAA,EAAGa,CAACA,CAAIL,EAAAA,CAAAA,GAAMU,EAAI,CAAClB,EAAGQ,IACnM,CAAA,GAAIR,IAAM,KAAM,OAAO,KACvB,UAAWA,GAAK,UAAwB,OAALA,GAAK,UAAW,OAAOA,EAC1D,GAAgB,OAALA,GAAK,SAAU,OAAOmB,OAAOC,MAAMpB,CAAAA,EAAKgB,EAAE,KAAShB,EAAAA,IAAM,IAAQgB,EAAE,UAAA,EAAchB,IAAM,KAASgB,EAAE,WAAA,EAAehB,EAC5H,GAAgB,OAALA,GAAK,SAAU,OAAOiB,EAAE,SAAUjB,EAAEqB,SAAAA,CAAAA,EAC/C,GAAIrB,WAAc,OAAOgB,EAAE,WAAA,EAC3B,GAAWhB,OAAAA,GAAK,mBAAqBA,GAAK,S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AME,OACtBZ,EAAWS,EAAQC,MAAMS,IAC3BnB,EAASoB,KAKbtB,IALwB,IAKxBA,EAAgBC,EAAOC,CAAAA,EACvBS,EAAQC,MAAMW,WACV,KACU,MAAAN,EAAmBP,EAAyBC,CAC5CP,EAAAA,EAAaC,EACfF,CAEA,EAAA,GAAA,CAACL,EAAgBM,CAcjB,EAAA,OAAA,KAZI1C,OAAOC,KAAKsD,CAAAA,EAAkBC,OAAS,EACvCZ,EAAkBH,EAAc,CAC5BR,CAACA,CAAAA,EAAY,IACNsB,CAEPf,EAAAA,CAACA,GAAWD,CAGhBK,CAAAA,EAAAA,EAAkBH,EAAc,CAC5BD,CAACA,CAAWD,EAAAA,CAAAA,CAAAA,GAKlB,MAAAuB,EAAcpB,EAAWT,CAE3BS,EAAAA,EAAWT,GADX6B,EACwB,CAAA,GACjBA,KACAP,CAGiB,EAAA,CAAA,GACjBA,CAGXb,EAAAA,EAAWF,CAAYD,EAAAA,EAGvBK,EAAkBH,EAAcC,CAAAA,CAAU,EAE9C,CACIqB,SAAAA,MA5CIvC,QAAAwC,MAAM,sBAAuBjC,CAAAA,CA+C7C,+BAOO,SAA8BkC,GAO1B,OANHA,IACkBjC,kBAAA,CAAA,GACXA,EAAAA,gBAAAA,GACAiC,CAGJP,GAAAA,CACX","x_google_ignoreList":[0]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(a,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):f((a=typeof globalThis<"u"?globalThis:a||self).piniaPersistedState={})})(this,function(a){"use strict";var f,v=((f=v||{}).LOCAL="localStorage",f.SESSION="sessionStorage",f);const S=t=>typeof t=="string"?t:t.key;class p extends Error{constructor(e){super(e),this.name="StorageSerializeError"}}const g="__matias_tag__",b="__matias_value__",_=new Set(["NaN","Infinity","-Infinity","undefined"]),m=t=>({[g]:t}),y=(t,e)=>({[g]:t,[b]:e}),c=(t,e)=>{if(t===null)return null;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isNaN(t)?m("NaN"):t===1/0?m("Infinity"):t===-1/0?m("-Infinity"):t;if(typeof t=="bigint")return y("BigInt",t.toString());if(t===void 0)return m("undefined");if(typeof t=="function"||typeof t=="symbol")throw new p("unsupported top-level value type: "+typeof t);if(t instanceof Date)return y("Date",t.getTime());if(t instanceof RegExp)return y("RegExp",{s:t.source,f:t.flags});if(t instanceof Map)return y("Map",Array.from(t.entries(),([n,r])=>[c(n,e),c(r,e)]));if(t instanceof Set)return y("Set",Array.from(t.values(),n=>c(n,e)));if(Array.isArray(t))return t.map(n=>typeof n=="function"||typeof n=="symbol"?null:c(n,e));const o=t;if(typeof o.toJSON=="function")return c(o.toJSON(),e);if(e.has(t))throw new p("circular reference detected");e.add(t);const i={};for(const n of Object.keys(o)){const r=o[n];typeof r!="function"&&typeof r!="symbol"&&(i[n]=c(r,e))}return e.delete(t),i},u=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(u);const e=(n=>{const r=n;if(typeof r[g]!="string")return null;const s=r[g];return _.has(s)||Object.prototype.hasOwnProperty.call(r,b)&&["Date","Map","Set","RegExp","BigInt"].includes(s)?s:null})(t);if(e==="undefined")return;if(e==="NaN")return NaN;if(e==="Infinity")return 1/0;if(e==="-Infinity")return-1/0;const o=t[b];if(e==="Date")return new Date(o);if(e==="RegExp"){const{s:n,f:r}=o;return new RegExp(n,r)}if(e==="BigInt")try{return BigInt(o)}catch{throw new p(`invalid BigInt payload: ${String(o)}`)}if(e==="Map")return new Map(o.map(([n,r])=>[u(n),u(r)]));if(e==="Set")return new Set(o.map(u));const i={};for(const n of Object.keys(t)){const r=u(t[n]);n==="__proto__"?Object.defineProperty(i,n,{value:r,enumerable:!0,writable:!0,configurable:!0}):i[n]=r}return i},l=(t,e)=>{const o=S(t);if(e===void 0)return localStorage.removeItem(o),!0;try{return localStorage.setItem(o,(i=>JSON.stringify(c(i,new Set)))(e)),!0}catch(i){return console.warn(`matias-storage localStorage write ${o} value=${String(e)}:`,i instanceof p?i.message:i),!1}},w=t=>{const e=localStorage.getItem(S(t));if(e===null)return null;try{return(o=>u(JSON.parse(o)))(e)}catch(o){console.warn(`matias-storage localStorage read ${S(t)}:`,o instanceof p?o.message:o)}return null},N="https://www.npmjs.com/package/@matiastang/pinia-persisted-state";a.persistedConfig={key:"pinia-key",customKey:"pinia-custom-key",customFilterKey:t=>!t.startsWith("$")&&!t.startsWith("_")&&!t.startsWith("set")};const O=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),j=(t,e)=>{const o=a.persistedConfig.key,i=w(o);if(!O(i))return void l(o,{[e]:t});const n=i[e];if(n===void 0)return i[e]=t,void l(o,i);for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(Object.prototype.hasOwnProperty.call(n,r)){const d=n[r];s!==d&&(t[r]=d)}}i[e]=t,l(o,i)},I=t=>{const e=t.store,o=Object.keys(e.$state),i=Object.keys(e).filter(r=>a.persistedConfig.customFilterKey(r));let n={};for(let r=0;r<i.length;r++){const s=i[r];o.includes(s)||(Object.keys(n).length<=0?n={[s]:e[s]}:n[s]=e[s])}return n};function h(t){const e=a.persistedConfig.key,o=a.persistedConfig.customKey,i=t.store.$state,n=t.store.$id;n.trim()!==""?(j(i,n),t.store.$subscribe(()=>{const r=I(t),s=w(e);if(!O(s))return void(Object.keys(r).length>0?l(e,{[o]:{...r},[n]:i}):l(e,{[n]:i}));const d=s[o];s[o]=d?{...d,...r}:{...r},s[n]=i,l(e,s)},{detached:!0})):console.error("store id 不能为空,详情查看:",N)}a.createPersistedState=function(t){return t&&(a.persistedConfig={...a.persistedConfig,...t}),h},a.default=h,a.piniaPersistedState=h,Object.defineProperties(a,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
2
|
+
//# sourceMappingURL=index.umd.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../node_modules/.pnpm/matias-storage@0.3.0/node_modules/matias-storage/dist/index.es.js","../src/plugin/index.ts"],"sourcesContent":["var i = ((e) => (e.LOCAL = \"localStorage\", e.SESSION = \"sessionStorage\", e))(i || {});\nconst I = Symbol(\"matias.storageKey\"), L = (e, t = i.LOCAL) => ({ key: e, storageType: t, [I]: void 0 }), s = (e) => typeof e == \"string\" ? e : e.key, m = (e, t) => t !== void 0 ? t : typeof e == \"string\" ? i.LOCAL : e.storageType;\nclass u extends Error {\n constructor(t) {\n super(t), this.name = \"StorageSerializeError\";\n }\n}\nconst y = \"__matias_tag__\", p = \"__matias_value__\", w = /* @__PURE__ */ new Set([\"NaN\", \"Infinity\", \"-Infinity\", \"undefined\"]), S = (e) => ({ [y]: e }), g = (e, t) => ({ [y]: e, [p]: t }), f = (e, t) => {\n if (e === null) return null;\n if (typeof e == \"string\" || typeof e == \"boolean\") return e;\n if (typeof e == \"number\") return Number.isNaN(e) ? S(\"NaN\") : e === 1 / 0 ? S(\"Infinity\") : e === -1 / 0 ? S(\"-Infinity\") : e;\n if (typeof e == \"bigint\") return g(\"BigInt\", e.toString());\n if (e === void 0) return S(\"undefined\");\n if (typeof e == \"function\" || typeof e == \"symbol\") throw new u(\"unsupported top-level value type: \" + typeof e);\n if (e instanceof Date) return g(\"Date\", e.getTime());\n if (e instanceof RegExp) return g(\"RegExp\", { s: e.source, f: e.flags });\n if (e instanceof Map) return g(\"Map\", Array.from(e.entries(), ([n, a]) => [f(n, t), f(a, t)]));\n if (e instanceof Set) return g(\"Set\", Array.from(e.values(), (n) => f(n, t)));\n if (Array.isArray(e)) return e.map((n) => typeof n == \"function\" || typeof n == \"symbol\" ? null : f(n, t));\n const r = e;\n if (typeof r.toJSON == \"function\") return f(r.toJSON(), t);\n if (t.has(e)) throw new u(\"circular reference detected\");\n t.add(e);\n const o = {};\n for (const n of Object.keys(r)) {\n const a = r[n];\n typeof a != \"function\" && typeof a != \"symbol\" && (o[n] = f(a, t));\n }\n return t.delete(e), o;\n}, d = (e) => JSON.stringify(f(e, /* @__PURE__ */ new Set())), c = (e) => {\n if (e === null || typeof e != \"object\") return e;\n if (Array.isArray(e)) return e.map(c);\n const t = ((n) => {\n const a = n;\n if (typeof a[y] != \"string\") return null;\n const l = a[y];\n return w.has(l) || Object.prototype.hasOwnProperty.call(a, p) && [\"Date\", \"Map\", \"Set\", \"RegExp\", \"BigInt\"].includes(l) ? l : null;\n })(e);\n if (t === \"undefined\") return;\n if (t === \"NaN\") return NaN;\n if (t === \"Infinity\") return 1 / 0;\n if (t === \"-Infinity\") return -1 / 0;\n const r = e[p];\n if (t === \"Date\") return new Date(r);\n if (t === \"RegExp\") {\n const { s: n, f: a } = r;\n return new RegExp(n, a);\n }\n if (t === \"BigInt\") try {\n return BigInt(r);\n } catch {\n throw new u(`invalid BigInt payload: ${String(r)}`);\n }\n if (t === \"Map\") return new Map(r.map(([n, a]) => [c(n), c(a)]));\n if (t === \"Set\") return new Set(r.map(c));\n const o = {};\n for (const n of Object.keys(e)) {\n const a = c(e[n]);\n n === \"__proto__\" ? Object.defineProperty(o, n, { value: a, enumerable: !0, writable: !0, configurable: !0 }) : o[n] = a;\n }\n return o;\n}, v = (e) => c(JSON.parse(e)), N = (e, t) => {\n const r = s(e);\n if (t === void 0) return localStorage.removeItem(r), !0;\n try {\n return localStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage localStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, O = (e) => {\n const t = localStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage localStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, b = (e) => {\n localStorage.removeItem(s(e));\n}, _ = () => {\n localStorage.clear();\n}, h = (e, t) => {\n const r = s(e);\n if (t === void 0) return sessionStorage.removeItem(r), !0;\n try {\n return sessionStorage.setItem(r, d(t)), !0;\n } catch (o) {\n return console.warn(`matias-storage sessionStorage write ${r} value=${String(t)}:`, o instanceof u ? o.message : o), !1;\n }\n}, R = (e) => {\n const t = sessionStorage.getItem(s(e));\n if (t === null) return null;\n try {\n return v(t);\n } catch (r) {\n console.warn(`matias-storage sessionStorage read ${s(e)}:`, r instanceof u ? r.message : r);\n }\n return null;\n}, A = (e) => {\n sessionStorage.removeItem(s(e));\n}, E = () => {\n sessionStorage.clear();\n};\nfunction $(e, t, r) {\n const o = m(e, r), n = s(e);\n return o === i.SESSION ? h(n, t) : N(n, t);\n}\nfunction x(e, t, r) {\n const o = typeof t == \"function\" ? t : r, n = m(e, typeof t == \"function\" ? void 0 : t), a = s(e), l = n === i.SESSION ? R(a) : O(a);\n return l === null ? null : o && !o(l) ? (console.warn(`matias-storage storage read ${a}: value failed the type guard, return null instead`), null) : l;\n}\nfunction j(e, t) {\n const r = m(e, t), o = s(e);\n r === i.SESSION ? A(o) : b(o);\n}\nconst B = (e = i.LOCAL) => {\n e === i.SESSION ? E() : _();\n};\nexport {\n i as WebStorageType,\n L as defineStorageKey,\n O as localStorageRead,\n b as localStorageRemove,\n _ as localStorageRemoveAll,\n N as localStorageWrite,\n s as resolveKeyString,\n m as resolveStorageType,\n R as sessionStorageRead,\n A as sessionStorageRemove,\n E as sessionStorageRemoveAll,\n h as sessionStorageWrite,\n x as storageRead,\n j as storageRemove,\n B as storageRemoveAll,\n $ as storageWrite\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * @Author: matiastang\n * @Date: 2022-02-09 17:17:20\n * @LastEditors: matiastang\n * @LastEditTime: 2024-07-16 18:28:21\n * @FilePath: /pinia-persisted-state/src/plugin/index.ts\n * @Description: pinia状态本地存储插件\n */\nimport type { PiniaPluginContext, PiniaCustomStateProperties, StateTree } from 'pinia'\nimport { localStorageRead, localStorageWrite } from 'matias-storage'\n\nconst NPMLINK = 'https://www.npmjs.com/package/@matiastang/pinia-persisted-state'\nconst PINIA_STORAGE_KEY = 'pinia-key'\nconst PINIA_STORAGE_CUSTOM_KEY = 'pinia-custom-key'\n\n/**\n * 需要对MapStoresCustomization类型进行扩展,不然将报错\n * Property 'suffix' does not exist on type 'MapStoresCustomization'.\n * [Id in `${Ids}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}`]: () => Store<Id extends `${infer RealId}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}` ? RealId : string, State, Getters, Actions>;\n */\ndeclare module 'pinia' {\n export interface MapStoresCustomization {\n suffix: string\n }\n}\n\n/**\n * 状态持久化config类型\n */\ninterface PersistedStateConfig {\n /**\n * 保存pinia的key\n */\n key?: string\n /**\n * 保存pinia custom properties的key\n */\n customKey?: string\n /**\n * 获取custom properties key 的过滤函数\n */\n customFilterKey?: (key: string) => boolean\n}\n\n/**\n * custom properties 类型\n */\ntype CustomPropertiesType = {\n [key: string]: StateTree & PiniaCustomStateProperties<StateTree>\n}\n\n/**\n * 状态持久化config\n */\nexport let persistedConfig: PersistedStateConfig = {\n key: PINIA_STORAGE_KEY,\n customKey: PINIA_STORAGE_CUSTOM_KEY,\n customFilterKey: (key: string) => {\n return !key.startsWith('$') && !key.startsWith('_') && !key.startsWith('set')\n },\n}\n\n/**\n * 判断本地数据是否为可用的记录对象(非null的非数组对象)\n * @param data\n * @returns\n */\nconst _isRecordObject = (\n data: unknown\n): data is StateTree & PiniaCustomStateProperties<StateTree> => {\n return typeof data === 'object' && data !== null && !Array.isArray(data)\n}\n\n/**\n * 本地存储数据差异化检测,更新\n * @param state\n * @param key\n * @returns\n */\nconst _localStateDiff = (\n state: StateTree & PiniaCustomStateProperties<StateTree>,\n stateKey: string\n) => {\n const persistedKey = persistedConfig.key\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或数据损坏/结构非法,均以初始值重建)\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n return\n }\n const localNameState = localState[stateKey]\n if (localNameState === undefined) {\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n return\n }\n // 差异查找更新\n for (const key in state) {\n if (Object.prototype.hasOwnProperty.call(state, key)) {\n const element = state[key]\n if (Object.prototype.hasOwnProperty.call(localNameState, key)) {\n const localElement = localNameState[key]\n if (element !== localElement) {\n state[key] = localElement\n }\n }\n }\n }\n localState[stateKey] = state\n // 差异保存\n localStorageWrite(persistedKey, localState)\n}\n\n/**\n * 获取custom properties\n * @param context\n * @returns\n */\nconst _contextCustomProperties = (context: PiniaPluginContext) => {\n const store = context.store\n const stateKeys = Object.keys(store.$state)\n const customKeys = Object.keys(store).filter((key) => {\n return persistedConfig.customFilterKey(key)\n })\n let customProperties = {} as CustomPropertiesType\n for (let i = 0; i < customKeys.length; i++) {\n const item = customKeys[i]\n if (!stateKeys.includes(item)) {\n if (Object.keys(customProperties).length <= 0) {\n customProperties = {\n [item]: store[item],\n }\n } else {\n customProperties[item] = store[item]\n }\n }\n }\n return customProperties\n}\n\n/**\n * pinia state 本地存储\n * @param context pinia context\n */\nexport function piniaPersistedState(context: PiniaPluginContext) {\n /**\n * FIXME: - 不能检测到customProperties和stateProperties,在调用customProperties和stateProperties之前\n */\n const persistedKey = persistedConfig.key\n const customKey = persistedConfig.customKey\n const state = context.store.$state\n const stateKey = context.store.$id\n if (stateKey.trim() === '') {\n console.error('store id 不能为空,详情查看:', NPMLINK)\n return\n }\n // 初始化检测更新\n _localStateDiff(state, stateKey)\n context.store.$subscribe(\n () => {\n const customProperties = _contextCustomProperties(context)\n const localState = localStorageRead<StateTree & PiniaCustomStateProperties<StateTree>>(\n persistedKey\n )\n if (!_isRecordObject(localState)) {\n // 初始化保存(本地无数据或结构非法时重建)\n if (Object.keys(customProperties).length > 0) {\n localStorageWrite(persistedKey, {\n [customKey]: {\n ...customProperties,\n },\n [stateKey]: state,\n })\n } else {\n localStorageWrite(persistedKey, {\n [stateKey]: state,\n })\n }\n return\n }\n const localCustom = localState[customKey]\n if (localCustom) {\n localState[customKey] = {\n ...localCustom,\n ...customProperties,\n }\n } else {\n localState[customKey] = {\n ...customProperties,\n }\n }\n localState[stateKey] = state\n // 直接更新存储状态\n // FIXME: - 非状态更新也会调用,可能会有性能问题\n localStorageWrite(persistedKey, localState)\n },\n {\n detached: true,\n }\n )\n}\n\n/**\n * 带配置创建pinia state 本地存储\n * @param config\n * @returns\n */\nexport function createPersistedState(config?: PersistedStateConfig) {\n if (config) {\n persistedConfig = {\n ...persistedConfig,\n ...config,\n }\n }\n return piniaPersistedState\n}\n\nexport default piniaPersistedState\n"],"names":["e","i","LOCAL","SESSION","s","key","u","Error","t","super","this","name","y","p","w","Set","S","g","f","Number","isNaN","toString","Date","getTime","RegExp","source","flags","Map","Array","from","entries","n","a","values","isArray","map","r","toJSON","has","add","o","Object","keys","delete","c","l","prototype","hasOwnProperty","call","includes","NaN","BigInt","String","defineProperty","value","enumerable","writable","configurable","N","localStorage","removeItem","setItem","JSON","stringify","d","console","warn","message","O","getItem","parse","NPMLINK","persistedConfig","customKey","customFilterKey","startsWith","_isRecordObject","data","_localStateDiff","state","stateKey","persistedKey","localState","localStorageRead","localStorageWrite","localNameState","element","localElement","_contextCustomProperties","context","store","stateKeys","$state","customKeys","filter","customProperties","length","item","piniaPersistedState","$id","trim","$subscribe","localCustom","detached","error","config"],"mappings":"yOAAA,IAAUA,EAANC,IAAMD,EAAmEC,GAAK,CAAE,GAAjEC,MAAQ,eAAgBF,EAAEG,QAAU,iBAAkBH,GACpE,MAAqGI,EAAKJ,GAAaA,OAAAA,GAAK,SAAWA,EAAIA,EAAEK,IAClJ,MAAMC,UAAUC,KAAAA,CACd,YAAYC,EAAAA,CACVC,MAAMD,CAAAA,EAAIE,KAAKC,KAAO,uBACvB,CAEE,CAAA,MAACC,EAAI,iBAAkBC,EAAI,mBAAoBC,EAAoB,IAAIC,IAAI,CAAC,MAAO,WAAY,YAAa,WAAeC,CAAAA,EAAAA,EAAKhB,KAASY,CAACA,GAAIZ,CAAMiB,GAAAA,EAAI,CAACjB,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AAAuC,MAAM,sBAAuBjC,EA+C7C,wBAOO,SAA8BkC,EAAAA,CAO1B,OANHA,IACkBjC,kBAAA,IACXA,EAAAA,gBAAAA,GACAiC,IAGJP,CACX","x_google_ignoreList":[0]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { PiniaPluginContext } from 'pinia';
|
|
2
|
+
/**
|
|
3
|
+
* 需要对MapStoresCustomization类型进行扩展,不然将报错
|
|
4
|
+
* Property 'suffix' does not exist on type 'MapStoresCustomization'.
|
|
5
|
+
* [Id in `${Ids}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}`]: () => Store<Id extends `${infer RealId}${MapStoresCustomization extends Record<'suffix', string> ? MapStoresCustomization['suffix'] : 'Store'}` ? RealId : string, State, Getters, Actions>;
|
|
6
|
+
*/
|
|
7
|
+
declare module 'pinia' {
|
|
8
|
+
interface MapStoresCustomization {
|
|
9
|
+
suffix: string;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* 状态持久化config类型
|
|
14
|
+
*/
|
|
15
|
+
interface PersistedStateConfig {
|
|
16
|
+
/**
|
|
17
|
+
* 保存pinia的key
|
|
18
|
+
*/
|
|
19
|
+
key?: string;
|
|
20
|
+
/**
|
|
21
|
+
* 保存pinia custom properties的key
|
|
22
|
+
*/
|
|
23
|
+
customKey?: string;
|
|
24
|
+
/**
|
|
25
|
+
* 获取custom properties key 的过滤函数
|
|
26
|
+
*/
|
|
27
|
+
customFilterKey?: (key: string) => boolean;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* 状态持久化config
|
|
31
|
+
*/
|
|
32
|
+
export declare let persistedConfig: PersistedStateConfig;
|
|
33
|
+
/**
|
|
34
|
+
* pinia state 本地存储
|
|
35
|
+
* @param context pinia context
|
|
36
|
+
*/
|
|
37
|
+
export declare function piniaPersistedState(context: PiniaPluginContext): void;
|
|
38
|
+
/**
|
|
39
|
+
* 带配置创建pinia state 本地存储
|
|
40
|
+
* @param config
|
|
41
|
+
* @returns
|
|
42
|
+
*/
|
|
43
|
+
export declare function createPersistedState(config?: PersistedStateConfig): typeof piniaPersistedState;
|
|
44
|
+
export default piniaPersistedState;
|
package/package.json
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@matiastang/pinia-persisted-state",
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "pinia状态持久化",
|
|
5
|
+
"main": "./dist/index.umd.js",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
9
|
+
"module": "./dist/index.es.js",
|
|
10
|
+
"types": "./dist/types/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./dist/index.es.js",
|
|
14
|
+
"require": "./dist/index.umd.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"pinia",
|
|
19
|
+
"matias",
|
|
20
|
+
"matiastang",
|
|
21
|
+
"pinia-persisted-state"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"dev": "vite",
|
|
25
|
+
"typecheck": "tsc --noEmit -p src/plugin/tsconfig.json",
|
|
26
|
+
"test": "vitest run",
|
|
27
|
+
"test:coverage": "vitest run --coverage",
|
|
28
|
+
"test:e2e": "playwright test",
|
|
29
|
+
"ts:build": "tsc --build src/plugin/tsconfig.json",
|
|
30
|
+
"build": "vite --config vite.build.config.ts build --mode production",
|
|
31
|
+
"cp:types": "cp -r src/plugin/types dist/",
|
|
32
|
+
"cp:type": "cp src/plugin/types/index.d.ts dist",
|
|
33
|
+
"plugin:build": "pnpm run ts:build && pnpm run build && pnpm run cp:types",
|
|
34
|
+
"push:npm:package": "npm version patch && npm publish",
|
|
35
|
+
"updata:package": "npm publish --registry https://registry.npmjs.org",
|
|
36
|
+
"plugin:build:push:npm:package": "pnpm run plugin:build && pnpm run push:npm:package"
|
|
37
|
+
},
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/matiastang/pinia-persisted-state.git"
|
|
41
|
+
},
|
|
42
|
+
"author": {
|
|
43
|
+
"name": "matiastang",
|
|
44
|
+
"email": "matiastang@163.com"
|
|
45
|
+
},
|
|
46
|
+
"license": "MIT",
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/matiastang/pinia-persisted-state/issues"
|
|
49
|
+
},
|
|
50
|
+
"homepage": "https://github.com/matiastang/pinia-persisted-state#readme",
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"matias-storage": "^0.3.0",
|
|
53
|
+
"pinia": "^2.0.23"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@playwright/test": "^1.62.1",
|
|
57
|
+
"@types/node": "^20.14.10",
|
|
58
|
+
"@vitejs/plugin-vue": "^5.0.5",
|
|
59
|
+
"@vitest/coverage-v8": "^3.2.7",
|
|
60
|
+
"@vue/test-utils": "^2.4.11",
|
|
61
|
+
"jsdom": "^25.0.1",
|
|
62
|
+
"rollup-plugin-terser": "^7.0.2",
|
|
63
|
+
"tslib": "^2.6.3",
|
|
64
|
+
"typescript": "^5.5.3",
|
|
65
|
+
"vite": "^5.3.3",
|
|
66
|
+
"vite-plugin-compression": "^0.5.1",
|
|
67
|
+
"vitest": "^3.2.7",
|
|
68
|
+
"vue": "^3.4.31",
|
|
69
|
+
"vue-router": "^4.4.0"
|
|
70
|
+
},
|
|
71
|
+
"pnpm": {
|
|
72
|
+
"onlyBuiltDependencies": [
|
|
73
|
+
"esbuild",
|
|
74
|
+
"vue-demi"
|
|
75
|
+
]
|
|
76
|
+
}
|
|
77
|
+
}
|