@metamask-previews/storage-service 1.0.0-preview-81c9cf83 → 1.0.0-preview-dcbbb24
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/CHANGELOG.md +16 -2
- package/README.md +23 -7
- package/dist/InMemoryStorageAdapter.cjs +39 -20
- package/dist/InMemoryStorageAdapter.cjs.map +1 -1
- package/dist/InMemoryStorageAdapter.d.cts +28 -11
- package/dist/InMemoryStorageAdapter.d.cts.map +1 -1
- package/dist/InMemoryStorageAdapter.d.mts +28 -11
- package/dist/InMemoryStorageAdapter.d.mts.map +1 -1
- package/dist/InMemoryStorageAdapter.mjs +39 -20
- package/dist/InMemoryStorageAdapter.mjs.map +1 -1
- package/dist/StorageService-method-action-types.cjs.map +1 -1
- package/dist/StorageService-method-action-types.d.cts +4 -7
- package/dist/StorageService-method-action-types.d.cts.map +1 -1
- package/dist/StorageService-method-action-types.d.mts +4 -7
- package/dist/StorageService-method-action-types.d.mts.map +1 -1
- package/dist/StorageService-method-action-types.mjs.map +1 -1
- package/dist/StorageService.cjs +12 -12
- package/dist/StorageService.cjs.map +1 -1
- package/dist/StorageService.d.cts +14 -13
- package/dist/StorageService.d.cts.map +1 -1
- package/dist/StorageService.d.mts +14 -13
- package/dist/StorageService.d.mts.map +1 -1
- package/dist/StorageService.mjs +12 -12
- package/dist/StorageService.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +47 -9
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +47 -9
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +6 -7
package/CHANGELOG.md
CHANGED
|
@@ -7,8 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.0.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Add optional `initialData` parameter to `InMemoryStorageAdapter` constructor for pre-populating storage during tests ([#7791](https://github.com/MetaMask/core/pull/7791))
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Upgrade `@metamask/utils` from `^11.8.1` to `^11.9.0` ([#7511](https://github.com/MetaMask/core/pull/7511))
|
|
19
|
+
|
|
20
|
+
## [0.0.1]
|
|
21
|
+
|
|
10
22
|
### Added
|
|
11
23
|
|
|
12
|
-
- Initial release of `@metamask/storage-service`
|
|
24
|
+
- Initial release of `@metamask/storage-service` ([#7192](https://github.com/MetaMask/core/pull/7192))
|
|
13
25
|
|
|
14
|
-
[Unreleased]: https://github.com/MetaMask/core/
|
|
26
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/storage-service@1.0.0...HEAD
|
|
27
|
+
[1.0.0]: https://github.com/MetaMask/core/compare/@metamask/storage-service@0.0.1...@metamask/storage-service@1.0.0
|
|
28
|
+
[0.0.1]: https://github.com/MetaMask/core/releases/tag/@metamask/storage-service@0.0.1
|
package/README.md
CHANGED
|
@@ -5,12 +5,14 @@ A platform-agnostic service for storing large, infrequently accessed controller
|
|
|
5
5
|
## When to Use
|
|
6
6
|
|
|
7
7
|
✅ **Use StorageService for:**
|
|
8
|
+
|
|
8
9
|
- Large data (> 100 KB)
|
|
9
10
|
- Infrequently accessed data
|
|
10
11
|
- Data that doesn't need to be in Redux state
|
|
11
12
|
- Examples: Snap source code, cached API responses
|
|
12
13
|
|
|
13
14
|
❌ **Don't use for:**
|
|
15
|
+
|
|
14
16
|
- Frequently accessed data (use controller state)
|
|
15
17
|
- Small data (< 10 KB - overhead not worth it)
|
|
16
18
|
- Data needed for UI rendering
|
|
@@ -48,12 +50,17 @@ class MyController extends BaseController<...> {
|
|
|
48
50
|
);
|
|
49
51
|
}
|
|
50
52
|
|
|
51
|
-
async getData(id: string): Promise<
|
|
52
|
-
|
|
53
|
+
async getData(id: string): Promise<string | undefined> {
|
|
54
|
+
const { result, error } = await this.messenger.call(
|
|
53
55
|
'StorageService:getItem',
|
|
54
56
|
'MyController',
|
|
55
57
|
`${id}:data`,
|
|
56
58
|
);
|
|
59
|
+
if (error) {
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
// result is undefined if key doesn't exist
|
|
63
|
+
return result as string | undefined;
|
|
57
64
|
}
|
|
58
65
|
}
|
|
59
66
|
```
|
|
@@ -85,7 +92,7 @@ Subscribe to storage changes:
|
|
|
85
92
|
```typescript
|
|
86
93
|
this.messenger.subscribe(
|
|
87
94
|
'StorageService:itemSet:MyController',
|
|
88
|
-
(
|
|
95
|
+
(key, value) => {
|
|
89
96
|
console.log(`Data stored: ${key}`);
|
|
90
97
|
},
|
|
91
98
|
);
|
|
@@ -96,9 +103,17 @@ this.messenger.subscribe(
|
|
|
96
103
|
Implement this interface to provide platform-specific storage:
|
|
97
104
|
|
|
98
105
|
```typescript
|
|
106
|
+
import type { Json } from '@metamask/utils';
|
|
107
|
+
|
|
108
|
+
// Response type for getItem - distinguishes found, not found, and error
|
|
109
|
+
type StorageGetResult =
|
|
110
|
+
| { result: Json; error?: never } // Data found
|
|
111
|
+
| { result?: never; error: Error } // Error occurred
|
|
112
|
+
| Record<string, never>; // Key doesn't exist (empty object)
|
|
113
|
+
|
|
99
114
|
export type StorageAdapter = {
|
|
100
|
-
getItem(namespace: string, key: string): Promise<
|
|
101
|
-
setItem(namespace: string, key: string, value:
|
|
115
|
+
getItem(namespace: string, key: string): Promise<StorageGetResult>;
|
|
116
|
+
setItem(namespace: string, key: string, value: Json): Promise<void>;
|
|
102
117
|
removeItem(namespace: string, key: string): Promise<void>;
|
|
103
118
|
getAllKeys(namespace: string): Promise<string[]>;
|
|
104
119
|
clear(namespace: string): Promise<void>;
|
|
@@ -106,9 +121,10 @@ export type StorageAdapter = {
|
|
|
106
121
|
```
|
|
107
122
|
|
|
108
123
|
Adapters are responsible for:
|
|
124
|
+
|
|
109
125
|
- Building the full storage key (e.g., `storageService:namespace:key`)
|
|
110
|
-
-
|
|
111
|
-
-
|
|
126
|
+
- Serializing/deserializing JSON data
|
|
127
|
+
- Returning the correct response format for getItem
|
|
112
128
|
|
|
113
129
|
## Contributing
|
|
114
130
|
|
|
@@ -29,66 +29,85 @@ const types_1 = require("./types.cjs");
|
|
|
29
29
|
* - Production (unless data is truly ephemeral)
|
|
30
30
|
* - Data that needs to persist across restarts
|
|
31
31
|
*
|
|
32
|
-
* @example
|
|
32
|
+
* @example Basic usage
|
|
33
33
|
* ```typescript
|
|
34
34
|
* const adapter = new InMemoryStorageAdapter();
|
|
35
|
-
* await adapter.setItem('
|
|
36
|
-
* const value = await adapter.getItem('
|
|
35
|
+
* await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');
|
|
36
|
+
* const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'
|
|
37
37
|
* // After restart: data is lost
|
|
38
38
|
* ```
|
|
39
|
+
*
|
|
40
|
+
* @example Initialize with data (useful for testing)
|
|
41
|
+
* ```typescript
|
|
42
|
+
* const adapter = new InMemoryStorageAdapter({
|
|
43
|
+
* SnapController: {
|
|
44
|
+
* 'snap-id:sourceCode': 'const x = 1;',
|
|
45
|
+
* 'snap-id:manifest': { name: 'My Snap' },
|
|
46
|
+
* },
|
|
47
|
+
* TokenListController: {
|
|
48
|
+
* cache: { '0x1': ['token1', 'token2'] },
|
|
49
|
+
* },
|
|
50
|
+
* });
|
|
51
|
+
* ```
|
|
39
52
|
*/
|
|
40
53
|
class InMemoryStorageAdapter {
|
|
41
54
|
/**
|
|
42
55
|
* Constructs a new InMemoryStorageAdapter.
|
|
56
|
+
*
|
|
57
|
+
* @param initialData - Optional initial data to populate the storage.
|
|
58
|
+
* Useful for setting up test fixtures without calling setItem multiple times.
|
|
43
59
|
*/
|
|
44
|
-
constructor() {
|
|
60
|
+
constructor(initialData) {
|
|
45
61
|
// Explicitly implement StorageAdapter interface
|
|
46
62
|
/**
|
|
47
63
|
* Internal storage map.
|
|
48
64
|
*/
|
|
49
65
|
_InMemoryStorageAdapter_storage.set(this, void 0);
|
|
50
66
|
__classPrivateFieldSet(this, _InMemoryStorageAdapter_storage, new Map(), "f");
|
|
67
|
+
if (initialData) {
|
|
68
|
+
for (const [namespace, items] of Object.entries(initialData)) {
|
|
69
|
+
for (const [key, value] of Object.entries(items)) {
|
|
70
|
+
const fullKey = `${types_1.STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
71
|
+
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").set(fullKey, JSON.stringify(value));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
51
75
|
}
|
|
52
76
|
/**
|
|
53
77
|
* Retrieve an item from in-memory storage.
|
|
54
|
-
* Deserializes
|
|
78
|
+
* Deserializes JSON data from storage.
|
|
55
79
|
*
|
|
56
80
|
* @param namespace - The controller namespace.
|
|
57
81
|
* @param key - The data key.
|
|
58
|
-
* @returns
|
|
82
|
+
* @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.
|
|
59
83
|
*/
|
|
60
84
|
async getItem(namespace, key) {
|
|
61
85
|
const fullKey = `${types_1.STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
62
86
|
const serialized = __classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").get(fullKey);
|
|
63
|
-
|
|
64
|
-
|
|
87
|
+
// Key not found - return empty object
|
|
88
|
+
if (serialized === undefined) {
|
|
89
|
+
return {};
|
|
65
90
|
}
|
|
66
91
|
try {
|
|
67
|
-
const
|
|
68
|
-
return
|
|
92
|
+
const result = JSON.parse(serialized);
|
|
93
|
+
return { result };
|
|
69
94
|
}
|
|
70
95
|
catch (error) {
|
|
71
|
-
// istanbul ignore next - defensive error handling for corrupted data
|
|
72
96
|
console.error(`Failed to parse stored data for ${fullKey}:`, error);
|
|
73
|
-
|
|
74
|
-
return null;
|
|
97
|
+
return { error: error };
|
|
75
98
|
}
|
|
76
99
|
}
|
|
77
100
|
/**
|
|
78
101
|
* Store an item in in-memory storage.
|
|
79
|
-
*
|
|
102
|
+
* Serializes JSON data to string.
|
|
80
103
|
*
|
|
81
104
|
* @param namespace - The controller namespace.
|
|
82
105
|
* @param key - The data key.
|
|
83
|
-
* @param value - The value to store
|
|
106
|
+
* @param value - The JSON value to store.
|
|
84
107
|
*/
|
|
85
108
|
async setItem(namespace, key, value) {
|
|
86
109
|
const fullKey = `${types_1.STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
87
|
-
|
|
88
|
-
timestamp: Date.now(),
|
|
89
|
-
data: value,
|
|
90
|
-
};
|
|
91
|
-
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").set(fullKey, JSON.stringify(wrapper));
|
|
110
|
+
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").set(fullKey, JSON.stringify(value));
|
|
92
111
|
}
|
|
93
112
|
/**
|
|
94
113
|
* Remove an item from in-memory storage.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InMemoryStorageAdapter.cjs","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"InMemoryStorageAdapter.cjs","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA,uCAA6C;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAa,sBAAsB;IAOjC;;;;;OAKG;IACH,YAAY,WAAgC;QAZ5C,gDAAgD;QAChD;;WAEG;QACM,kDAA8B;QASrC,uBAAA,IAAI,mCAAY,IAAI,GAAG,EAAE,MAAA,CAAC;QAE1B,IAAI,WAAW,EAAE,CAAC;YAChB,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apter,\n StorageGetResult,\n} from './types';\nimport { STORAGE_KEY_PREFIX } from './types';\n\n/**\n * In-memory storage adapter (default fallback).\n * Implements the {@link StorageAdapter} interface using a Map.\n *\n * ⚠️ **Warning**: Data is NOT persisted - lost on restart.\n *\n * **Suitable for:**\n * - Testing (isolated, no mocking needed)\n * - Development (quick start, zero config)\n * - Temporary/ephemeral data\n *\n * **Not suitable for:**\n * - Production (unless data is truly ephemeral)\n * - Data that needs to persist across restarts\n *\n * @example Basic usage\n * ```typescript\n * const adapter = new InMemoryStorageAdapter();\n * await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');\n * const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'\n * // After restart: data is lost\n * ```\n *\n * @example Initialize with data (useful for testing)\n * ```typescript\n * const adapter = new InMemoryStorageAdapter({\n * SnapController: {\n * 'snap-id:sourceCode': 'const x = 1;',\n * 'snap-id:manifest': { name: 'My Snap' },\n * },\n * TokenListController: {\n * cache: { '0x1': ['token1', 'token2'] },\n * },\n * });\n * ```\n */\nexport class InMemoryStorageAdapter implements StorageAdapter {\n // Explicitly implement StorageAdapter interface\n /**\n * Internal storage map.\n */\n readonly #storage: Map<string, string>;\n\n /**\n * Constructs a new InMemoryStorageAdapter.\n *\n * @param initialData - Optional initial data to populate the storage.\n * Useful for setting up test fixtures without calling setItem multiple times.\n */\n constructor(initialData?: InitialStorageData) {\n this.#storage = new Map();\n\n if (initialData) {\n for (const [namespace, items] of Object.entries(initialData)) {\n for (const [key, value] of Object.entries(items)) {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.set(fullKey, JSON.stringify(value));\n }\n }\n }\n }\n\n /**\n * Retrieve an item from in-memory storage.\n * Deserializes JSON data from storage.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n * @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.\n */\n async getItem(namespace: string, key: string): Promise<StorageGetResult> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n const serialized = this.#storage.get(fullKey);\n\n // Key not found - return empty object\n if (serialized === undefined) {\n return {};\n }\n\n try {\n const result = JSON.parse(serialized);\n return { result };\n } catch (error) {\n console.error(`Failed to parse stored data for ${fullKey}:`, error);\n return { error: error as Error };\n }\n }\n\n /**\n * Store an item in in-memory storage.\n * Serializes JSON data to string.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n * @param value - The JSON value to store.\n */\n async setItem(namespace: string, key: string, value: Json): Promise<void> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.set(fullKey, JSON.stringify(value));\n }\n\n /**\n * Remove an item from in-memory storage.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n */\n async removeItem(namespace: string, key: string): Promise<void> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.delete(fullKey);\n }\n\n /**\n * Get all keys for a namespace.\n * Returns keys without the 'storage:namespace:' prefix.\n *\n * @param namespace - The namespace to get keys for.\n * @returns Array of keys (without prefix) for this namespace.\n */\n async getAllKeys(namespace: string): Promise<string[]> {\n const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;\n return Array.from(this.#storage.keys())\n .filter((key) => key.startsWith(prefix))\n .map((key) => key.slice(prefix.length));\n }\n\n /**\n * Clear all items for a namespace.\n *\n * @param namespace - The namespace to clear.\n */\n async clear(namespace: string): Promise<void> {\n const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;\n const keysToDelete = Array.from(this.#storage.keys()).filter((key) =>\n key.startsWith(prefix),\n );\n keysToDelete.forEach((key) => this.#storage.delete(key));\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Json } from "@metamask/utils";
|
|
2
|
+
import type { InitialStorageData, StorageAdapter, StorageGetResult } from "./types.cjs";
|
|
2
3
|
/**
|
|
3
4
|
* In-memory storage adapter (default fallback).
|
|
4
5
|
* Implements the {@link StorageAdapter} interface using a Map.
|
|
@@ -14,38 +15,54 @@ import type { StorageAdapter } from "./types.cjs";
|
|
|
14
15
|
* - Production (unless data is truly ephemeral)
|
|
15
16
|
* - Data that needs to persist across restarts
|
|
16
17
|
*
|
|
17
|
-
* @example
|
|
18
|
+
* @example Basic usage
|
|
18
19
|
* ```typescript
|
|
19
20
|
* const adapter = new InMemoryStorageAdapter();
|
|
20
|
-
* await adapter.setItem('
|
|
21
|
-
* const value = await adapter.getItem('
|
|
21
|
+
* await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');
|
|
22
|
+
* const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'
|
|
22
23
|
* // After restart: data is lost
|
|
23
24
|
* ```
|
|
25
|
+
*
|
|
26
|
+
* @example Initialize with data (useful for testing)
|
|
27
|
+
* ```typescript
|
|
28
|
+
* const adapter = new InMemoryStorageAdapter({
|
|
29
|
+
* SnapController: {
|
|
30
|
+
* 'snap-id:sourceCode': 'const x = 1;',
|
|
31
|
+
* 'snap-id:manifest': { name: 'My Snap' },
|
|
32
|
+
* },
|
|
33
|
+
* TokenListController: {
|
|
34
|
+
* cache: { '0x1': ['token1', 'token2'] },
|
|
35
|
+
* },
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
24
38
|
*/
|
|
25
39
|
export declare class InMemoryStorageAdapter implements StorageAdapter {
|
|
26
40
|
#private;
|
|
27
41
|
/**
|
|
28
42
|
* Constructs a new InMemoryStorageAdapter.
|
|
43
|
+
*
|
|
44
|
+
* @param initialData - Optional initial data to populate the storage.
|
|
45
|
+
* Useful for setting up test fixtures without calling setItem multiple times.
|
|
29
46
|
*/
|
|
30
|
-
constructor();
|
|
47
|
+
constructor(initialData?: InitialStorageData);
|
|
31
48
|
/**
|
|
32
49
|
* Retrieve an item from in-memory storage.
|
|
33
|
-
* Deserializes
|
|
50
|
+
* Deserializes JSON data from storage.
|
|
34
51
|
*
|
|
35
52
|
* @param namespace - The controller namespace.
|
|
36
53
|
* @param key - The data key.
|
|
37
|
-
* @returns
|
|
54
|
+
* @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.
|
|
38
55
|
*/
|
|
39
|
-
getItem(namespace: string, key: string): Promise<
|
|
56
|
+
getItem(namespace: string, key: string): Promise<StorageGetResult>;
|
|
40
57
|
/**
|
|
41
58
|
* Store an item in in-memory storage.
|
|
42
|
-
*
|
|
59
|
+
* Serializes JSON data to string.
|
|
43
60
|
*
|
|
44
61
|
* @param namespace - The controller namespace.
|
|
45
62
|
* @param key - The data key.
|
|
46
|
-
* @param value - The value to store
|
|
63
|
+
* @param value - The JSON value to store.
|
|
47
64
|
*/
|
|
48
|
-
setItem(namespace: string, key: string, value:
|
|
65
|
+
setItem(namespace: string, key: string, value: Json): Promise<void>;
|
|
49
66
|
/**
|
|
50
67
|
* Remove an item from in-memory storage.
|
|
51
68
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InMemoryStorageAdapter.d.cts","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"InMemoryStorageAdapter.d.cts","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C,OAAO,KAAK,EACV,kBAAkB,EAClB,cAAc,EACd,gBAAgB,EACjB,oBAAgB;AAGjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,sBAAuB,YAAW,cAAc;;IAO3D;;;;;OAKG;gBACS,WAAW,CAAC,EAAE,kBAAkB;IAa5C;;;;;;;OAOG;IACG,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAkBxE;;;;;;;OAOG;IACG,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKzE;;;;;OAKG;IACG,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK/D;;;;;;OAMG;IACG,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAOtD;;;;OAIG;IACG,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAO9C"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Json } from "@metamask/utils";
|
|
2
|
+
import type { InitialStorageData, StorageAdapter, StorageGetResult } from "./types.mjs";
|
|
2
3
|
/**
|
|
3
4
|
* In-memory storage adapter (default fallback).
|
|
4
5
|
* Implements the {@link StorageAdapter} interface using a Map.
|
|
@@ -14,38 +15,54 @@ import type { StorageAdapter } from "./types.mjs";
|
|
|
14
15
|
* - Production (unless data is truly ephemeral)
|
|
15
16
|
* - Data that needs to persist across restarts
|
|
16
17
|
*
|
|
17
|
-
* @example
|
|
18
|
+
* @example Basic usage
|
|
18
19
|
* ```typescript
|
|
19
20
|
* const adapter = new InMemoryStorageAdapter();
|
|
20
|
-
* await adapter.setItem('
|
|
21
|
-
* const value = await adapter.getItem('
|
|
21
|
+
* await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');
|
|
22
|
+
* const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'
|
|
22
23
|
* // After restart: data is lost
|
|
23
24
|
* ```
|
|
25
|
+
*
|
|
26
|
+
* @example Initialize with data (useful for testing)
|
|
27
|
+
* ```typescript
|
|
28
|
+
* const adapter = new InMemoryStorageAdapter({
|
|
29
|
+
* SnapController: {
|
|
30
|
+
* 'snap-id:sourceCode': 'const x = 1;',
|
|
31
|
+
* 'snap-id:manifest': { name: 'My Snap' },
|
|
32
|
+
* },
|
|
33
|
+
* TokenListController: {
|
|
34
|
+
* cache: { '0x1': ['token1', 'token2'] },
|
|
35
|
+
* },
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
24
38
|
*/
|
|
25
39
|
export declare class InMemoryStorageAdapter implements StorageAdapter {
|
|
26
40
|
#private;
|
|
27
41
|
/**
|
|
28
42
|
* Constructs a new InMemoryStorageAdapter.
|
|
43
|
+
*
|
|
44
|
+
* @param initialData - Optional initial data to populate the storage.
|
|
45
|
+
* Useful for setting up test fixtures without calling setItem multiple times.
|
|
29
46
|
*/
|
|
30
|
-
constructor();
|
|
47
|
+
constructor(initialData?: InitialStorageData);
|
|
31
48
|
/**
|
|
32
49
|
* Retrieve an item from in-memory storage.
|
|
33
|
-
* Deserializes
|
|
50
|
+
* Deserializes JSON data from storage.
|
|
34
51
|
*
|
|
35
52
|
* @param namespace - The controller namespace.
|
|
36
53
|
* @param key - The data key.
|
|
37
|
-
* @returns
|
|
54
|
+
* @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.
|
|
38
55
|
*/
|
|
39
|
-
getItem(namespace: string, key: string): Promise<
|
|
56
|
+
getItem(namespace: string, key: string): Promise<StorageGetResult>;
|
|
40
57
|
/**
|
|
41
58
|
* Store an item in in-memory storage.
|
|
42
|
-
*
|
|
59
|
+
* Serializes JSON data to string.
|
|
43
60
|
*
|
|
44
61
|
* @param namespace - The controller namespace.
|
|
45
62
|
* @param key - The data key.
|
|
46
|
-
* @param value - The value to store
|
|
63
|
+
* @param value - The JSON value to store.
|
|
47
64
|
*/
|
|
48
|
-
setItem(namespace: string, key: string, value:
|
|
65
|
+
setItem(namespace: string, key: string, value: Json): Promise<void>;
|
|
49
66
|
/**
|
|
50
67
|
* Remove an item from in-memory storage.
|
|
51
68
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InMemoryStorageAdapter.d.mts","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"InMemoryStorageAdapter.d.mts","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C,OAAO,KAAK,EACV,kBAAkB,EAClB,cAAc,EACd,gBAAgB,EACjB,oBAAgB;AAGjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,sBAAuB,YAAW,cAAc;;IAO3D;;;;;OAKG;gBACS,WAAW,CAAC,EAAE,kBAAkB;IAa5C;;;;;;;OAOG;IACG,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAkBxE;;;;;;;OAOG;IACG,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAKzE;;;;;OAKG;IACG,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK/D;;;;;;OAMG;IACG,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAOtD;;;;OAIG;IACG,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAO9C"}
|
|
@@ -26,66 +26,85 @@ import { STORAGE_KEY_PREFIX } from "./types.mjs";
|
|
|
26
26
|
* - Production (unless data is truly ephemeral)
|
|
27
27
|
* - Data that needs to persist across restarts
|
|
28
28
|
*
|
|
29
|
-
* @example
|
|
29
|
+
* @example Basic usage
|
|
30
30
|
* ```typescript
|
|
31
31
|
* const adapter = new InMemoryStorageAdapter();
|
|
32
|
-
* await adapter.setItem('
|
|
33
|
-
* const value = await adapter.getItem('
|
|
32
|
+
* await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');
|
|
33
|
+
* const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'
|
|
34
34
|
* // After restart: data is lost
|
|
35
35
|
* ```
|
|
36
|
+
*
|
|
37
|
+
* @example Initialize with data (useful for testing)
|
|
38
|
+
* ```typescript
|
|
39
|
+
* const adapter = new InMemoryStorageAdapter({
|
|
40
|
+
* SnapController: {
|
|
41
|
+
* 'snap-id:sourceCode': 'const x = 1;',
|
|
42
|
+
* 'snap-id:manifest': { name: 'My Snap' },
|
|
43
|
+
* },
|
|
44
|
+
* TokenListController: {
|
|
45
|
+
* cache: { '0x1': ['token1', 'token2'] },
|
|
46
|
+
* },
|
|
47
|
+
* });
|
|
48
|
+
* ```
|
|
36
49
|
*/
|
|
37
50
|
export class InMemoryStorageAdapter {
|
|
38
51
|
/**
|
|
39
52
|
* Constructs a new InMemoryStorageAdapter.
|
|
53
|
+
*
|
|
54
|
+
* @param initialData - Optional initial data to populate the storage.
|
|
55
|
+
* Useful for setting up test fixtures without calling setItem multiple times.
|
|
40
56
|
*/
|
|
41
|
-
constructor() {
|
|
57
|
+
constructor(initialData) {
|
|
42
58
|
// Explicitly implement StorageAdapter interface
|
|
43
59
|
/**
|
|
44
60
|
* Internal storage map.
|
|
45
61
|
*/
|
|
46
62
|
_InMemoryStorageAdapter_storage.set(this, void 0);
|
|
47
63
|
__classPrivateFieldSet(this, _InMemoryStorageAdapter_storage, new Map(), "f");
|
|
64
|
+
if (initialData) {
|
|
65
|
+
for (const [namespace, items] of Object.entries(initialData)) {
|
|
66
|
+
for (const [key, value] of Object.entries(items)) {
|
|
67
|
+
const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
68
|
+
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").set(fullKey, JSON.stringify(value));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
48
72
|
}
|
|
49
73
|
/**
|
|
50
74
|
* Retrieve an item from in-memory storage.
|
|
51
|
-
* Deserializes
|
|
75
|
+
* Deserializes JSON data from storage.
|
|
52
76
|
*
|
|
53
77
|
* @param namespace - The controller namespace.
|
|
54
78
|
* @param key - The data key.
|
|
55
|
-
* @returns
|
|
79
|
+
* @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.
|
|
56
80
|
*/
|
|
57
81
|
async getItem(namespace, key) {
|
|
58
82
|
const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
59
83
|
const serialized = __classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").get(fullKey);
|
|
60
|
-
|
|
61
|
-
|
|
84
|
+
// Key not found - return empty object
|
|
85
|
+
if (serialized === undefined) {
|
|
86
|
+
return {};
|
|
62
87
|
}
|
|
63
88
|
try {
|
|
64
|
-
const
|
|
65
|
-
return
|
|
89
|
+
const result = JSON.parse(serialized);
|
|
90
|
+
return { result };
|
|
66
91
|
}
|
|
67
92
|
catch (error) {
|
|
68
|
-
// istanbul ignore next - defensive error handling for corrupted data
|
|
69
93
|
console.error(`Failed to parse stored data for ${fullKey}:`, error);
|
|
70
|
-
|
|
71
|
-
return null;
|
|
94
|
+
return { error: error };
|
|
72
95
|
}
|
|
73
96
|
}
|
|
74
97
|
/**
|
|
75
98
|
* Store an item in in-memory storage.
|
|
76
|
-
*
|
|
99
|
+
* Serializes JSON data to string.
|
|
77
100
|
*
|
|
78
101
|
* @param namespace - The controller namespace.
|
|
79
102
|
* @param key - The data key.
|
|
80
|
-
* @param value - The value to store
|
|
103
|
+
* @param value - The JSON value to store.
|
|
81
104
|
*/
|
|
82
105
|
async setItem(namespace, key, value) {
|
|
83
106
|
const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;
|
|
84
|
-
|
|
85
|
-
timestamp: Date.now(),
|
|
86
|
-
data: value,
|
|
87
|
-
};
|
|
88
|
-
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").set(fullKey, JSON.stringify(wrapper));
|
|
107
|
+
__classPrivateFieldGet(this, _InMemoryStorageAdapter_storage, "f").set(fullKey, JSON.stringify(value));
|
|
89
108
|
}
|
|
90
109
|
/**
|
|
91
110
|
* Remove an item from in-memory storage.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InMemoryStorageAdapter.mjs","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":";;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"InMemoryStorageAdapter.mjs","sourceRoot":"","sources":["../src/InMemoryStorageAdapter.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,OAAO,EAAE,kBAAkB,EAAE,oBAAgB;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,OAAO,sBAAsB;IAOjC;;;;;OAKG;IACH,YAAY,WAAgC;QAZ5C,gDAAgD;QAChD;;WAEG;QACM,kDAA8B;QASrC,uBAAA,IAAI,mCAAY,IAAI,GAAG,EAAE,MAAA,CAAC;QAE1B,IAAI,WAAW,EAAE,CAAC;YAChB,KAAK,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,CAAC;gBAC7D,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;oBACjD,MAAM,OAAO,GAAG,GAAG,kBAAkB,GAAG,SAAS,IAAI,GAAG,EAAE,CAAC;oBAC3D,uBAAA,IAAI,uCAAS,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;gBACpD,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAW;QAC1C,MAAM,OAAO,GAAG,GAAG,kBAAkB,GAAG,SAAS,IAAI,G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G,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;aACvC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK,CAAC,SAAiB;QAC3B,MAAM,MAAM,GAAG,GAAG,kBAAkB,GAAG,SAAS,GAAG,CAAC;QACpD,MAAM,YAAY,GAAG,KAAK,CAAC,IAAI,CAAC,uBAAA,IAAI,uCAAS,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CACnE,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CACvB,CAAC;QACF,YAAY,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAA,IAAI,uCAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF","sourcesContent":["import type { Json } from '@metamask/utils';\n\nimport type {\n InitialStorageData,\n StorageAdapter,\n StorageGetResult,\n} from './types';\nimport { STORAGE_KEY_PREFIX } from './types';\n\n/**\n * In-memory storage adapter (default fallback).\n * Implements the {@link StorageAdapter} interface using a Map.\n *\n * ⚠️ **Warning**: Data is NOT persisted - lost on restart.\n *\n * **Suitable for:**\n * - Testing (isolated, no mocking needed)\n * - Development (quick start, zero config)\n * - Temporary/ephemeral data\n *\n * **Not suitable for:**\n * - Production (unless data is truly ephemeral)\n * - Data that needs to persist across restarts\n *\n * @example Basic usage\n * ```typescript\n * const adapter = new InMemoryStorageAdapter();\n * await adapter.setItem('SnapController', 'snap-id:sourceCode', 'const x = 1;');\n * const value = await adapter.getItem('SnapController', 'snap-id:sourceCode'); // 'const x = 1;'\n * // After restart: data is lost\n * ```\n *\n * @example Initialize with data (useful for testing)\n * ```typescript\n * const adapter = new InMemoryStorageAdapter({\n * SnapController: {\n * 'snap-id:sourceCode': 'const x = 1;',\n * 'snap-id:manifest': { name: 'My Snap' },\n * },\n * TokenListController: {\n * cache: { '0x1': ['token1', 'token2'] },\n * },\n * });\n * ```\n */\nexport class InMemoryStorageAdapter implements StorageAdapter {\n // Explicitly implement StorageAdapter interface\n /**\n * Internal storage map.\n */\n readonly #storage: Map<string, string>;\n\n /**\n * Constructs a new InMemoryStorageAdapter.\n *\n * @param initialData - Optional initial data to populate the storage.\n * Useful for setting up test fixtures without calling setItem multiple times.\n */\n constructor(initialData?: InitialStorageData) {\n this.#storage = new Map();\n\n if (initialData) {\n for (const [namespace, items] of Object.entries(initialData)) {\n for (const [key, value] of Object.entries(items)) {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.set(fullKey, JSON.stringify(value));\n }\n }\n }\n }\n\n /**\n * Retrieve an item from in-memory storage.\n * Deserializes JSON data from storage.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n * @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.\n */\n async getItem(namespace: string, key: string): Promise<StorageGetResult> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n const serialized = this.#storage.get(fullKey);\n\n // Key not found - return empty object\n if (serialized === undefined) {\n return {};\n }\n\n try {\n const result = JSON.parse(serialized);\n return { result };\n } catch (error) {\n console.error(`Failed to parse stored data for ${fullKey}:`, error);\n return { error: error as Error };\n }\n }\n\n /**\n * Store an item in in-memory storage.\n * Serializes JSON data to string.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n * @param value - The JSON value to store.\n */\n async setItem(namespace: string, key: string, value: Json): Promise<void> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.set(fullKey, JSON.stringify(value));\n }\n\n /**\n * Remove an item from in-memory storage.\n *\n * @param namespace - The controller namespace.\n * @param key - The data key.\n */\n async removeItem(namespace: string, key: string): Promise<void> {\n const fullKey = `${STORAGE_KEY_PREFIX}${namespace}:${key}`;\n this.#storage.delete(fullKey);\n }\n\n /**\n * Get all keys for a namespace.\n * Returns keys without the 'storage:namespace:' prefix.\n *\n * @param namespace - The namespace to get keys for.\n * @returns Array of keys (without prefix) for this namespace.\n */\n async getAllKeys(namespace: string): Promise<string[]> {\n const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;\n return Array.from(this.#storage.keys())\n .filter((key) => key.startsWith(prefix))\n .map((key) => key.slice(prefix.length));\n }\n\n /**\n * Clear all items for a namespace.\n *\n * @param namespace - The namespace to clear.\n */\n async clear(namespace: string): Promise<void> {\n const prefix = `${STORAGE_KEY_PREFIX}${namespace}:`;\n const keysToDelete = Array.from(this.#storage.keys()).filter((key) =>\n key.startsWith(prefix),\n );\n keysToDelete.forEach((key) => this.#storage.delete(key));\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StorageService-method-action-types.cjs","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { StorageService } from './StorageService';\n\n/**\n * Store large data in storage.\n *\n * ⚠️ **Designed for large values (100KB+), not many small ones.**\n * Each storage operation has I/O overhead. For best performance,\n * store one large object rather than many small key-value pairs.\n *\n * @example Good: Store entire cache as one value\n * ```typescript\n * await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });\n * ```\n *\n * @example Avoid: Many small values\n * ```typescript\n * // ❌ Don't do this - too many small writes\n * await service.setItem('TokenList', 'cache:0x1', [...]);\n * await service.setItem('TokenList', 'cache:0x38', [...]);\n * ```\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @param value -
|
|
1
|
+
{"version":3,"file":"StorageService-method-action-types.cjs","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { StorageService } from './StorageService';\n\n/**\n * Store large JSON data in storage.\n *\n * ⚠️ **Designed for large values (100KB+), not many small ones.**\n * Each storage operation has I/O overhead. For best performance,\n * store one large object rather than many small key-value pairs.\n *\n * @example Good: Store entire cache as one value\n * ```typescript\n * await service.setItem('TokenList', 'cache', { '0x1': [...], '0x38': [...] });\n * ```\n *\n * @example Avoid: Many small values\n * ```typescript\n * // ❌ Don't do this - too many small writes\n * await service.setItem('TokenList', 'cache:0x1', [...]);\n * await service.setItem('TokenList', 'cache:0x38', [...]);\n * ```\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @param value - JSON data to store (should be 100KB+ for optimal use).\n */\nexport type StorageServiceSetItemAction = {\n type: `StorageService:setItem`;\n handler: StorageService['setItem'];\n};\n\n/**\n * Retrieve JSON data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n * @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.\n */\nexport type StorageServiceGetItemAction = {\n type: `StorageService:getItem`;\n handler: StorageService['getItem'];\n};\n\n/**\n * Remove data from storage.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').\n */\nexport type StorageServiceRemoveItemAction = {\n type: `StorageService:removeItem`;\n handler: StorageService['removeItem'];\n};\n\n/**\n * Get all keys for a namespace.\n * Delegates to storage adapter which handles filtering.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n * @returns Array of keys (without prefix) for this namespace.\n */\nexport type StorageServiceGetAllKeysAction = {\n type: `StorageService:getAllKeys`;\n handler: StorageService['getAllKeys'];\n};\n\n/**\n * Clear all data for a namespace.\n *\n * @param namespace - Controller namespace (e.g., 'SnapController').\n */\nexport type StorageServiceClearAction = {\n type: `StorageService:clear`;\n handler: StorageService['clear'];\n};\n\n/**\n * Union of all StorageService action types.\n */\nexport type StorageServiceMethodActions =\n | StorageServiceSetItemAction\n | StorageServiceGetItemAction\n | StorageServiceRemoveItemAction\n | StorageServiceGetAllKeysAction\n | StorageServiceClearAction;\n"]}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import type { StorageService } from "./StorageService.cjs";
|
|
6
6
|
/**
|
|
7
|
-
* Store large data in storage.
|
|
7
|
+
* Store large JSON data in storage.
|
|
8
8
|
*
|
|
9
9
|
* ⚠️ **Designed for large values (100KB+), not many small ones.**
|
|
10
10
|
* Each storage operation has I/O overhead. For best performance,
|
|
@@ -24,21 +24,18 @@ import type { StorageService } from "./StorageService.cjs";
|
|
|
24
24
|
*
|
|
25
25
|
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
26
26
|
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
27
|
-
* @param value -
|
|
27
|
+
* @param value - JSON data to store (should be 100KB+ for optimal use).
|
|
28
28
|
*/
|
|
29
29
|
export type StorageServiceSetItemAction = {
|
|
30
30
|
type: `StorageService:setItem`;
|
|
31
31
|
handler: StorageService['setItem'];
|
|
32
32
|
};
|
|
33
33
|
/**
|
|
34
|
-
* Retrieve data from storage.
|
|
35
|
-
*
|
|
36
|
-
* Returns `unknown` since there's no schema validation.
|
|
37
|
-
* Callers should validate or cast the result to the expected type.
|
|
34
|
+
* Retrieve JSON data from storage.
|
|
38
35
|
*
|
|
39
36
|
* @param namespace - Controller namespace (e.g., 'SnapController').
|
|
40
37
|
* @param key - Storage key (e.g., 'npm:@metamask/example-snap:sourceCode').
|
|
41
|
-
* @returns
|
|
38
|
+
* @returns StorageGetResult: { result } if found, {} if not found, { error } on failure.
|
|
42
39
|
*/
|
|
43
40
|
export type StorageServiceGetItemAction = {
|
|
44
41
|
type: `StorageService:getItem`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StorageService-method-action-types.d.cts","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,6BAAyB;AAEvD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"StorageService-method-action-types.d.cts","sourceRoot":"","sources":["../src/StorageService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,6BAAyB;AAEvD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC,IAAI,EAAE,sBAAsB,CAAC;IAC7B,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,2BAA2B,GACnC,2BAA2B,GAC3B,2BAA2B,GAC3B,8BAA8B,GAC9B,8BAA8B,GAC9B,yBAAyB,CAAC"}
|