react-native-mmkv 2.4.0 → 2.4.3
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/README.md +8 -3
- package/android/build.gradle +17 -2
- package/lib/commonjs/MMKV.js +5 -1
- package/lib/commonjs/MMKV.js.map +1 -1
- package/lib/commonjs/PlatformChecker.js +11 -0
- package/lib/commonjs/PlatformChecker.js.map +1 -0
- package/lib/commonjs/createMMKV.mock.js +36 -0
- package/lib/commonjs/createMMKV.mock.js.map +1 -0
- package/lib/commonjs/hooks.js +2 -6
- package/lib/commonjs/hooks.js.map +1 -1
- package/lib/module/MMKV.js +3 -1
- package/lib/module/MMKV.js.map +1 -1
- package/lib/module/PlatformChecker.js +4 -0
- package/lib/module/PlatformChecker.js.map +1 -0
- package/lib/module/createMMKV.mock.js +27 -0
- package/lib/module/createMMKV.mock.js.map +1 -0
- package/lib/module/hooks.js +2 -6
- package/lib/module/hooks.js.map +1 -1
- package/lib/typescript/PlatformChecker.d.ts +1 -0
- package/lib/typescript/createMMKV.mock.d.ts +2 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -52,11 +52,15 @@ react-native-mmkv is sponsored by **getstream.io**. <br/>
|
|
|
52
52
|
|
|
53
53
|
## Benchmark
|
|
54
54
|
|
|
55
|
+
[StorageBenchmark](https://github.com/mrousavy/StorageBenchmark) compares popular storage libraries against each other by reading a value from storage for 1000 times:
|
|
56
|
+
|
|
55
57
|
<div align="center">
|
|
56
|
-
<
|
|
58
|
+
<a href="https://github.com/mrousavy/StorageBenchmark">
|
|
59
|
+
<img src="./img/benchmark_1000_get.png" />
|
|
60
|
+
</a>
|
|
57
61
|
<p>
|
|
58
|
-
<b>
|
|
59
|
-
Measured in milliseconds on an iPhone
|
|
62
|
+
<b>MMKV vs other storage libraries</b>: Reading a value from Storage 1000 times. <br/>
|
|
63
|
+
Measured in milliseconds on an iPhone 11 Pro, lower is better. <br/>
|
|
60
64
|
</p>
|
|
61
65
|
</div>
|
|
62
66
|
|
|
@@ -183,6 +187,7 @@ A mocked MMKV instance is automatically used when testing with Jest, so you will
|
|
|
183
187
|
* [Using MMKV with mobx-persist-storage](./docs/WRAPPER_MOBX.md)
|
|
184
188
|
* [Using MMKV with mobx-persist](./docs/WRAPPER_MOBXPERSIST.md)
|
|
185
189
|
* [Using MMKV with zustand persist-middleware](./docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md)
|
|
190
|
+
* [Using MMKV with jotai](./docs/WRAPPER_JOTAI.md)
|
|
186
191
|
* [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361)
|
|
187
192
|
|
|
188
193
|
## Limitations
|
package/android/build.gradle
CHANGED
|
@@ -160,7 +160,17 @@ dependencies {
|
|
|
160
160
|
extractJNI("com.facebook.fbjni:fbjni:+")
|
|
161
161
|
|
|
162
162
|
if (!sourceBuild) {
|
|
163
|
-
def
|
|
163
|
+
def buildType = "debug"
|
|
164
|
+
tasks.all({ task ->
|
|
165
|
+
if (task.name == "buildCMakeRelease") {
|
|
166
|
+
buildType = "release"
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
def rnAarMatcher = "**/react-native/**/*${buildType}.aar"
|
|
170
|
+
if (REACT_NATIVE_VERSION < 69) {
|
|
171
|
+
rnAarMatcher = "**/**/*.aar"
|
|
172
|
+
}
|
|
173
|
+
def rnAAR = fileTree("${defaultDir.toString()}").matching({ it.include rnAarMatcher }).singleFile
|
|
164
174
|
extractJNI(files(rnAAR))
|
|
165
175
|
}
|
|
166
176
|
}
|
|
@@ -193,7 +203,12 @@ task createNativeDepsDirectories {
|
|
|
193
203
|
}
|
|
194
204
|
|
|
195
205
|
task downloadBoost(dependsOn: createNativeDepsDirectories, type: Download) {
|
|
196
|
-
|
|
206
|
+
def transformedVersion = BOOST_VERSION.replace("_", ".")
|
|
207
|
+
def srcUrl = "https://boostorg.jfrog.io/artifactory/main/release/${transformedVersion}/source/boost_${BOOST_VERSION}.tar.gz"
|
|
208
|
+
if (REACT_NATIVE_VERSION < 69) {
|
|
209
|
+
srcUrl = "https://github.com/react-native-community/boost-for-react-native/releases/download/v${transformedVersion}-0/boost_${BOOST_VERSION}.tar.gz"
|
|
210
|
+
}
|
|
211
|
+
src(srcUrl)
|
|
197
212
|
onlyIfNewer(true)
|
|
198
213
|
overwrite(false)
|
|
199
214
|
dest(boost_file)
|
package/lib/commonjs/MMKV.js
CHANGED
|
@@ -7,6 +7,10 @@ exports.MMKV = void 0;
|
|
|
7
7
|
|
|
8
8
|
var _createMMKV = require("./createMMKV");
|
|
9
9
|
|
|
10
|
+
var _createMMKV2 = require("./createMMKV.mock");
|
|
11
|
+
|
|
12
|
+
var _PlatformChecker = require("./PlatformChecker");
|
|
13
|
+
|
|
10
14
|
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
|
11
15
|
|
|
12
16
|
const onValueChangedListeners = new Map();
|
|
@@ -29,7 +33,7 @@ class MMKV {
|
|
|
29
33
|
_defineProperty(this, "id", void 0);
|
|
30
34
|
|
|
31
35
|
this.id = configuration.id;
|
|
32
|
-
this.nativeInstance = (0, _createMMKV.createMMKV)(configuration);
|
|
36
|
+
this.nativeInstance = (0, _PlatformChecker.isJest)() ? (0, _createMMKV2.createMockMMKV)() : (0, _createMMKV.createMMKV)(configuration);
|
|
33
37
|
this.functionCache = {};
|
|
34
38
|
}
|
|
35
39
|
|
package/lib/commonjs/MMKV.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["MMKV.ts"],"names":["onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesChanged","keys","length","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","recrypt","toString","join","toJSON","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;;;;;;AAAA;;;;AAwHA,MAAMA,uBAAuB,GAAG,IAAIC,GAAJ,EAAhC;AAEA;AACA;AACA;;AACO,MAAMC,IAAN,CAAoC;AAKzC;AACF;AACA;AACA;AACEC,EAAAA,WAAW,CAACC,aAAgC,GAAG;AAAEC,IAAAA,EAAE,EAAE;AAAN,GAApC,EAA4D;AAAA;;AAAA;;AAAA;;AACrE,SAAKA,EAAL,GAAUD,aAAa,CAACC,EAAxB;AACA,SAAKC,cAAL,GAAsB,4BAAWF,aAAX,
|
|
1
|
+
{"version":3,"sources":["MMKV.ts"],"names":["onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesChanged","keys","length","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","recrypt","toString","join","toJSON","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;;;AAwHA,MAAMA,uBAAuB,GAAG,IAAIC,GAAJ,EAAhC;AAEA;AACA;AACA;;AACO,MAAMC,IAAN,CAAoC;AAKzC;AACF;AACA;AACA;AACEC,EAAAA,WAAW,CAACC,aAAgC,GAAG;AAAEC,IAAAA,EAAE,EAAE;AAAN,GAApC,EAA4D;AAAA;;AAAA;;AAAA;;AACrE,SAAKA,EAAL,GAAUD,aAAa,CAACC,EAAxB;AACA,SAAKC,cAAL,GAAsB,iCAClB,kCADkB,GAElB,4BAAWF,aAAX,CAFJ;AAGA,SAAKG,aAAL,GAAqB,EAArB;AACD;;AAEkC,MAAvBP,uBAAuB,GAAG;AACpC,QAAI,CAACA,uBAAuB,CAACQ,GAAxB,CAA4B,KAAKH,EAAjC,CAAL,EAA2C;AACzCL,MAAAA,uBAAuB,CAACS,GAAxB,CAA4B,KAAKJ,EAAjC,EAAqC,EAArC;AACD;;AACD,WAAOL,uBAAuB,CAACU,GAAxB,CAA4B,KAAKL,EAAjC,CAAP;AACD;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qC,MAA7B,CAAoCF,KAApC,EAA2C,CAA3C;AACD;AACF;AANI,KAAP;AAQD;;AA5GwC","sourcesContent":["import { createMMKV } from './createMMKV';\nimport { createMockMMKV } from './createMMKV.mock';\nimport { isJest } from './PlatformChecker';\n\ninterface Listener {\n remove: () => void;\n}\n\n/**\n * Used for configuration of a single MMKV instance.\n */\nexport interface MMKVConfiguration {\n /**\n * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!\n *\n * @example\n * ```ts\n * const userStorage = new MMKV({ id: `user-${userId}-storage` })\n * const globalStorage = new MMKV({ id: 'global-app-storage' })\n * ```\n *\n * @default 'mmkv.default'\n */\n id: string;\n /**\n * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:\n *\n * @example\n * ```ts\n * const temporaryStorage = new MMKV({ path: '/tmp/' })\n * ```\n */\n path?: string;\n /**\n * The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n *\n * @example\n * ```ts\n * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })\n * ```\n */\n encryptionKey?: string;\n}\n\n/**\n * Represents a single MMKV instance.\n */\ninterface MMKVInterface {\n /**\n * Set a value for the given `key`.\n */\n set: (key: string, value: boolean | string | number) => void;\n /**\n * Get the boolean value for the given `key`, or `undefined` if it does not exist.\n *\n * @default undefined\n */\n getBoolean: (key: string) => boolean | undefined;\n /**\n * Get the string value for the given `key`, or `undefined` if it does not exist.\n *\n * @default undefined\n */\n getString: (key: string) => string | undefined;\n /**\n * Get the number value for the given `key`, or `undefined` if it does not exist.\n *\n * @default undefined\n */\n getNumber: (key: string) => number | undefined;\n /**\n * Checks whether the given `key` is being stored in this MMKV instance.\n */\n contains: (key: string) => boolean;\n /**\n * Delete the given `key`.\n */\n delete: (key: string) => void;\n /**\n * Get all keys.\n *\n * @default []\n */\n getAllKeys: () => string[];\n /**\n * Delete all keys.\n */\n clearAll: () => void;\n /**\n * Sets (or updates) the encryption-key to encrypt all data in this MMKV instance with.\n *\n * To remove encryption, pass `undefined` as a key.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n */\n recrypt: (key: string | undefined) => void;\n /**\n * Adds a value changed listener. The Listener will be called whenever any value\n * in this storage instance changes (set or delete).\n *\n * To unsubscribe from value changes, call `remove()` on the Listener.\n */\n addOnValueChangedListener: (\n onValueChanged: (key: string) => void\n ) => Listener;\n}\n\nexport type NativeMMKV = Pick<\n MMKVInterface,\n | 'clearAll'\n | 'contains'\n | 'delete'\n | 'getAllKeys'\n | 'getBoolean'\n | 'getNumber'\n | 'getString'\n | 'set'\n | 'recrypt'\n>;\n\nconst onValueChangedListeners = new Map<string, ((key: string) => void)[]>();\n\n/**\n * A single MMKV instance.\n */\nexport class MMKV implements MMKVInterface {\n private nativeInstance: NativeMMKV;\n private functionCache: Partial<NativeMMKV>;\n private id: string;\n\n /**\n * Creates a new MMKV instance with the given Configuration.\n * If no custom `id` is supplied, `'mmkv.default'` will be used.\n */\n constructor(configuration: MMKVConfiguration = { id: 'mmkv.default' }) {\n this.id = configuration.id;\n this.nativeInstance = isJest()\n ? createMockMMKV()\n : createMMKV(configuration);\n this.functionCache = {};\n }\n\n private get onValueChangedListeners() {\n if (!onValueChangedListeners.has(this.id)) {\n onValueChangedListeners.set(this.id, []);\n }\n return onValueChangedListeners.get(this.id)!;\n }\n\n private getFunctionFromCache<T extends keyof NativeMMKV>(\n functionName: T\n ): NativeMMKV[T] {\n if (this.functionCache[functionName] == null) {\n this.functionCache[functionName] = this.nativeInstance[functionName];\n }\n return this.functionCache[functionName] as NativeMMKV[T];\n }\n\n private onValuesChanged(keys: string[]) {\n if (this.onValueChangedListeners.length === 0) return;\n\n for (const key of keys) {\n for (const listener of this.onValueChangedListeners) {\n listener(key);\n }\n }\n }\n\n set(key: string, value: boolean | string | number): void {\n const func = this.getFunctionFromCache('set');\n func(key, value);\n\n this.onValuesChanged([key]);\n }\n getBoolean(key: string): boolean | undefined {\n const func = this.getFunctionFromCache('getBoolean');\n return func(key);\n }\n getString(key: string): string | undefined {\n const func = this.getFunctionFromCache('getString');\n return func(key);\n }\n getNumber(key: string): number | undefined {\n const func = this.getFunctionFromCache('getNumber');\n return func(key);\n }\n contains(key: string): boolean {\n const func = this.getFunctionFromCache('contains');\n return func(key);\n }\n delete(key: string): void {\n const func = this.getFunctionFromCache('delete');\n func(key);\n\n this.onValuesChanged([key]);\n }\n getAllKeys(): string[] {\n const func = this.getFunctionFromCache('getAllKeys');\n return func();\n }\n clearAll(): void {\n const keys = this.getAllKeys();\n\n const func = this.getFunctionFromCache('clearAll');\n func();\n\n this.onValuesChanged(keys);\n }\n recrypt(key: string | undefined): void {\n const func = this.getFunctionFromCache('recrypt');\n return func(key);\n }\n\n toString(): string {\n return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;\n }\n toJSON(): object {\n return {\n [this.id]: this.getAllKeys(),\n };\n }\n\n addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {\n this.onValueChangedListeners.push(onValueChanged);\n\n return {\n remove: () => {\n const index = this.onValueChangedListeners.indexOf(onValueChanged);\n if (index !== -1) {\n this.onValueChangedListeners.splice(index, 1);\n }\n },\n };\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["PlatformChecker.ts"],"names":["isJest","process","env","JEST_WORKER_ID"],"mappings":";;;;;;;AAAO,SAASA,MAAT,GAA2B;AAChC,SAAOC,OAAO,CAACC,GAAR,CAAYC,cAAZ,IAA8B,IAArC;AACD","sourcesContent":["export function isJest(): boolean {\n return process.env.JEST_WORKER_ID != null;\n}\n"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.createMockMMKV = void 0;
|
|
7
|
+
|
|
8
|
+
/* Mock MMKV instance for use in tests */
|
|
9
|
+
const createMockMMKV = () => {
|
|
10
|
+
const storage = new Map();
|
|
11
|
+
return {
|
|
12
|
+
clearAll: () => storage.clear(),
|
|
13
|
+
delete: key => storage.delete(key),
|
|
14
|
+
set: (key, value) => storage.set(key, value),
|
|
15
|
+
getString: key => {
|
|
16
|
+
const result = storage.get(key);
|
|
17
|
+
return typeof result === 'string' ? result : undefined;
|
|
18
|
+
},
|
|
19
|
+
getNumber: key => {
|
|
20
|
+
const result = storage.get(key);
|
|
21
|
+
return typeof result === 'number' ? result : undefined;
|
|
22
|
+
},
|
|
23
|
+
getBoolean: key => {
|
|
24
|
+
const result = storage.get(key);
|
|
25
|
+
return typeof result === 'boolean' ? result : undefined;
|
|
26
|
+
},
|
|
27
|
+
getAllKeys: () => Array.from(storage.keys()),
|
|
28
|
+
contains: key => storage.has(key),
|
|
29
|
+
recrypt: () => {
|
|
30
|
+
console.warn('Encryption is not supported in mocked MMKV instances!');
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
exports.createMockMMKV = createMockMMKV;
|
|
36
|
+
//# sourceMappingURL=createMMKV.mock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["createMMKV.mock.ts"],"names":["createMockMMKV","storage","Map","clearAll","clear","delete","key","set","value","getString","result","get","undefined","getNumber","getBoolean","getAllKeys","Array","from","keys","contains","has","recrypt","console","warn"],"mappings":";;;;;;;AAEA;AACO,MAAMA,cAAc,GAAG,MAAkB;AAC9C,QAAMC,OAAO,GAAG,IAAIC,GAAJ,EAAhB;AAEA,SAAO;AACLC,IAAAA,QAAQ,EAAE,MAAMF,OAAO,CAACG,KAAR,EADX;AAELC,IAAAA,MAAM,EAAGC,GAAD,IAASL,OAAO,CAACI,MAAR,CAAeC,GAAf,CAFZ;AAGLC,IAAAA,GAAG,EAAE,CAACD,GAAD,EAAME,KAAN,KAAgBP,OAAO,CAACM,GAAR,CAAYD,GAAZ,EAAiBE,KAAjB,CAHhB;AAILC,IAAAA,SAAS,EAAGH,GAAD,IAAS;AAClB,YAAMI,MAAM,GAAGT,OAAO,CAACU,GAAR,CAAYL,GAAZ,CAAf;AACA,aAAO,OAAOI,MAAP,KAAkB,QAAlB,GAA6BA,MAA7B,GAAsCE,SAA7C;AACD,KAPI;AAQLC,IAAAA,SAAS,EAAGP,GAAD,IAAS;AAClB,YAAMI,MAAM,GAAGT,OAAO,CAACU,GAAR,CAAYL,GAAZ,CAAf;AACA,aAAO,OAAOI,MAAP,KAAkB,QAAlB,GAA6BA,MAA7B,GAAsCE,SAA7C;AACD,KAXI;AAYLE,IAAAA,UAAU,EAAGR,GAAD,IAAS;AACnB,YAAMI,MAAM,GAAGT,OAAO,CAACU,GAAR,CAAYL,GAAZ,CAAf;AACA,aAAO,OAAOI,MAAP,KAAkB,SAAlB,GAA8BA,MAA9B,GAAuCE,SAA9C;AACD,KAfI;AAgBLG,IAAAA,UAAU,EAAE,MAAMC,KAAK,CAACC,IAAN,CAAWhB,OAAO,CAACiB,IAAR,EAAX,CAhBb;AAiBLC,IAAAA,QAAQ,EAAGb,GAAD,IAASL,OAAO,CAACmB,GAAR,CAAYd,GAAZ,CAjBd;AAkBLe,IAAAA,OAAO,EAAE,MAAM;AACbC,MAAAA,OAAO,CAACC,IAAR,CAAa,uDAAb;AACD;AApBI,GAAP;AAsBD,CAzBM","sourcesContent":["import type { NativeMMKV } from 'react-native-mmkv';\n\n/* Mock MMKV instance for use in tests */\nexport const createMockMMKV = (): NativeMMKV => {\n const storage = new Map<string, string | boolean | number>();\n\n return {\n clearAll: () => storage.clear(),\n delete: (key) => storage.delete(key),\n set: (key, value) => storage.set(key, value),\n getString: (key) => {\n const result = storage.get(key);\n return typeof result === 'string' ? result : undefined;\n },\n getNumber: (key) => {\n const result = storage.get(key);\n return typeof result === 'number' ? result : undefined;\n },\n getBoolean: (key) => {\n const result = storage.get(key);\n return typeof result === 'boolean' ? result : undefined;\n },\n getAllKeys: () => Array.from(storage.keys()),\n contains: (key) => storage.has(key),\n recrypt: () => {\n console.warn('Encryption is not supported in mocked MMKV instances!');\n },\n };\n};\n"]}
|
package/lib/commonjs/hooks.js
CHANGED
|
@@ -70,14 +70,10 @@ function createMMKVHook(getter) {
|
|
|
70
70
|
default:
|
|
71
71
|
throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);
|
|
72
72
|
}
|
|
73
|
-
}, [key, mmkv]); // update value if key changes
|
|
73
|
+
}, [key, mmkv]); // update value if key or instance changes
|
|
74
74
|
|
|
75
|
-
const keyRef = (0, _react.useRef)(key);
|
|
76
75
|
(0, _react.useEffect)(() => {
|
|
77
|
-
|
|
78
|
-
setValue(getter(mmkv, key));
|
|
79
|
-
keyRef.current = key;
|
|
80
|
-
}
|
|
76
|
+
setValue(getter(mmkv, key));
|
|
81
77
|
}, [key, mmkv]); // update value if it changes somewhere else (second hook, same key)
|
|
82
78
|
|
|
83
79
|
(0, _react.useEffect)(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["hooks.ts"],"names":["isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","MMKV","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","keyRef","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify","useMMKVListener","valueChangedListener","ref"],"mappings":";;;;;;;;;;;;AAAA;;AACA;;AAEA,SAASA,oBAAT,CACEC,IADF,EAEEC,KAFF,EAGW;AACT,MAAID,IAAI,IAAI,IAAR,IAAgBC,KAAK,IAAI,IAA7B,EAAmC,OAAOD,IAAI,IAAI,IAAR,IAAgBC,KAAK,IAAI,IAAhC;AAEnC,SACED,IAAI,CAACE,aAAL,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FK,EAGC;AACN,QAAMmC,GAAG,GAAG,mBAAOD,oBAAP,CAAZ;AACAC,EAAAA,GAAG,CAACjC,OAAJ,GAAcgC,oBAAd;AAEA,QAAM5B,IAAI,GAAGN,QAAH,aAAGA,QAAH,cAAGA,QAAH,GAAeJ,kBAAkB,EAA3C;AAEA,wBAAU,MAAM;AACd,UAAMoB,QAAQ,GAAGV,IAAI,CAACW,yBAAL,CAAgCC,UAAD,IAAgB;AAC9DiB,MAAAA,GAAG,CAACjC,OAAJ,CAAYgB,UAAZ;AACD,KAFgB,CAAjB;AAGA,WAAO,MAAMF,QAAQ,CAACG,MAAT,EAAb;AACD,GALD,EAKG,CAACb,IAAD,CALH;AAMD","sourcesContent":["import { useRef, useState, useMemo, useCallback, useEffect } from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left?: MMKVConfiguration,\n right?: MMKVConfiguration\n): boolean {\n if (left == null || right == null) return left == null && right == null;\n\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\n/**\n * Use the default, shared MMKV instance.\n */\nexport function useMMKV(): MMKV;\n/**\n * Use a custom MMKV instance with the given configuration.\n * @param configuration The configuration to initialize the MMKV instance with. Does not have to be memoized.\n */\nexport function useMMKV(configuration: MMKVConfiguration): MMKV;\nexport function useMMKV(configuration?: MMKVConfiguration): MMKV {\n const instance = useRef<MMKV>();\n const lastConfiguration = useRef<MMKVConfiguration>();\n\n if (configuration == null) return getDefaultInstance();\n\n if (\n instance.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n return instance.current;\n}\n\nfunction createMMKVHook<\n T extends (boolean | number | string) | undefined,\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n // update value by user set\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n // update value if key changes\n const keyRef = useRef(key);\n useEffect(() => {\n if (key !== keyRef.current) {\n setValue(getter(mmkv, key));\n keyRef.current = key;\n }\n }, [key, mmkv]);\n\n // update value if it changes somewhere else (second hook, same key)\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n\n/**\n * Listen for changes in the given MMKV storage instance.\n * If no instance is passed, the default instance will be used.\n * @param valueChangedListener The function to call whenever a value inside the storage instance changes\n * @param instance The instance to listen to changes to (or the default instance)\n *\n * @example\n * ```ts\n * useMMKVListener((key) => {\n * console.log(`Value for \"${key}\" changed!`)\n * })\n * ```\n */\nexport function useMMKVListener(\n valueChangedListener: (key: string) => void,\n instance?: MMKV\n): void {\n const ref = useRef(valueChangedListener);\n ref.current = valueChangedListener;\n\n const mmkv = instance ?? getDefaultInstance();\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n ref.current(changedKey);\n });\n return () => listener.remove();\n }, [mmkv]);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["hooks.ts"],"names":["isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","MMKV","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify","useMMKVListener","valueChangedListener","ref"],"mappings":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ACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASwB,eAAT,CACLC,oBADK,EAELjC,QAFK,EAGC;AACN,QAAMkC,GAAG,GAAG,mBAAOD,oBAAP,CAAZ;AACAC,EAAAA,GAAG,CAAChC,OAAJ,GAAc+B,oBAAd;AAEA,QAAM3B,IAAI,GAAGN,QAAH,aAAGA,QAAH,cAAGA,QAAH,GAAeJ,kBAAkB,EAA3C;AAEA,wBAAU,MAAM;AACd,UAAMmB,QAAQ,GAAGT,IAAI,CAACU,yBAAL,CAAgCC,UAAD,IAAgB;AAC9DiB,MAAAA,GAAG,CAAChC,OAAJ,CAAYe,UAAZ;AACD,KAFgB,CAAjB;AAGA,WAAO,MAAMF,QAAQ,CAACG,MAAT,EAAb;AACD,GALD,EAKG,CAACZ,IAAD,CALH;AAMD","sourcesContent":["import { useRef, useState, useMemo, useCallback, useEffect } from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left?: MMKVConfiguration,\n right?: MMKVConfiguration\n): boolean {\n if (left == null || right == null) return left == null && right == null;\n\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\n/**\n * Use the default, shared MMKV instance.\n */\nexport function useMMKV(): MMKV;\n/**\n * Use a custom MMKV instance with the given configuration.\n * @param configuration The configuration to initialize the MMKV instance with. Does not have to be memoized.\n */\nexport function useMMKV(configuration: MMKVConfiguration): MMKV;\nexport function useMMKV(configuration?: MMKVConfiguration): MMKV {\n const instance = useRef<MMKV>();\n const lastConfiguration = useRef<MMKVConfiguration>();\n\n if (configuration == null) return getDefaultInstance();\n\n if (\n instance.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n return instance.current;\n}\n\nfunction createMMKVHook<\n T extends (boolean | number | string) | undefined,\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n // update value by user set\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n // update value if key or instance changes\n useEffect(() => {\n setValue(getter(mmkv, key));\n }, [key, mmkv]);\n\n // update value if it changes somewhere else (second hook, same key)\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n\n/**\n * Listen for changes in the given MMKV storage instance.\n * If no instance is passed, the default instance will be used.\n * @param valueChangedListener The function to call whenever a value inside the storage instance changes\n * @param instance The instance to listen to changes to (or the default instance)\n *\n * @example\n * ```ts\n * useMMKVListener((key) => {\n * console.log(`Value for \"${key}\" changed!`)\n * })\n * ```\n */\nexport function useMMKVListener(\n valueChangedListener: (key: string) => void,\n instance?: MMKV\n): void {\n const ref = useRef(valueChangedListener);\n ref.current = valueChangedListener;\n\n const mmkv = instance ?? getDefaultInstance();\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n ref.current(changedKey);\n });\n return () => listener.remove();\n }, [mmkv]);\n}\n"]}
|
package/lib/module/MMKV.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
|
2
2
|
|
|
3
3
|
import { createMMKV } from './createMMKV';
|
|
4
|
+
import { createMockMMKV } from './createMMKV.mock';
|
|
5
|
+
import { isJest } from './PlatformChecker';
|
|
4
6
|
const onValueChangedListeners = new Map();
|
|
5
7
|
/**
|
|
6
8
|
* A single MMKV instance.
|
|
@@ -21,7 +23,7 @@ export class MMKV {
|
|
|
21
23
|
_defineProperty(this, "id", void 0);
|
|
22
24
|
|
|
23
25
|
this.id = configuration.id;
|
|
24
|
-
this.nativeInstance = createMMKV(configuration);
|
|
26
|
+
this.nativeInstance = isJest() ? createMockMMKV() : createMMKV(configuration);
|
|
25
27
|
this.functionCache = {};
|
|
26
28
|
}
|
|
27
29
|
|
package/lib/module/MMKV.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["MMKV.ts"],"names":["createMMKV","onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesChanged","keys","length","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","recrypt","toString","join","toJSON","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;AAAA,SAASA,UAAT,QAA2B,cAA3B;AAwHA,MAAMC,uBAAuB,GAAG,IAAIC,GAAJ,EAAhC;AAEA;AACA;AACA;;AACA,OAAO,MAAMC,IAAN,CAAoC;AAKzC;AACF;AACA;AACA;AACEC,EAAAA,WAAW,CAACC,aAAgC,GAAG;AAAEC,IAAAA,EAAE,EAAE;AAAN,GAApC,EAA4D;AAAA;;AAAA;;AAAA;;AACrE,SAAKA,EAAL,GAAUD,aAAa,CAACC,EAAxB;AACA,SAAKC,cAAL,GAAsBP,UAAU,
|
|
1
|
+
{"version":3,"sources":["MMKV.ts"],"names":["createMMKV","createMockMMKV","isJest","onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesChanged","keys","length","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","recrypt","toString","join","toJSON","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;AAAA,SAASA,UAAT,Q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IAAAA,IAAI;AAEJ,SAAKN,eAAL,CAAqBC,IAArB;AACD;;AACDa,EAAAA,OAAO,CAACX,GAAD,EAAgC;AACrC,UAAMG,IAAI,GAAG,KAAKR,oBAAL,CAA0B,SAA1B,CAAb;AACA,WAAOQ,IAAI,CAACH,GAAD,CAAX;AACD;;AAEDY,EAAAA,QAAQ,GAAW;AACjB,WAAQ,SAAQ,KAAKvB,EAAG,OAAM,KAAKoB,UAAL,GAAkBI,IAAlB,CAAuB,IAAvB,CAA6B,GAA3D;AACD;;AACDC,EAAAA,MAAM,GAAW;AACf,WAAO;AACL,OAAC,KAAKzB,EAAN,GAAW,KAAKoB,UAAL;AADN,KAAP;AAGD;;AAEDM,EAAAA,yBAAyB,CAACC,cAAD,EAAkD;AACzE,SAAKhC,uBAAL,CAA6BiC,IAA7B,CAAkCD,cAAlC;AAEA,WAAO;AACLE,MAAAA,MAAM,EAAE,MAAM;AACZ,cAAMC,KAAK,GAAG,KAAKnC,uBAAL,CAA6BoC,OAA7B,CAAqCJ,cAArC,CAAd;;AACA,YAAIG,KAAK,KAAK,CAAC,CAAf,EAAkB;AAChB,eAAKnC,uBAAL,CAA6BqC,MAA7B,CAAoCF,KAApC,EAA2C,CAA3C;AACD;AACF;AANI,KAAP;AAQD;;AA5GwC","sourcesContent":["import { createMMKV } from './createMMKV';\nimport { createMockMMKV } from './createMMKV.mock';\nimport { isJest } from './PlatformChecker';\n\ninterface Listener {\n remove: () => void;\n}\n\n/**\n * Used for configuration of a single MMKV instance.\n */\nexport interface MMKVConfiguration {\n /**\n * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!\n *\n * @example\n * ```ts\n * const userStorage = new MMKV({ id: `user-${userId}-storage` })\n * const globalStorage = new MMKV({ id: 'global-app-storage' })\n * ```\n *\n * @default 'mmkv.default'\n */\n id: string;\n /**\n * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:\n *\n * @example\n * ```ts\n * const temporaryStorage = new MMKV({ path: '/tmp/' })\n * ```\n */\n path?: string;\n /**\n * The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n *\n * @example\n * ```ts\n * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })\n * ```\n */\n encryptionKey?: string;\n}\n\n/**\n * Represents a single MMKV instance.\n */\ninterface MMKVInterface {\n /**\n * Set a value for the given `key`.\n */\n set: (key: string, value: boolean | string | number) => void;\n /**\n * Get the boolean value for the given `key`, or `undefined` if it does not exist.\n *\n * @default undefined\n */\n getBoolean: (key: string) => boolean | undefined;\n /**\n * Get the string value for the given `key`, or `undefined` if it does not exist.\n *\n * @default undefined\n */\n getString: (key: string) => string | undefined;\n /**\n * Get the number value for the given `key`, or `undefined` if it does not exist.\n *\n * @default undefined\n */\n getNumber: (key: string) => number | undefined;\n /**\n * Checks whether the given `key` is being stored in this MMKV instance.\n */\n contains: (key: string) => boolean;\n /**\n * Delete the given `key`.\n */\n delete: (key: string) => void;\n /**\n * Get all keys.\n *\n * @default []\n */\n getAllKeys: () => string[];\n /**\n * Delete all keys.\n */\n clearAll: () => void;\n /**\n * Sets (or updates) the encryption-key to encrypt all data in this MMKV instance with.\n *\n * To remove encryption, pass `undefined` as a key.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n */\n recrypt: (key: string | undefined) => void;\n /**\n * Adds a value changed listener. The Listener will be called whenever any value\n * in this storage instance changes (set or delete).\n *\n * To unsubscribe from value changes, call `remove()` on the Listener.\n */\n addOnValueChangedListener: (\n onValueChanged: (key: string) => void\n ) => Listener;\n}\n\nexport type NativeMMKV = Pick<\n MMKVInterface,\n | 'clearAll'\n | 'contains'\n | 'delete'\n | 'getAllKeys'\n | 'getBoolean'\n | 'getNumber'\n | 'getString'\n | 'set'\n | 'recrypt'\n>;\n\nconst onValueChangedListeners = new Map<string, ((key: string) => void)[]>();\n\n/**\n * A single MMKV instance.\n */\nexport class MMKV implements MMKVInterface {\n private nativeInstance: NativeMMKV;\n private functionCache: Partial<NativeMMKV>;\n private id: string;\n\n /**\n * Creates a new MMKV instance with the given Configuration.\n * If no custom `id` is supplied, `'mmkv.default'` will be used.\n */\n constructor(configuration: MMKVConfiguration = { id: 'mmkv.default' }) {\n this.id = configuration.id;\n this.nativeInstance = isJest()\n ? createMockMMKV()\n : createMMKV(configuration);\n this.functionCache = {};\n }\n\n private get onValueChangedListeners() {\n if (!onValueChangedListeners.has(this.id)) {\n onValueChangedListeners.set(this.id, []);\n }\n return onValueChangedListeners.get(this.id)!;\n }\n\n private getFunctionFromCache<T extends keyof NativeMMKV>(\n functionName: T\n ): NativeMMKV[T] {\n if (this.functionCache[functionName] == null) {\n this.functionCache[functionName] = this.nativeInstance[functionName];\n }\n return this.functionCache[functionName] as NativeMMKV[T];\n }\n\n private onValuesChanged(keys: string[]) {\n if (this.onValueChangedListeners.length === 0) return;\n\n for (const key of keys) {\n for (const listener of this.onValueChangedListeners) {\n listener(key);\n }\n }\n }\n\n set(key: string, value: boolean | string | number): void {\n const func = this.getFunctionFromCache('set');\n func(key, value);\n\n this.onValuesChanged([key]);\n }\n getBoolean(key: string): boolean | undefined {\n const func = this.getFunctionFromCache('getBoolean');\n return func(key);\n }\n getString(key: string): string | undefined {\n const func = this.getFunctionFromCache('getString');\n return func(key);\n }\n getNumber(key: string): number | undefined {\n const func = this.getFunctionFromCache('getNumber');\n return func(key);\n }\n contains(key: string): boolean {\n const func = this.getFunctionFromCache('contains');\n return func(key);\n }\n delete(key: string): void {\n const func = this.getFunctionFromCache('delete');\n func(key);\n\n this.onValuesChanged([key]);\n }\n getAllKeys(): string[] {\n const func = this.getFunctionFromCache('getAllKeys');\n return func();\n }\n clearAll(): void {\n const keys = this.getAllKeys();\n\n const func = this.getFunctionFromCache('clearAll');\n func();\n\n this.onValuesChanged(keys);\n }\n recrypt(key: string | undefined): void {\n const func = this.getFunctionFromCache('recrypt');\n return func(key);\n }\n\n toString(): string {\n return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;\n }\n toJSON(): object {\n return {\n [this.id]: this.getAllKeys(),\n };\n }\n\n addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {\n this.onValueChangedListeners.push(onValueChanged);\n\n return {\n remove: () => {\n const index = this.onValueChangedListeners.indexOf(onValueChanged);\n if (index !== -1) {\n this.onValueChangedListeners.splice(index, 1);\n }\n },\n };\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["PlatformChecker.ts"],"names":["isJest","process","env","JEST_WORKER_ID"],"mappings":"AAAA,OAAO,SAASA,MAAT,GAA2B;AAChC,SAAOC,OAAO,CAACC,GAAR,CAAYC,cAAZ,IAA8B,IAArC;AACD","sourcesContent":["export function isJest(): boolean {\n return process.env.JEST_WORKER_ID != null;\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/* Mock MMKV instance for use in tests */
|
|
2
|
+
export const createMockMMKV = () => {
|
|
3
|
+
const storage = new Map();
|
|
4
|
+
return {
|
|
5
|
+
clearAll: () => storage.clear(),
|
|
6
|
+
delete: key => storage.delete(key),
|
|
7
|
+
set: (key, value) => storage.set(key, value),
|
|
8
|
+
getString: key => {
|
|
9
|
+
const result = storage.get(key);
|
|
10
|
+
return typeof result === 'string' ? result : undefined;
|
|
11
|
+
},
|
|
12
|
+
getNumber: key => {
|
|
13
|
+
const result = storage.get(key);
|
|
14
|
+
return typeof result === 'number' ? result : undefined;
|
|
15
|
+
},
|
|
16
|
+
getBoolean: key => {
|
|
17
|
+
const result = storage.get(key);
|
|
18
|
+
return typeof result === 'boolean' ? result : undefined;
|
|
19
|
+
},
|
|
20
|
+
getAllKeys: () => Array.from(storage.keys()),
|
|
21
|
+
contains: key => storage.has(key),
|
|
22
|
+
recrypt: () => {
|
|
23
|
+
console.warn('Encryption is not supported in mocked MMKV instances!');
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=createMMKV.mock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["createMMKV.mock.ts"],"names":["createMockMMKV","storage","Map","clearAll","clear","delete","key","set","value","getString","result","get","undefined","getNumber","getBoolean","getAllKeys","Array","from","keys","contains","has","recrypt","console","warn"],"mappings":"AAEA;AACA,OAAO,MAAMA,cAAc,GAAG,MAAkB;AAC9C,QAAMC,OAAO,GAAG,IAAIC,GAAJ,EAAhB;AAEA,SAAO;AACLC,IAAAA,QAAQ,EAAE,MAAMF,OAAO,CAACG,KAAR,EADX;AAELC,IAAAA,MAAM,EAAGC,GAAD,IAASL,OAAO,CAACI,MAAR,CAAeC,GAAf,CAFZ;AAGLC,IAAAA,GAAG,EAAE,CAACD,GAAD,EAAME,KAAN,KAAgBP,OAAO,CAACM,GAAR,CAAYD,GAAZ,EAAiBE,KAAjB,CAHhB;AAILC,IAAAA,SAAS,EAAGH,GAAD,IAAS;AAClB,YAAMI,MAAM,GAAGT,OAAO,CAACU,GAAR,CAAYL,GAAZ,CAAf;AACA,aAAO,OAAOI,MAAP,KAAkB,QAAlB,GAA6BA,MAA7B,GAAsCE,SAA7C;AACD,KAPI;AAQLC,IAAAA,SAAS,EAAGP,GAAD,IAAS;AAClB,YAAMI,MAAM,GAAGT,OAAO,CAACU,GAAR,CAAYL,GAAZ,CAAf;AACA,aAAO,OAAOI,MAAP,KAAkB,QAAlB,GAA6BA,MAA7B,GAAsCE,SAA7C;AACD,KAXI;AAYLE,IAAAA,UAAU,EAAGR,GAAD,IAAS;AACnB,YAAMI,MAAM,GAAGT,OAAO,CAACU,GAAR,CAAYL,GAAZ,CAAf;AACA,aAAO,OAAOI,MAAP,KAAkB,SAAlB,GAA8BA,MAA9B,GAAuCE,SAA9C;AACD,KAfI;AAgBLG,IAAAA,UAAU,EAAE,MAAMC,KAAK,CAACC,IAAN,CAAWhB,OAAO,CAACiB,IAAR,EAAX,CAhBb;AAiBLC,IAAAA,QAAQ,EAAGb,GAAD,IAASL,OAAO,CAACmB,GAAR,CAAYd,GAAZ,CAjBd;AAkBLe,IAAAA,OAAO,EAAE,MAAM;AACbC,MAAAA,OAAO,CAACC,IAAR,CAAa,uDAAb;AACD;AApBI,GAAP;AAsBD,CAzBM","sourcesContent":["import type { NativeMMKV } from 'react-native-mmkv';\n\n/* Mock MMKV instance for use in tests */\nexport const createMockMMKV = (): NativeMMKV => {\n const storage = new Map<string, string | boolean | number>();\n\n return {\n clearAll: () => storage.clear(),\n delete: (key) => storage.delete(key),\n set: (key, value) => storage.set(key, value),\n getString: (key) => {\n const result = storage.get(key);\n return typeof result === 'string' ? result : undefined;\n },\n getNumber: (key) => {\n const result = storage.get(key);\n return typeof result === 'number' ? result : undefined;\n },\n getBoolean: (key) => {\n const result = storage.get(key);\n return typeof result === 'boolean' ? result : undefined;\n },\n getAllKeys: () => Array.from(storage.keys()),\n contains: (key) => storage.has(key),\n recrypt: () => {\n console.warn('Encryption is not supported in mocked MMKV instances!');\n },\n };\n};\n"]}
|
package/lib/module/hooks.js
CHANGED
|
@@ -57,14 +57,10 @@ function createMMKVHook(getter) {
|
|
|
57
57
|
default:
|
|
58
58
|
throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);
|
|
59
59
|
}
|
|
60
|
-
}, [key, mmkv]); // update value if key changes
|
|
60
|
+
}, [key, mmkv]); // update value if key or instance changes
|
|
61
61
|
|
|
62
|
-
const keyRef = useRef(key);
|
|
63
62
|
useEffect(() => {
|
|
64
|
-
|
|
65
|
-
setValue(getter(mmkv, key));
|
|
66
|
-
keyRef.current = key;
|
|
67
|
-
}
|
|
63
|
+
setValue(getter(mmkv, key));
|
|
68
64
|
}, [key, mmkv]); // update value if it changes somewhere else (second hook, same key)
|
|
69
65
|
|
|
70
66
|
useEffect(() => {
|
package/lib/module/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["hooks.ts"],"names":["useRef","useState","useMemo","useCallback","useEffect","MMKV","isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","keyRef","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify","useMMKVListener","valueChangedListener","ref"],"mappings":"AAAA,SAASA,MAAT,EAAiBC,QAAjB,EAA2BC,OAA3B,EAAoCC,WAApC,EAAiDC,SAAjD,QAAkE,OAAlE;AACA,SAASC,IAAT,QAAwC,QAAxC;;AAEA,SAASC,oBAAT,CACEC,IADF,EAEEC,KAFF,EAGW;AACT,MAAID,IAAI,IAAI,IAAR,IAAgBC,KAAK,IAAI,IAA7B,EAAmC,OAAOD,IAAI,IAAI,IAAR,IAAgBC,KAAK,IAAI,IAAhC;AAEnC,SACED,IAAI,CAACE,aAAL,KAAuBD,KAAK,CAACC,aAA7B,IACAF,IAAI,CAACG,EAAL,KAAYF,KAAK,CAACE,EADlB,IAEAH,IAAI,CAACI,IAAL,KAAcH,KAAK,CAACG,IAHtB;AAKD;;AAED,IAAIC,eAA4B,GAAG,IAAnC;;AACA,SAASC,kBAAT,GAAoC;AAClC,MAAID,eAAe,IAAI,IAAvB,EAA6B;AAC3BA,IAAAA,eAAe,GAAG,IAAIP,IAAJ,EAAlB;AACD;;AACD,SAAOO,eAAP;AACD;AAED;AACA;AACA;;;AAOA,OAAO,SAASE,OAAT,CAAiBC,aAAjB,EAA0D;AAC/D,QAAMC,QAAQ,GAAGhB,MAAM,EAAvB;AACA,QAAMiB,iBAAiB,GAAGjB,MAAM,EAAhC;AAEA,MAAIe,aAAa,IAAI,IAArB,EAA2B,OAAOF,kBAAkB,EAAzB;;AAE3B,MACEG,QAAQ,CAACE,OAAT,IAAoB,IAApB,IACA,CAACZ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KN,CAACb,IAAD,CALM,CAAT;AAMD","sourcesContent":["import { useRef, useState, useMemo, useCallback, useEffect } from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left?: MMKVConfiguration,\n right?: MMKVConfiguration\n): boolean {\n if (left == null || right == null) return left == null && right == null;\n\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\n/**\n * Use the default, shared MMKV instance.\n */\nexport function useMMKV(): MMKV;\n/**\n * Use a custom MMKV instance with the given configuration.\n * @param configuration The configuration to initialize the MMKV instance with. Does not have to be memoized.\n */\nexport function useMMKV(configuration: MMKVConfiguration): MMKV;\nexport function useMMKV(configuration?: MMKVConfiguration): MMKV {\n const instance = useRef<MMKV>();\n const lastConfiguration = useRef<MMKVConfiguration>();\n\n if (configuration == null) return getDefaultInstance();\n\n if (\n instance.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n return instance.current;\n}\n\nfunction createMMKVHook<\n T extends (boolean | number | string) | undefined,\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n // update value by user set\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n // update value if key changes\n const keyRef = useRef(key);\n useEffect(() => {\n if (key !== keyRef.current) {\n setValue(getter(mmkv, key));\n keyRef.current = key;\n }\n }, [key, mmkv]);\n\n // update value if it changes somewhere else (second hook, same key)\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n\n/**\n * Listen for changes in the given MMKV storage instance.\n * If no instance is passed, the default instance will be used.\n * @param valueChangedListener The function to call whenever a value inside the storage instance changes\n * @param instance The instance to listen to changes to (or the default instance)\n *\n * @example\n * ```ts\n * useMMKVListener((key) => {\n * console.log(`Value for \"${key}\" changed!`)\n * })\n * ```\n */\nexport function useMMKVListener(\n valueChangedListener: (key: string) => void,\n instance?: MMKV\n): void {\n const ref = useRef(valueChangedListener);\n ref.current = valueChangedListener;\n\n const mmkv = instance ?? getDefaultInstance();\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n ref.current(changedKey);\n });\n return () => listener.remove();\n }, [mmkv]);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["hooks.ts"],"names":["useRef","useState","useMemo","useCallback","useEffect","MMKV","isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify","useMMKVListener","valueChangedListener","ref"],"mappings":"AAAA,SAASA,MAAT,EAAiBC,QAAjB,EAA2BC,OAA3B,EAAoCC,WAApC,EAAiDC,SAAjD,QAAkE,OAAlE;AACA,SAASC,IAAT,QAAwC,QAAxC;;AAEA,SAASC,oBAAT,CACEC,IADF,EAEEC,KAFF,EAGW;AACT,MAAID,IAAI,IAAI,IAAR,IAAgBC,KAAK,IAAI,IAA7B,EAAmC,OAAOD,IAAI,IAAI,IAAR,IAAgBC,KAAK,IAAI,IAAhC;AAEnC,SACED,IAAI,CAACE,aAAL,KAAuBD,KAAK,CAACC,aAA7B,IACAF,IAAI,CAACG,EAAL,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D,CAAlB;AACAC,EAAAA,GAAG,CAAChC,OAAJ,GAAc+B,oBAAd;AAEA,QAAM3B,IAAI,GAAGN,QAAH,aAAGA,QAAH,cAAGA,QAAH,GAAeH,kBAAkB,EAA3C;AAEAT,EAAAA,SAAS,CAAC,MAAM;AACd,UAAM2B,QAAQ,GAAGT,IAAI,CAACU,yBAAL,CAAgCC,UAAD,IAAgB;AAC9DiB,MAAAA,GAAG,CAAChC,OAAJ,CAAYe,UAAZ;AACD,KAFgB,CAAjB;AAGA,WAAO,MAAMF,QAAQ,CAACG,MAAT,EAAb;AACD,GALQ,EAKN,CAACZ,IAAD,CALM,CAAT;AAMD","sourcesContent":["import { useRef, useState, useMemo, useCallback, useEffect } from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left?: MMKVConfiguration,\n right?: MMKVConfiguration\n): boolean {\n if (left == null || right == null) return left == null && right == null;\n\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\n/**\n * Use the default, shared MMKV instance.\n */\nexport function useMMKV(): MMKV;\n/**\n * Use a custom MMKV instance with the given configuration.\n * @param configuration The configuration to initialize the MMKV instance with. Does not have to be memoized.\n */\nexport function useMMKV(configuration: MMKVConfiguration): MMKV;\nexport function useMMKV(configuration?: MMKVConfiguration): MMKV {\n const instance = useRef<MMKV>();\n const lastConfiguration = useRef<MMKVConfiguration>();\n\n if (configuration == null) return getDefaultInstance();\n\n if (\n instance.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n return instance.current;\n}\n\nfunction createMMKVHook<\n T extends (boolean | number | string) | undefined,\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n // update value by user set\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n // update value if key or instance changes\n useEffect(() => {\n setValue(getter(mmkv, key));\n }, [key, mmkv]);\n\n // update value if it changes somewhere else (second hook, same key)\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n\n/**\n * Listen for changes in the given MMKV storage instance.\n * If no instance is passed, the default instance will be used.\n * @param valueChangedListener The function to call whenever a value inside the storage instance changes\n * @param instance The instance to listen to changes to (or the default instance)\n *\n * @example\n * ```ts\n * useMMKVListener((key) => {\n * console.log(`Value for \"${key}\" changed!`)\n * })\n * ```\n */\nexport function useMMKVListener(\n valueChangedListener: (key: string) => void,\n instance?: MMKV\n): void {\n const ref = useRef(valueChangedListener);\n ref.current = valueChangedListener;\n\n const mmkv = instance ?? getDefaultInstance();\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n ref.current(changedKey);\n });\n return () => listener.remove();\n }, [mmkv]);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function isJest(): boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-mmkv",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.3",
|
|
4
4
|
"description": "The fastest key/value storage for React Native. ~30x faster than AsyncStorage! Works on Android, iOS and Web.",
|
|
5
5
|
"main": "lib/commonjs/index",
|
|
6
6
|
"module": "lib/module/index",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
"lint-ci": "yarn lint -f ./node_modules/@firmnav/eslint-github-actions-formatter/dist/formatter.js",
|
|
31
31
|
"prepare": "git submodule update --init --recursive",
|
|
32
32
|
"build": "bob build",
|
|
33
|
+
"prepack": "bob build",
|
|
33
34
|
"update-submodule": "git submodule update --remote --merge",
|
|
34
35
|
"release": "release-it",
|
|
35
36
|
"example": "yarn --cwd example",
|