@wxt-dev/storage 1.0.0
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 +36 -0
- package/dist/index.d.mts +268 -0
- package/dist/index.d.ts +268 -0
- package/dist/index.mjs +493 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Aaron
|
|
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,36 @@
|
|
|
1
|
+
# WXT Storage
|
|
2
|
+
|
|
3
|
+
[Changelog](https://github.com/wxt-dev/wxt/blob/main/packages/storage/CHANGELOG.md) • [Docs](https://wxt.dev/storage.html)
|
|
4
|
+
|
|
5
|
+
A simplified wrapper around the extension storage APIs.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
### With WXT
|
|
10
|
+
|
|
11
|
+
This module is built-in to WXT, so you don't need to install anything.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { storage } from 'wxt/storage';
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
If you use auto-imports, `storage` is auto-imported for you, so you don't even need to import it!
|
|
18
|
+
|
|
19
|
+
### Without WXT
|
|
20
|
+
|
|
21
|
+
Install the NPM package:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm i @wxt-dev/storage
|
|
25
|
+
pnpm add @wxt-dev/storage
|
|
26
|
+
yarn add @wxt-dev/storage
|
|
27
|
+
bun add @wxt-dev/storage
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { storage } from '@wxt-dev/storage';
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
Read full docs on the [documentation website](https://wxt.dev/storage.html).
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
declare const storage: WxtStorage;
|
|
2
|
+
interface WxtStorage {
|
|
3
|
+
/**
|
|
4
|
+
* Get an item from storage, or return `null` if it doesn't exist.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* await storage.getItem<number>("local:installDate");
|
|
8
|
+
*/
|
|
9
|
+
getItem<TValue>(key: StorageItemKey, opts: GetItemOptions<TValue> & {
|
|
10
|
+
fallback: TValue;
|
|
11
|
+
}): Promise<TValue>;
|
|
12
|
+
getItem<TValue>(key: StorageItemKey, opts?: GetItemOptions<TValue>): Promise<TValue | null>;
|
|
13
|
+
/**
|
|
14
|
+
* Get multiple items from storage. The return order is guaranteed to be the same as the order
|
|
15
|
+
* requested.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* await storage.getItems(["local:installDate", "session:someCounter"]);
|
|
19
|
+
*/
|
|
20
|
+
getItems(keys: Array<StorageItemKey | WxtStorageItem<any, any> | {
|
|
21
|
+
key: StorageItemKey;
|
|
22
|
+
options?: GetItemOptions<any>;
|
|
23
|
+
}>): Promise<Array<{
|
|
24
|
+
key: StorageItemKey;
|
|
25
|
+
value: any;
|
|
26
|
+
}>>;
|
|
27
|
+
/**
|
|
28
|
+
* Return an object containing metadata about the key. Object is stored at `key + "$"`. If value
|
|
29
|
+
* is not an object, it returns an empty object.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* await storage.getMeta("local:installDate");
|
|
33
|
+
*/
|
|
34
|
+
getMeta<T extends Record<string, unknown>>(key: StorageItemKey): Promise<T>;
|
|
35
|
+
/**
|
|
36
|
+
* Get the metadata of multiple storage items.
|
|
37
|
+
*
|
|
38
|
+
* @param items List of keys or items to get the metadata of.
|
|
39
|
+
* @returns An array containing storage keys and their metadata.
|
|
40
|
+
*/
|
|
41
|
+
getMetas(keys: Array<StorageItemKey | WxtStorageItem<any, any>>): Promise<Array<{
|
|
42
|
+
key: StorageItemKey;
|
|
43
|
+
meta: any;
|
|
44
|
+
}>>;
|
|
45
|
+
/**
|
|
46
|
+
* Set a value in storage. Setting a value to `null` or `undefined` is equivalent to calling
|
|
47
|
+
* `removeItem`.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* await storage.setItem<number>("local:installDate", Date.now());
|
|
51
|
+
*/
|
|
52
|
+
setItem<T>(key: StorageItemKey, value: T | null): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Set multiple values in storage. If a value is set to `null` or `undefined`, the key is removed.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* await storage.setItem([
|
|
58
|
+
* { key: "local:installDate", value: Date.now() },
|
|
59
|
+
* { key: "session:someCounter, value: 5 },
|
|
60
|
+
* ]);
|
|
61
|
+
*/
|
|
62
|
+
setItems(values: Array<{
|
|
63
|
+
key: StorageItemKey;
|
|
64
|
+
value: any;
|
|
65
|
+
} | {
|
|
66
|
+
item: WxtStorageItem<any, any>;
|
|
67
|
+
value: any;
|
|
68
|
+
}>): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Sets metadata properties. If some properties are already set, but are not included in the
|
|
71
|
+
* `properties` parameter, they will not be removed.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* await storage.setMeta("local:installDate", { appVersion });
|
|
75
|
+
*/
|
|
76
|
+
setMeta<T extends Record<string, unknown>>(key: StorageItemKey, properties: T | null): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Set the metadata of multiple storage items.
|
|
79
|
+
*
|
|
80
|
+
* @param items List of storage keys or items and metadata to set for each.
|
|
81
|
+
*/
|
|
82
|
+
setMetas(metas: Array<{
|
|
83
|
+
key: StorageItemKey;
|
|
84
|
+
meta: Record<string, any>;
|
|
85
|
+
} | {
|
|
86
|
+
item: WxtStorageItem<any, any>;
|
|
87
|
+
meta: Record<string, any>;
|
|
88
|
+
}>): Promise<void>;
|
|
89
|
+
/**
|
|
90
|
+
* Removes an item from storage.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* await storage.removeItem("local:installDate");
|
|
94
|
+
*/
|
|
95
|
+
removeItem(key: StorageItemKey, opts?: RemoveItemOptions): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Remove a list of keys from storage.
|
|
98
|
+
*/
|
|
99
|
+
removeItems(keys: Array<StorageItemKey | WxtStorageItem<any, any> | {
|
|
100
|
+
key: StorageItemKey;
|
|
101
|
+
options?: RemoveItemOptions;
|
|
102
|
+
} | {
|
|
103
|
+
item: WxtStorageItem<any, any>;
|
|
104
|
+
options?: RemoveItemOptions;
|
|
105
|
+
}>): Promise<void>;
|
|
106
|
+
/**
|
|
107
|
+
* Remove the entire metadata for a key, or specific properties by name.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* // Remove all metadata properties from the item
|
|
111
|
+
* await storage.removeMeta("local:installDate");
|
|
112
|
+
*
|
|
113
|
+
* // Remove only specific the "v" field
|
|
114
|
+
* await storage.removeMeta("local:installDate", "v")
|
|
115
|
+
*/
|
|
116
|
+
removeMeta(key: StorageItemKey, properties?: string | string[]): Promise<void>;
|
|
117
|
+
/**
|
|
118
|
+
* Return all the items in storage.
|
|
119
|
+
*/
|
|
120
|
+
snapshot(base: StorageArea, opts?: SnapshotOptions): Promise<Record<string, unknown>>;
|
|
121
|
+
/**
|
|
122
|
+
* Restores the results of `snapshot`. If new properties have been saved since the snapshot, they are
|
|
123
|
+
* not overridden. Only values existing in the snapshot are overridden.
|
|
124
|
+
*/
|
|
125
|
+
restoreSnapshot(base: StorageArea, data: any): Promise<void>;
|
|
126
|
+
/**
|
|
127
|
+
* Watch for changes to a specific key in storage.
|
|
128
|
+
*/
|
|
129
|
+
watch<T>(key: StorageItemKey, cb: WatchCallback<T | null>): Unwatch;
|
|
130
|
+
/**
|
|
131
|
+
* Remove all watch listeners.
|
|
132
|
+
*/
|
|
133
|
+
unwatch(): void;
|
|
134
|
+
/**
|
|
135
|
+
* Define a storage item with a default value, type, or versioning.
|
|
136
|
+
*
|
|
137
|
+
* Read full docs: https://wxt.dev/guide/extension-apis/storage.html#defining-storage-items
|
|
138
|
+
*/
|
|
139
|
+
defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(key: StorageItemKey): WxtStorageItem<TValue | null, TMetadata>;
|
|
140
|
+
defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(key: StorageItemKey, options: WxtStorageItemOptions<TValue>): WxtStorageItem<TValue, TMetadata>;
|
|
141
|
+
}
|
|
142
|
+
interface WxtStorageItem<TValue, TMetadata extends Record<string, unknown>> {
|
|
143
|
+
/**
|
|
144
|
+
* The storage key passed when creating the storage item.
|
|
145
|
+
*/
|
|
146
|
+
key: StorageItemKey;
|
|
147
|
+
/**
|
|
148
|
+
* @deprecated Renamed to fallback, use it instead.
|
|
149
|
+
*/
|
|
150
|
+
defaultValue: TValue;
|
|
151
|
+
/**
|
|
152
|
+
* The value provided by the `fallback` option.
|
|
153
|
+
*/
|
|
154
|
+
fallback: TValue;
|
|
155
|
+
/**
|
|
156
|
+
* Get the latest value from storage.
|
|
157
|
+
*/
|
|
158
|
+
getValue(): Promise<TValue>;
|
|
159
|
+
/**
|
|
160
|
+
* Get metadata.
|
|
161
|
+
*/
|
|
162
|
+
getMeta(): Promise<NullablePartial<TMetadata>>;
|
|
163
|
+
/**
|
|
164
|
+
* Set the value in storage.
|
|
165
|
+
*/
|
|
166
|
+
setValue(value: TValue): Promise<void>;
|
|
167
|
+
/**
|
|
168
|
+
* Set metadata properties.
|
|
169
|
+
*/
|
|
170
|
+
setMeta(properties: NullablePartial<TMetadata>): Promise<void>;
|
|
171
|
+
/**
|
|
172
|
+
* Remove the value from storage.
|
|
173
|
+
*/
|
|
174
|
+
removeValue(opts?: RemoveItemOptions): Promise<void>;
|
|
175
|
+
/**
|
|
176
|
+
* Remove all metadata or certain properties from metadata.
|
|
177
|
+
*/
|
|
178
|
+
removeMeta(properties?: string[]): Promise<void>;
|
|
179
|
+
/**
|
|
180
|
+
* Listen for changes to the value in storage.
|
|
181
|
+
*/
|
|
182
|
+
watch(cb: WatchCallback<TValue>): Unwatch;
|
|
183
|
+
/**
|
|
184
|
+
* If there are migrations defined on the storage item, migrate to the latest version.
|
|
185
|
+
*
|
|
186
|
+
* **This function is ran automatically whenever the extension updates**, so you don't have to call it
|
|
187
|
+
* manually.
|
|
188
|
+
*/
|
|
189
|
+
migrate(): Promise<void>;
|
|
190
|
+
}
|
|
191
|
+
type StorageArea = 'local' | 'session' | 'sync' | 'managed';
|
|
192
|
+
type StorageItemKey = `${StorageArea}:${string}`;
|
|
193
|
+
interface GetItemOptions<T> {
|
|
194
|
+
/**
|
|
195
|
+
* @deprecated Renamed to `fallback`, use it instead.
|
|
196
|
+
*/
|
|
197
|
+
defaultValue?: T;
|
|
198
|
+
/**
|
|
199
|
+
* Default value returned when `getItem` would otherwise return `null`.
|
|
200
|
+
*/
|
|
201
|
+
fallback?: T;
|
|
202
|
+
}
|
|
203
|
+
interface RemoveItemOptions {
|
|
204
|
+
/**
|
|
205
|
+
* Optionally remove metadata when deleting a key.
|
|
206
|
+
*
|
|
207
|
+
* @default false
|
|
208
|
+
*/
|
|
209
|
+
removeMeta?: boolean;
|
|
210
|
+
}
|
|
211
|
+
interface SnapshotOptions {
|
|
212
|
+
/**
|
|
213
|
+
* Exclude a list of keys. The storage area prefix should be removed since the snapshot is for a
|
|
214
|
+
* specific storage area already.
|
|
215
|
+
*/
|
|
216
|
+
excludeKeys?: string[];
|
|
217
|
+
}
|
|
218
|
+
interface WxtStorageItemOptions<T> {
|
|
219
|
+
/**
|
|
220
|
+
* @deprecated Renamed to `fallback`, use it instead.
|
|
221
|
+
*/
|
|
222
|
+
defaultValue?: T;
|
|
223
|
+
/**
|
|
224
|
+
* Default value returned when `getValue` would otherwise return `null`.
|
|
225
|
+
*/
|
|
226
|
+
fallback?: T;
|
|
227
|
+
/**
|
|
228
|
+
* If passed, a value in storage will be initialized immediately after
|
|
229
|
+
* defining the storage item. This function returns the value that will be
|
|
230
|
+
* saved to storage during the initialization process if a value doesn't
|
|
231
|
+
* already exist.
|
|
232
|
+
*/
|
|
233
|
+
init?: () => T | Promise<T>;
|
|
234
|
+
/**
|
|
235
|
+
* Provide a version number for the storage item to enable migrations. When changing the version
|
|
236
|
+
* in the future, migration functions will be ran on application startup.
|
|
237
|
+
*/
|
|
238
|
+
version?: number;
|
|
239
|
+
/**
|
|
240
|
+
* A map of version numbers to the functions used to migrate the data to that version.
|
|
241
|
+
*/
|
|
242
|
+
migrations?: Record<number, (oldValue: any) => any>;
|
|
243
|
+
}
|
|
244
|
+
type StorageAreaChanges = {
|
|
245
|
+
[key: string]: chrome.storage.StorageChange;
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* Same as `Partial`, but includes `| null`. It makes all the properties of an object optional and
|
|
249
|
+
* nullable.
|
|
250
|
+
*/
|
|
251
|
+
type NullablePartial<T> = {
|
|
252
|
+
[key in keyof T]+?: T[key] | undefined | null;
|
|
253
|
+
};
|
|
254
|
+
/**
|
|
255
|
+
* Callback called when a value in storage is changed.
|
|
256
|
+
*/
|
|
257
|
+
type WatchCallback<T> = (newValue: T, oldValue: T) => void;
|
|
258
|
+
/**
|
|
259
|
+
* Call to remove a watch listener
|
|
260
|
+
*/
|
|
261
|
+
type Unwatch = () => void;
|
|
262
|
+
declare class MigrationError extends Error {
|
|
263
|
+
key: string;
|
|
264
|
+
version: number;
|
|
265
|
+
constructor(key: string, version: number, options?: ErrorOptions);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export { type GetItemOptions, MigrationError, type RemoveItemOptions, type SnapshotOptions, type StorageArea, type StorageAreaChanges, type StorageItemKey, type Unwatch, type WatchCallback, type WxtStorage, type WxtStorageItem, type WxtStorageItemOptions, storage };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
declare const storage: WxtStorage;
|
|
2
|
+
interface WxtStorage {
|
|
3
|
+
/**
|
|
4
|
+
* Get an item from storage, or return `null` if it doesn't exist.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* await storage.getItem<number>("local:installDate");
|
|
8
|
+
*/
|
|
9
|
+
getItem<TValue>(key: StorageItemKey, opts: GetItemOptions<TValue> & {
|
|
10
|
+
fallback: TValue;
|
|
11
|
+
}): Promise<TValue>;
|
|
12
|
+
getItem<TValue>(key: StorageItemKey, opts?: GetItemOptions<TValue>): Promise<TValue | null>;
|
|
13
|
+
/**
|
|
14
|
+
* Get multiple items from storage. The return order is guaranteed to be the same as the order
|
|
15
|
+
* requested.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* await storage.getItems(["local:installDate", "session:someCounter"]);
|
|
19
|
+
*/
|
|
20
|
+
getItems(keys: Array<StorageItemKey | WxtStorageItem<any, any> | {
|
|
21
|
+
key: StorageItemKey;
|
|
22
|
+
options?: GetItemOptions<any>;
|
|
23
|
+
}>): Promise<Array<{
|
|
24
|
+
key: StorageItemKey;
|
|
25
|
+
value: any;
|
|
26
|
+
}>>;
|
|
27
|
+
/**
|
|
28
|
+
* Return an object containing metadata about the key. Object is stored at `key + "$"`. If value
|
|
29
|
+
* is not an object, it returns an empty object.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* await storage.getMeta("local:installDate");
|
|
33
|
+
*/
|
|
34
|
+
getMeta<T extends Record<string, unknown>>(key: StorageItemKey): Promise<T>;
|
|
35
|
+
/**
|
|
36
|
+
* Get the metadata of multiple storage items.
|
|
37
|
+
*
|
|
38
|
+
* @param items List of keys or items to get the metadata of.
|
|
39
|
+
* @returns An array containing storage keys and their metadata.
|
|
40
|
+
*/
|
|
41
|
+
getMetas(keys: Array<StorageItemKey | WxtStorageItem<any, any>>): Promise<Array<{
|
|
42
|
+
key: StorageItemKey;
|
|
43
|
+
meta: any;
|
|
44
|
+
}>>;
|
|
45
|
+
/**
|
|
46
|
+
* Set a value in storage. Setting a value to `null` or `undefined` is equivalent to calling
|
|
47
|
+
* `removeItem`.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* await storage.setItem<number>("local:installDate", Date.now());
|
|
51
|
+
*/
|
|
52
|
+
setItem<T>(key: StorageItemKey, value: T | null): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Set multiple values in storage. If a value is set to `null` or `undefined`, the key is removed.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* await storage.setItem([
|
|
58
|
+
* { key: "local:installDate", value: Date.now() },
|
|
59
|
+
* { key: "session:someCounter, value: 5 },
|
|
60
|
+
* ]);
|
|
61
|
+
*/
|
|
62
|
+
setItems(values: Array<{
|
|
63
|
+
key: StorageItemKey;
|
|
64
|
+
value: any;
|
|
65
|
+
} | {
|
|
66
|
+
item: WxtStorageItem<any, any>;
|
|
67
|
+
value: any;
|
|
68
|
+
}>): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Sets metadata properties. If some properties are already set, but are not included in the
|
|
71
|
+
* `properties` parameter, they will not be removed.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* await storage.setMeta("local:installDate", { appVersion });
|
|
75
|
+
*/
|
|
76
|
+
setMeta<T extends Record<string, unknown>>(key: StorageItemKey, properties: T | null): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Set the metadata of multiple storage items.
|
|
79
|
+
*
|
|
80
|
+
* @param items List of storage keys or items and metadata to set for each.
|
|
81
|
+
*/
|
|
82
|
+
setMetas(metas: Array<{
|
|
83
|
+
key: StorageItemKey;
|
|
84
|
+
meta: Record<string, any>;
|
|
85
|
+
} | {
|
|
86
|
+
item: WxtStorageItem<any, any>;
|
|
87
|
+
meta: Record<string, any>;
|
|
88
|
+
}>): Promise<void>;
|
|
89
|
+
/**
|
|
90
|
+
* Removes an item from storage.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* await storage.removeItem("local:installDate");
|
|
94
|
+
*/
|
|
95
|
+
removeItem(key: StorageItemKey, opts?: RemoveItemOptions): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Remove a list of keys from storage.
|
|
98
|
+
*/
|
|
99
|
+
removeItems(keys: Array<StorageItemKey | WxtStorageItem<any, any> | {
|
|
100
|
+
key: StorageItemKey;
|
|
101
|
+
options?: RemoveItemOptions;
|
|
102
|
+
} | {
|
|
103
|
+
item: WxtStorageItem<any, any>;
|
|
104
|
+
options?: RemoveItemOptions;
|
|
105
|
+
}>): Promise<void>;
|
|
106
|
+
/**
|
|
107
|
+
* Remove the entire metadata for a key, or specific properties by name.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* // Remove all metadata properties from the item
|
|
111
|
+
* await storage.removeMeta("local:installDate");
|
|
112
|
+
*
|
|
113
|
+
* // Remove only specific the "v" field
|
|
114
|
+
* await storage.removeMeta("local:installDate", "v")
|
|
115
|
+
*/
|
|
116
|
+
removeMeta(key: StorageItemKey, properties?: string | string[]): Promise<void>;
|
|
117
|
+
/**
|
|
118
|
+
* Return all the items in storage.
|
|
119
|
+
*/
|
|
120
|
+
snapshot(base: StorageArea, opts?: SnapshotOptions): Promise<Record<string, unknown>>;
|
|
121
|
+
/**
|
|
122
|
+
* Restores the results of `snapshot`. If new properties have been saved since the snapshot, they are
|
|
123
|
+
* not overridden. Only values existing in the snapshot are overridden.
|
|
124
|
+
*/
|
|
125
|
+
restoreSnapshot(base: StorageArea, data: any): Promise<void>;
|
|
126
|
+
/**
|
|
127
|
+
* Watch for changes to a specific key in storage.
|
|
128
|
+
*/
|
|
129
|
+
watch<T>(key: StorageItemKey, cb: WatchCallback<T | null>): Unwatch;
|
|
130
|
+
/**
|
|
131
|
+
* Remove all watch listeners.
|
|
132
|
+
*/
|
|
133
|
+
unwatch(): void;
|
|
134
|
+
/**
|
|
135
|
+
* Define a storage item with a default value, type, or versioning.
|
|
136
|
+
*
|
|
137
|
+
* Read full docs: https://wxt.dev/guide/extension-apis/storage.html#defining-storage-items
|
|
138
|
+
*/
|
|
139
|
+
defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(key: StorageItemKey): WxtStorageItem<TValue | null, TMetadata>;
|
|
140
|
+
defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(key: StorageItemKey, options: WxtStorageItemOptions<TValue>): WxtStorageItem<TValue, TMetadata>;
|
|
141
|
+
}
|
|
142
|
+
interface WxtStorageItem<TValue, TMetadata extends Record<string, unknown>> {
|
|
143
|
+
/**
|
|
144
|
+
* The storage key passed when creating the storage item.
|
|
145
|
+
*/
|
|
146
|
+
key: StorageItemKey;
|
|
147
|
+
/**
|
|
148
|
+
* @deprecated Renamed to fallback, use it instead.
|
|
149
|
+
*/
|
|
150
|
+
defaultValue: TValue;
|
|
151
|
+
/**
|
|
152
|
+
* The value provided by the `fallback` option.
|
|
153
|
+
*/
|
|
154
|
+
fallback: TValue;
|
|
155
|
+
/**
|
|
156
|
+
* Get the latest value from storage.
|
|
157
|
+
*/
|
|
158
|
+
getValue(): Promise<TValue>;
|
|
159
|
+
/**
|
|
160
|
+
* Get metadata.
|
|
161
|
+
*/
|
|
162
|
+
getMeta(): Promise<NullablePartial<TMetadata>>;
|
|
163
|
+
/**
|
|
164
|
+
* Set the value in storage.
|
|
165
|
+
*/
|
|
166
|
+
setValue(value: TValue): Promise<void>;
|
|
167
|
+
/**
|
|
168
|
+
* Set metadata properties.
|
|
169
|
+
*/
|
|
170
|
+
setMeta(properties: NullablePartial<TMetadata>): Promise<void>;
|
|
171
|
+
/**
|
|
172
|
+
* Remove the value from storage.
|
|
173
|
+
*/
|
|
174
|
+
removeValue(opts?: RemoveItemOptions): Promise<void>;
|
|
175
|
+
/**
|
|
176
|
+
* Remove all metadata or certain properties from metadata.
|
|
177
|
+
*/
|
|
178
|
+
removeMeta(properties?: string[]): Promise<void>;
|
|
179
|
+
/**
|
|
180
|
+
* Listen for changes to the value in storage.
|
|
181
|
+
*/
|
|
182
|
+
watch(cb: WatchCallback<TValue>): Unwatch;
|
|
183
|
+
/**
|
|
184
|
+
* If there are migrations defined on the storage item, migrate to the latest version.
|
|
185
|
+
*
|
|
186
|
+
* **This function is ran automatically whenever the extension updates**, so you don't have to call it
|
|
187
|
+
* manually.
|
|
188
|
+
*/
|
|
189
|
+
migrate(): Promise<void>;
|
|
190
|
+
}
|
|
191
|
+
type StorageArea = 'local' | 'session' | 'sync' | 'managed';
|
|
192
|
+
type StorageItemKey = `${StorageArea}:${string}`;
|
|
193
|
+
interface GetItemOptions<T> {
|
|
194
|
+
/**
|
|
195
|
+
* @deprecated Renamed to `fallback`, use it instead.
|
|
196
|
+
*/
|
|
197
|
+
defaultValue?: T;
|
|
198
|
+
/**
|
|
199
|
+
* Default value returned when `getItem` would otherwise return `null`.
|
|
200
|
+
*/
|
|
201
|
+
fallback?: T;
|
|
202
|
+
}
|
|
203
|
+
interface RemoveItemOptions {
|
|
204
|
+
/**
|
|
205
|
+
* Optionally remove metadata when deleting a key.
|
|
206
|
+
*
|
|
207
|
+
* @default false
|
|
208
|
+
*/
|
|
209
|
+
removeMeta?: boolean;
|
|
210
|
+
}
|
|
211
|
+
interface SnapshotOptions {
|
|
212
|
+
/**
|
|
213
|
+
* Exclude a list of keys. The storage area prefix should be removed since the snapshot is for a
|
|
214
|
+
* specific storage area already.
|
|
215
|
+
*/
|
|
216
|
+
excludeKeys?: string[];
|
|
217
|
+
}
|
|
218
|
+
interface WxtStorageItemOptions<T> {
|
|
219
|
+
/**
|
|
220
|
+
* @deprecated Renamed to `fallback`, use it instead.
|
|
221
|
+
*/
|
|
222
|
+
defaultValue?: T;
|
|
223
|
+
/**
|
|
224
|
+
* Default value returned when `getValue` would otherwise return `null`.
|
|
225
|
+
*/
|
|
226
|
+
fallback?: T;
|
|
227
|
+
/**
|
|
228
|
+
* If passed, a value in storage will be initialized immediately after
|
|
229
|
+
* defining the storage item. This function returns the value that will be
|
|
230
|
+
* saved to storage during the initialization process if a value doesn't
|
|
231
|
+
* already exist.
|
|
232
|
+
*/
|
|
233
|
+
init?: () => T | Promise<T>;
|
|
234
|
+
/**
|
|
235
|
+
* Provide a version number for the storage item to enable migrations. When changing the version
|
|
236
|
+
* in the future, migration functions will be ran on application startup.
|
|
237
|
+
*/
|
|
238
|
+
version?: number;
|
|
239
|
+
/**
|
|
240
|
+
* A map of version numbers to the functions used to migrate the data to that version.
|
|
241
|
+
*/
|
|
242
|
+
migrations?: Record<number, (oldValue: any) => any>;
|
|
243
|
+
}
|
|
244
|
+
type StorageAreaChanges = {
|
|
245
|
+
[key: string]: chrome.storage.StorageChange;
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* Same as `Partial`, but includes `| null`. It makes all the properties of an object optional and
|
|
249
|
+
* nullable.
|
|
250
|
+
*/
|
|
251
|
+
type NullablePartial<T> = {
|
|
252
|
+
[key in keyof T]+?: T[key] | undefined | null;
|
|
253
|
+
};
|
|
254
|
+
/**
|
|
255
|
+
* Callback called when a value in storage is changed.
|
|
256
|
+
*/
|
|
257
|
+
type WatchCallback<T> = (newValue: T, oldValue: T) => void;
|
|
258
|
+
/**
|
|
259
|
+
* Call to remove a watch listener
|
|
260
|
+
*/
|
|
261
|
+
type Unwatch = () => void;
|
|
262
|
+
declare class MigrationError extends Error {
|
|
263
|
+
key: string;
|
|
264
|
+
version: number;
|
|
265
|
+
constructor(key: string, version: number, options?: ErrorOptions);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export { type GetItemOptions, MigrationError, type RemoveItemOptions, type SnapshotOptions, type StorageArea, type StorageAreaChanges, type StorageItemKey, type Unwatch, type WatchCallback, type WxtStorage, type WxtStorageItem, type WxtStorageItemOptions, storage };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
import { dequal } from 'dequal/lite';
|
|
2
|
+
import { Mutex } from 'async-mutex';
|
|
3
|
+
|
|
4
|
+
const storage = createStorage();
|
|
5
|
+
function createStorage() {
|
|
6
|
+
const drivers = {
|
|
7
|
+
local: createDriver("local"),
|
|
8
|
+
session: createDriver("session"),
|
|
9
|
+
sync: createDriver("sync"),
|
|
10
|
+
managed: createDriver("managed")
|
|
11
|
+
};
|
|
12
|
+
const getDriver = (area) => {
|
|
13
|
+
const driver = drivers[area];
|
|
14
|
+
if (driver == null) {
|
|
15
|
+
const areaNames = Object.keys(drivers).join(", ");
|
|
16
|
+
throw Error(`Invalid area "${area}". Options: ${areaNames}`);
|
|
17
|
+
}
|
|
18
|
+
return driver;
|
|
19
|
+
};
|
|
20
|
+
const resolveKey = (key) => {
|
|
21
|
+
const deliminatorIndex = key.indexOf(":");
|
|
22
|
+
const driverArea = key.substring(0, deliminatorIndex);
|
|
23
|
+
const driverKey = key.substring(deliminatorIndex + 1);
|
|
24
|
+
if (driverKey == null)
|
|
25
|
+
throw Error(
|
|
26
|
+
`Storage key should be in the form of "area:key", but received "${key}"`
|
|
27
|
+
);
|
|
28
|
+
return {
|
|
29
|
+
driverArea,
|
|
30
|
+
driverKey,
|
|
31
|
+
driver: getDriver(driverArea)
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
const getMetaKey = (key) => key + "$";
|
|
35
|
+
const mergeMeta = (oldMeta, newMeta) => {
|
|
36
|
+
const newFields = { ...oldMeta };
|
|
37
|
+
Object.entries(newMeta).forEach(([key, value]) => {
|
|
38
|
+
if (value == null)
|
|
39
|
+
delete newFields[key];
|
|
40
|
+
else
|
|
41
|
+
newFields[key] = value;
|
|
42
|
+
});
|
|
43
|
+
return newFields;
|
|
44
|
+
};
|
|
45
|
+
const getValueOrFallback = (value, fallback) => value ?? fallback ?? null;
|
|
46
|
+
const getMetaValue = (properties) => typeof properties === "object" && !Array.isArray(properties) ? properties : {};
|
|
47
|
+
const getItem = async (driver, driverKey, opts) => {
|
|
48
|
+
const res = await driver.getItem(driverKey);
|
|
49
|
+
return getValueOrFallback(res, opts?.fallback ?? opts?.defaultValue);
|
|
50
|
+
};
|
|
51
|
+
const getMeta = async (driver, driverKey) => {
|
|
52
|
+
const metaKey = getMetaKey(driverKey);
|
|
53
|
+
const res = await driver.getItem(metaKey);
|
|
54
|
+
return getMetaValue(res);
|
|
55
|
+
};
|
|
56
|
+
const setItem = async (driver, driverKey, value) => {
|
|
57
|
+
await driver.setItem(driverKey, value ?? null);
|
|
58
|
+
};
|
|
59
|
+
const setMeta = async (driver, driverKey, properties) => {
|
|
60
|
+
const metaKey = getMetaKey(driverKey);
|
|
61
|
+
const existingFields = getMetaValue(await driver.getItem(metaKey));
|
|
62
|
+
await driver.setItem(metaKey, mergeMeta(existingFields, properties));
|
|
63
|
+
};
|
|
64
|
+
const removeItem = async (driver, driverKey, opts) => {
|
|
65
|
+
await driver.removeItem(driverKey);
|
|
66
|
+
if (opts?.removeMeta) {
|
|
67
|
+
const metaKey = getMetaKey(driverKey);
|
|
68
|
+
await driver.removeItem(metaKey);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
const removeMeta = async (driver, driverKey, properties) => {
|
|
72
|
+
const metaKey = getMetaKey(driverKey);
|
|
73
|
+
if (properties == null) {
|
|
74
|
+
await driver.removeItem(metaKey);
|
|
75
|
+
} else {
|
|
76
|
+
const newFields = getMetaValue(await driver.getItem(metaKey));
|
|
77
|
+
[properties].flat().forEach((field) => delete newFields[field]);
|
|
78
|
+
await driver.setItem(metaKey, newFields);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const watch = (driver, driverKey, cb) => {
|
|
82
|
+
return driver.watch(driverKey, cb);
|
|
83
|
+
};
|
|
84
|
+
const storage2 = {
|
|
85
|
+
getItem: async (key, opts) => {
|
|
86
|
+
const { driver, driverKey } = resolveKey(key);
|
|
87
|
+
return await getItem(driver, driverKey, opts);
|
|
88
|
+
},
|
|
89
|
+
getItems: async (keys) => {
|
|
90
|
+
const areaToKeyMap = /* @__PURE__ */ new Map();
|
|
91
|
+
const keyToOptsMap = /* @__PURE__ */ new Map();
|
|
92
|
+
const orderedKeys = [];
|
|
93
|
+
keys.forEach((key) => {
|
|
94
|
+
let keyStr;
|
|
95
|
+
let opts;
|
|
96
|
+
if (typeof key === "string") {
|
|
97
|
+
keyStr = key;
|
|
98
|
+
} else if ("getValue" in key) {
|
|
99
|
+
keyStr = key.key;
|
|
100
|
+
opts = { fallback: key.fallback };
|
|
101
|
+
} else {
|
|
102
|
+
keyStr = key.key;
|
|
103
|
+
opts = key.options;
|
|
104
|
+
}
|
|
105
|
+
orderedKeys.push(keyStr);
|
|
106
|
+
const { driverArea, driverKey } = resolveKey(keyStr);
|
|
107
|
+
const areaKeys = areaToKeyMap.get(driverArea) ?? [];
|
|
108
|
+
areaToKeyMap.set(driverArea, areaKeys.concat(driverKey));
|
|
109
|
+
keyToOptsMap.set(keyStr, opts);
|
|
110
|
+
});
|
|
111
|
+
const resultsMap = /* @__PURE__ */ new Map();
|
|
112
|
+
await Promise.all(
|
|
113
|
+
Array.from(areaToKeyMap.entries()).map(async ([driverArea, keys2]) => {
|
|
114
|
+
const driverResults = await drivers[driverArea].getItems(keys2);
|
|
115
|
+
driverResults.forEach((driverResult) => {
|
|
116
|
+
const key = `${driverArea}:${driverResult.key}`;
|
|
117
|
+
const opts = keyToOptsMap.get(key);
|
|
118
|
+
const value = getValueOrFallback(
|
|
119
|
+
driverResult.value,
|
|
120
|
+
opts?.fallback ?? opts?.defaultValue
|
|
121
|
+
);
|
|
122
|
+
resultsMap.set(key, value);
|
|
123
|
+
});
|
|
124
|
+
})
|
|
125
|
+
);
|
|
126
|
+
return orderedKeys.map((key) => ({
|
|
127
|
+
key,
|
|
128
|
+
value: resultsMap.get(key)
|
|
129
|
+
}));
|
|
130
|
+
},
|
|
131
|
+
getMeta: async (key) => {
|
|
132
|
+
const { driver, driverKey } = resolveKey(key);
|
|
133
|
+
return await getMeta(driver, driverKey);
|
|
134
|
+
},
|
|
135
|
+
getMetas: async (args) => {
|
|
136
|
+
const keys = args.map((arg) => {
|
|
137
|
+
const key = typeof arg === "string" ? arg : arg.key;
|
|
138
|
+
const { driverArea, driverKey } = resolveKey(key);
|
|
139
|
+
return {
|
|
140
|
+
key,
|
|
141
|
+
driverArea,
|
|
142
|
+
driverKey,
|
|
143
|
+
driverMetaKey: getMetaKey(driverKey)
|
|
144
|
+
};
|
|
145
|
+
});
|
|
146
|
+
const areaToDriverMetaKeysMap = keys.reduce((map, key) => {
|
|
147
|
+
var _a;
|
|
148
|
+
map[_a = key.driverArea] ?? (map[_a] = []);
|
|
149
|
+
map[key.driverArea].push(key);
|
|
150
|
+
return map;
|
|
151
|
+
}, {});
|
|
152
|
+
const resultsMap = {};
|
|
153
|
+
await Promise.all(
|
|
154
|
+
Object.entries(areaToDriverMetaKeysMap).map(async ([area, keys2]) => {
|
|
155
|
+
const areaRes = await chrome.storage[area].get(
|
|
156
|
+
keys2.map((key) => key.driverMetaKey)
|
|
157
|
+
);
|
|
158
|
+
keys2.forEach((key) => {
|
|
159
|
+
resultsMap[key.key] = areaRes[key.driverMetaKey] ?? {};
|
|
160
|
+
});
|
|
161
|
+
})
|
|
162
|
+
);
|
|
163
|
+
return keys.map((key) => ({
|
|
164
|
+
key: key.key,
|
|
165
|
+
meta: resultsMap[key.key]
|
|
166
|
+
}));
|
|
167
|
+
},
|
|
168
|
+
setItem: async (key, value) => {
|
|
169
|
+
const { driver, driverKey } = resolveKey(key);
|
|
170
|
+
await setItem(driver, driverKey, value);
|
|
171
|
+
},
|
|
172
|
+
setItems: async (items) => {
|
|
173
|
+
const areaToKeyValueMap = {};
|
|
174
|
+
items.forEach((item) => {
|
|
175
|
+
const { driverArea, driverKey } = resolveKey(
|
|
176
|
+
"key" in item ? item.key : item.item.key
|
|
177
|
+
);
|
|
178
|
+
areaToKeyValueMap[driverArea] ?? (areaToKeyValueMap[driverArea] = []);
|
|
179
|
+
areaToKeyValueMap[driverArea].push({
|
|
180
|
+
key: driverKey,
|
|
181
|
+
value: item.value
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
await Promise.all(
|
|
185
|
+
Object.entries(areaToKeyValueMap).map(async ([driverArea, values]) => {
|
|
186
|
+
const driver = getDriver(driverArea);
|
|
187
|
+
await driver.setItems(values);
|
|
188
|
+
})
|
|
189
|
+
);
|
|
190
|
+
},
|
|
191
|
+
setMeta: async (key, properties) => {
|
|
192
|
+
const { driver, driverKey } = resolveKey(key);
|
|
193
|
+
await setMeta(driver, driverKey, properties);
|
|
194
|
+
},
|
|
195
|
+
setMetas: async (items) => {
|
|
196
|
+
const areaToMetaUpdatesMap = {};
|
|
197
|
+
items.forEach((item) => {
|
|
198
|
+
const { driverArea, driverKey } = resolveKey(
|
|
199
|
+
"key" in item ? item.key : item.item.key
|
|
200
|
+
);
|
|
201
|
+
areaToMetaUpdatesMap[driverArea] ?? (areaToMetaUpdatesMap[driverArea] = []);
|
|
202
|
+
areaToMetaUpdatesMap[driverArea].push({
|
|
203
|
+
key: driverKey,
|
|
204
|
+
properties: item.meta
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
await Promise.all(
|
|
208
|
+
Object.entries(areaToMetaUpdatesMap).map(
|
|
209
|
+
async ([storageArea, updates]) => {
|
|
210
|
+
const driver = getDriver(storageArea);
|
|
211
|
+
const metaKeys = updates.map(({ key }) => getMetaKey(key));
|
|
212
|
+
console.log(storageArea, metaKeys);
|
|
213
|
+
const existingMetas = await driver.getItems(metaKeys);
|
|
214
|
+
const existingMetaMap = Object.fromEntries(
|
|
215
|
+
existingMetas.map(({ key, value }) => [key, getMetaValue(value)])
|
|
216
|
+
);
|
|
217
|
+
const metaUpdates = updates.map(({ key, properties }) => {
|
|
218
|
+
const metaKey = getMetaKey(key);
|
|
219
|
+
return {
|
|
220
|
+
key: metaKey,
|
|
221
|
+
value: mergeMeta(existingMetaMap[metaKey] ?? {}, properties)
|
|
222
|
+
};
|
|
223
|
+
});
|
|
224
|
+
await driver.setItems(metaUpdates);
|
|
225
|
+
}
|
|
226
|
+
)
|
|
227
|
+
);
|
|
228
|
+
},
|
|
229
|
+
removeItem: async (key, opts) => {
|
|
230
|
+
const { driver, driverKey } = resolveKey(key);
|
|
231
|
+
await removeItem(driver, driverKey, opts);
|
|
232
|
+
},
|
|
233
|
+
removeItems: async (keys) => {
|
|
234
|
+
const areaToKeysMap = {};
|
|
235
|
+
keys.forEach((key) => {
|
|
236
|
+
let keyStr;
|
|
237
|
+
let opts;
|
|
238
|
+
if (typeof key === "string") {
|
|
239
|
+
keyStr = key;
|
|
240
|
+
} else if ("getValue" in key) {
|
|
241
|
+
keyStr = key.key;
|
|
242
|
+
} else if ("item" in key) {
|
|
243
|
+
keyStr = key.item.key;
|
|
244
|
+
opts = key.options;
|
|
245
|
+
} else {
|
|
246
|
+
keyStr = key.key;
|
|
247
|
+
opts = key.options;
|
|
248
|
+
}
|
|
249
|
+
const { driverArea, driverKey } = resolveKey(keyStr);
|
|
250
|
+
areaToKeysMap[driverArea] ?? (areaToKeysMap[driverArea] = []);
|
|
251
|
+
areaToKeysMap[driverArea].push(driverKey);
|
|
252
|
+
if (opts?.removeMeta) {
|
|
253
|
+
areaToKeysMap[driverArea].push(getMetaKey(driverKey));
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
await Promise.all(
|
|
257
|
+
Object.entries(areaToKeysMap).map(async ([driverArea, keys2]) => {
|
|
258
|
+
const driver = getDriver(driverArea);
|
|
259
|
+
await driver.removeItems(keys2);
|
|
260
|
+
})
|
|
261
|
+
);
|
|
262
|
+
},
|
|
263
|
+
removeMeta: async (key, properties) => {
|
|
264
|
+
const { driver, driverKey } = resolveKey(key);
|
|
265
|
+
await removeMeta(driver, driverKey, properties);
|
|
266
|
+
},
|
|
267
|
+
snapshot: async (base, opts) => {
|
|
268
|
+
const driver = getDriver(base);
|
|
269
|
+
const data = await driver.snapshot();
|
|
270
|
+
opts?.excludeKeys?.forEach((key) => {
|
|
271
|
+
delete data[key];
|
|
272
|
+
delete data[getMetaKey(key)];
|
|
273
|
+
});
|
|
274
|
+
return data;
|
|
275
|
+
},
|
|
276
|
+
restoreSnapshot: async (base, data) => {
|
|
277
|
+
const driver = getDriver(base);
|
|
278
|
+
await driver.restoreSnapshot(data);
|
|
279
|
+
},
|
|
280
|
+
watch: (key, cb) => {
|
|
281
|
+
const { driver, driverKey } = resolveKey(key);
|
|
282
|
+
return watch(driver, driverKey, cb);
|
|
283
|
+
},
|
|
284
|
+
unwatch() {
|
|
285
|
+
Object.values(drivers).forEach((driver) => {
|
|
286
|
+
driver.unwatch();
|
|
287
|
+
});
|
|
288
|
+
},
|
|
289
|
+
defineItem: (key, opts) => {
|
|
290
|
+
const { driver, driverKey } = resolveKey(key);
|
|
291
|
+
const { version: targetVersion = 1, migrations = {} } = opts ?? {};
|
|
292
|
+
if (targetVersion < 1) {
|
|
293
|
+
throw Error(
|
|
294
|
+
"Storage item version cannot be less than 1. Initial versions should be set to 1, not 0."
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
const migrate = async () => {
|
|
298
|
+
const driverMetaKey = getMetaKey(driverKey);
|
|
299
|
+
const [{ value }, { value: meta }] = await driver.getItems([
|
|
300
|
+
driverKey,
|
|
301
|
+
driverMetaKey
|
|
302
|
+
]);
|
|
303
|
+
if (value == null)
|
|
304
|
+
return;
|
|
305
|
+
const currentVersion = meta?.v ?? 1;
|
|
306
|
+
if (currentVersion > targetVersion) {
|
|
307
|
+
throw Error(
|
|
308
|
+
`Version downgrade detected (v${currentVersion} -> v${targetVersion}) for "${key}"`
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
console.debug(
|
|
312
|
+
`[@wxt-dev/storage] Running storage migration for ${key}: v${currentVersion} -> v${targetVersion}`
|
|
313
|
+
);
|
|
314
|
+
const migrationsToRun = Array.from(
|
|
315
|
+
{ length: targetVersion - currentVersion },
|
|
316
|
+
(_, i) => currentVersion + i + 1
|
|
317
|
+
);
|
|
318
|
+
let migratedValue = value;
|
|
319
|
+
for (const migrateToVersion of migrationsToRun) {
|
|
320
|
+
try {
|
|
321
|
+
migratedValue = await migrations?.[migrateToVersion]?.(migratedValue) ?? migratedValue;
|
|
322
|
+
} catch (err) {
|
|
323
|
+
throw Error(`v${migrateToVersion} migration failed for "${key}"`, {
|
|
324
|
+
cause: err
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
await driver.setItems([
|
|
329
|
+
{ key: driverKey, value: migratedValue },
|
|
330
|
+
{ key: driverMetaKey, value: { ...meta, v: targetVersion } }
|
|
331
|
+
]);
|
|
332
|
+
console.debug(
|
|
333
|
+
`[@wxt-dev/storage] Storage migration completed for ${key} v${targetVersion}`,
|
|
334
|
+
{ migratedValue }
|
|
335
|
+
);
|
|
336
|
+
};
|
|
337
|
+
const migrationsDone = opts?.migrations == null ? Promise.resolve() : migrate().catch((err) => {
|
|
338
|
+
console.error(
|
|
339
|
+
`[@wxt-dev/storage] Migration failed for ${key}`,
|
|
340
|
+
err
|
|
341
|
+
);
|
|
342
|
+
});
|
|
343
|
+
const initMutex = new Mutex();
|
|
344
|
+
const getFallback = () => opts?.fallback ?? opts?.defaultValue ?? null;
|
|
345
|
+
const getOrInitValue = () => initMutex.runExclusive(async () => {
|
|
346
|
+
const value = await driver.getItem(driverKey);
|
|
347
|
+
if (value != null || opts?.init == null)
|
|
348
|
+
return value;
|
|
349
|
+
const newValue = await opts.init();
|
|
350
|
+
await driver.setItem(driverKey, newValue);
|
|
351
|
+
return newValue;
|
|
352
|
+
});
|
|
353
|
+
migrationsDone.then(getOrInitValue);
|
|
354
|
+
return {
|
|
355
|
+
key,
|
|
356
|
+
get defaultValue() {
|
|
357
|
+
return getFallback();
|
|
358
|
+
},
|
|
359
|
+
get fallback() {
|
|
360
|
+
return getFallback();
|
|
361
|
+
},
|
|
362
|
+
getValue: async () => {
|
|
363
|
+
await migrationsDone;
|
|
364
|
+
if (opts?.init) {
|
|
365
|
+
return await getOrInitValue();
|
|
366
|
+
} else {
|
|
367
|
+
return await getItem(driver, driverKey, opts);
|
|
368
|
+
}
|
|
369
|
+
},
|
|
370
|
+
getMeta: async () => {
|
|
371
|
+
await migrationsDone;
|
|
372
|
+
return await getMeta(driver, driverKey);
|
|
373
|
+
},
|
|
374
|
+
setValue: async (value) => {
|
|
375
|
+
await migrationsDone;
|
|
376
|
+
return await setItem(driver, driverKey, value);
|
|
377
|
+
},
|
|
378
|
+
setMeta: async (properties) => {
|
|
379
|
+
await migrationsDone;
|
|
380
|
+
return await setMeta(driver, driverKey, properties);
|
|
381
|
+
},
|
|
382
|
+
removeValue: async (opts2) => {
|
|
383
|
+
await migrationsDone;
|
|
384
|
+
return await removeItem(driver, driverKey, opts2);
|
|
385
|
+
},
|
|
386
|
+
removeMeta: async (properties) => {
|
|
387
|
+
await migrationsDone;
|
|
388
|
+
return await removeMeta(driver, driverKey, properties);
|
|
389
|
+
},
|
|
390
|
+
watch: (cb) => watch(
|
|
391
|
+
driver,
|
|
392
|
+
driverKey,
|
|
393
|
+
(newValue, oldValue) => cb(newValue ?? getFallback(), oldValue ?? getFallback())
|
|
394
|
+
),
|
|
395
|
+
migrate
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
return storage2;
|
|
400
|
+
}
|
|
401
|
+
function createDriver(storageArea) {
|
|
402
|
+
const getStorageArea = () => {
|
|
403
|
+
if (chrome.runtime == null) {
|
|
404
|
+
throw Error(
|
|
405
|
+
[
|
|
406
|
+
"'wxt/storage' must be loaded in a web extension environment",
|
|
407
|
+
"\n - If thrown during a build, see https://github.com/wxt-dev/wxt/issues/371",
|
|
408
|
+
" - If thrown during tests, mock 'wxt/browser' correctly. See https://wxt.dev/guide/go-further/testing.html\n"
|
|
409
|
+
].join("\n")
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
if (chrome.storage == null) {
|
|
413
|
+
throw Error(
|
|
414
|
+
"You must add the 'storage' permission to your manifest to use 'wxt/storage'"
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
const area = chrome.storage[storageArea];
|
|
418
|
+
if (area == null)
|
|
419
|
+
throw Error(`"chrome.storage.${storageArea}" is undefined`);
|
|
420
|
+
return area;
|
|
421
|
+
};
|
|
422
|
+
const watchListeners = /* @__PURE__ */ new Set();
|
|
423
|
+
return {
|
|
424
|
+
getItem: async (key) => {
|
|
425
|
+
const res = await getStorageArea().get(key);
|
|
426
|
+
return res[key];
|
|
427
|
+
},
|
|
428
|
+
getItems: async (keys) => {
|
|
429
|
+
const result = await getStorageArea().get(keys);
|
|
430
|
+
return keys.map((key) => ({ key, value: result[key] ?? null }));
|
|
431
|
+
},
|
|
432
|
+
setItem: async (key, value) => {
|
|
433
|
+
if (value == null) {
|
|
434
|
+
await getStorageArea().remove(key);
|
|
435
|
+
} else {
|
|
436
|
+
await getStorageArea().set({ [key]: value });
|
|
437
|
+
}
|
|
438
|
+
},
|
|
439
|
+
setItems: async (values) => {
|
|
440
|
+
const map = values.reduce(
|
|
441
|
+
(map2, { key, value }) => {
|
|
442
|
+
map2[key] = value;
|
|
443
|
+
return map2;
|
|
444
|
+
},
|
|
445
|
+
{}
|
|
446
|
+
);
|
|
447
|
+
await getStorageArea().set(map);
|
|
448
|
+
},
|
|
449
|
+
removeItem: async (key) => {
|
|
450
|
+
await getStorageArea().remove(key);
|
|
451
|
+
},
|
|
452
|
+
removeItems: async (keys) => {
|
|
453
|
+
await getStorageArea().remove(keys);
|
|
454
|
+
},
|
|
455
|
+
snapshot: async () => {
|
|
456
|
+
return await getStorageArea().get();
|
|
457
|
+
},
|
|
458
|
+
restoreSnapshot: async (data) => {
|
|
459
|
+
await getStorageArea().set(data);
|
|
460
|
+
},
|
|
461
|
+
watch(key, cb) {
|
|
462
|
+
const listener = (changes) => {
|
|
463
|
+
const change = changes[key];
|
|
464
|
+
if (change == null)
|
|
465
|
+
return;
|
|
466
|
+
if (dequal(change.newValue, change.oldValue))
|
|
467
|
+
return;
|
|
468
|
+
cb(change.newValue ?? null, change.oldValue ?? null);
|
|
469
|
+
};
|
|
470
|
+
getStorageArea().onChanged.addListener(listener);
|
|
471
|
+
watchListeners.add(listener);
|
|
472
|
+
return () => {
|
|
473
|
+
getStorageArea().onChanged.removeListener(listener);
|
|
474
|
+
watchListeners.delete(listener);
|
|
475
|
+
};
|
|
476
|
+
},
|
|
477
|
+
unwatch() {
|
|
478
|
+
watchListeners.forEach((listener) => {
|
|
479
|
+
getStorageArea().onChanged.removeListener(listener);
|
|
480
|
+
});
|
|
481
|
+
watchListeners.clear();
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
class MigrationError extends Error {
|
|
486
|
+
constructor(key, version, options) {
|
|
487
|
+
super(`v${version} migration failed for "${key}"`, options);
|
|
488
|
+
this.key = key;
|
|
489
|
+
this.version = version;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export { MigrationError, storage };
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@wxt-dev/storage",
|
|
3
|
+
"description": "Web extension storage API provided by WXT, supports all browsers.",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/wxt-dev/wxt.git",
|
|
9
|
+
"directory": "packages/storage"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://wxt.dev/storage.html",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"wxt",
|
|
14
|
+
"storage",
|
|
15
|
+
"extension",
|
|
16
|
+
"addon",
|
|
17
|
+
"chrome",
|
|
18
|
+
"firefox",
|
|
19
|
+
"edge"
|
|
20
|
+
],
|
|
21
|
+
"author": {
|
|
22
|
+
"name": "Aaron Klinker",
|
|
23
|
+
"email": "aaronklinker1+wxt@gmail.com"
|
|
24
|
+
},
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"async-mutex": "^0.5.0",
|
|
28
|
+
"dequal": "^2.0.3"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@aklinker1/check": "^1.4.5",
|
|
32
|
+
"@types/chrome": "^0.0.268",
|
|
33
|
+
"@webext-core/fake-browser": "^1.3.1",
|
|
34
|
+
"oxlint": "^0.9.9",
|
|
35
|
+
"publint": "^0.2.11",
|
|
36
|
+
"typescript": "^5.6.2",
|
|
37
|
+
"unbuild": "^2.0.0",
|
|
38
|
+
"vitest": "^2.0.0"
|
|
39
|
+
},
|
|
40
|
+
"module": "./dist/index.mjs",
|
|
41
|
+
"types": "./dist/index.d.ts",
|
|
42
|
+
"exports": {
|
|
43
|
+
".": {
|
|
44
|
+
"types": "./dist/index.d.mts",
|
|
45
|
+
"import": "./dist/index.mjs"
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"files": [
|
|
49
|
+
"dist"
|
|
50
|
+
],
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "buildc -- unbuild",
|
|
53
|
+
"check": "buildc --deps-only -- check",
|
|
54
|
+
"test": "buildc --deps-only -- vitest"
|
|
55
|
+
}
|
|
56
|
+
}
|