@alwatr/local-storage 6.3.3 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +20 -22
- package/dist/facade.d.ts +2 -3
- package/dist/facade.d.ts.map +1 -1
- package/dist/local-storage.provider.d.ts +28 -37
- package/dist/local-storage.provider.d.ts.map +1 -1
- package/dist/main.cjs +3 -3
- package/dist/main.cjs.map +2 -2
- package/dist/main.mjs +3 -3
- package/dist/main.mjs.map +2 -2
- package/dist/type.d.ts +6 -9
- package/dist/type.d.ts.map +1 -1
- package/package.json +11 -10
- package/src/main.test.js +0 -234
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,32 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [7.0.0](https://github.com/Alwatr/nanolib/compare/@alwatr/local-storage@6.3.4...@alwatr/local-storage@7.0.0) (2025-10-06)
|
|
7
|
+
|
|
8
|
+
### ⚠ BREAKING CHANGES
|
|
9
|
+
|
|
10
|
+
* api changed and defaultValue removed
|
|
11
|
+
|
|
12
|
+
### ✨ Features
|
|
13
|
+
|
|
14
|
+
* implement static method to check existence of versioned item in localStorage ([c622595](https://github.com/Alwatr/nanolib/commit/c622595bcd793746133733b22c7704463d50314d))
|
|
15
|
+
|
|
16
|
+
### 🔨 Code Refactoring
|
|
17
|
+
|
|
18
|
+
* enhance documentation for LocalStorageProviderConfig interface ([11407cd](https://github.com/Alwatr/nanolib/commit/11407cd80ee9def06bcb21c6bb426e92caa7d702))
|
|
19
|
+
* improve documentation for LocalStorageProvider's static methods ([145ac5c](https://github.com/Alwatr/nanolib/commit/145ac5c0d947c9d3f1e91a25e5ca749e0e56d85b))
|
|
20
|
+
* simplify LocalStorageProvider configuration and remove unused types ([b839299](https://github.com/Alwatr/nanolib/commit/b839299d3950f1662773fd8f3a0e6b2189c3d140))
|
|
21
|
+
|
|
22
|
+
### 🔗 Dependencies update
|
|
23
|
+
|
|
24
|
+
* bump the npm-dependencies group with 4 updates ([9825815](https://github.com/Alwatr/nanolib/commit/982581552bbb4b97dca52af5e93a80937f0c3109))
|
|
25
|
+
|
|
26
|
+
## [6.3.4](https://github.com/Alwatr/nanolib/compare/@alwatr/local-storage@6.3.3...@alwatr/local-storage@6.3.4) (2025-09-27)
|
|
27
|
+
|
|
28
|
+
### 🧹 Miscellaneous Chores
|
|
29
|
+
|
|
30
|
+
* exclude test files from package distribution ([86f4f2f](https://github.com/Alwatr/nanolib/commit/86f4f2f5985845c5cf3a3a9398de7b2f98ce53e7))
|
|
31
|
+
|
|
6
32
|
## [6.3.3](https://github.com/Alwatr/nanolib/compare/@alwatr/local-storage@6.3.2...@alwatr/local-storage@6.3.3) (2025-09-22)
|
|
7
33
|
|
|
8
34
|
### 🐛 Bug Fixes
|
package/README.md
CHANGED
|
@@ -14,13 +14,13 @@ It's designed to handle data structure migrations automatically, preventing issu
|
|
|
14
14
|
|
|
15
15
|
This library is built upon a few simple but powerful concepts:
|
|
16
16
|
|
|
17
|
-
1. **Provider Pattern**: Instead of using static functions, you create an _instance_ of a `LocalStorageProvider` for each unique data item you want to manage. This instance is configured once with a name
|
|
17
|
+
1. **Provider Pattern**: Instead of using static functions, you create an _instance_ of a `LocalStorageProvider` for each unique data item you want to manage. This instance is configured once with a name and schemaVersion, and then used to interact with that specific item.
|
|
18
18
|
|
|
19
19
|
2. **Versioning & Automatic Migration**: When you initialize a provider with a new `schemaVersion` number, it automatically removes all older versions of that data from `localStorage`. This prevents conflicts and ensures the application is working with the correct data structure.
|
|
20
20
|
|
|
21
21
|
3. **Facade Factory Function**: The `createLocalStorageProvider` function acts as a clean entry point (Facade) to the library. This simplifies the API and decouples your code from the internal class implementation, making future library upgrades safer and easier.
|
|
22
22
|
|
|
23
|
-
4. **Static Existence Check**: The static method `LocalStorageProvider.has()` allows you to check if data exists _before_ creating a provider instance. This is highly efficient for scenarios where you only need to know if the data is present, without needing the data itself
|
|
23
|
+
4. **Static Existence Check**: The static method `LocalStorageProvider.has()` allows you to check if data exists _before_ creating a provider instance. This is highly efficient for scenarios where you only need to know if the data is present, without needing the data itself.
|
|
24
24
|
|
|
25
25
|
## Installation
|
|
26
26
|
|
|
@@ -52,11 +52,6 @@ interface UserSettings {
|
|
|
52
52
|
const userSettingsProvider = createLocalStorageProvider<UserSettings>({
|
|
53
53
|
name: 'user-settings',
|
|
54
54
|
schemaVersion: 1,
|
|
55
|
-
defaultValue: {
|
|
56
|
-
theme: 'light',
|
|
57
|
-
notifications: true,
|
|
58
|
-
lastLogin: null,
|
|
59
|
-
},
|
|
60
55
|
});
|
|
61
56
|
```
|
|
62
57
|
|
|
@@ -77,20 +72,24 @@ userSettingsProvider.write({
|
|
|
77
72
|
Use the `.read()` method to retrieve the data.
|
|
78
73
|
|
|
79
74
|
- If a value exists in `localStorage` and is valid JSON, it will be parsed and returned.
|
|
80
|
-
- If no value exists or if the stored value is corrupted (invalid JSON),
|
|
75
|
+
- If no value exists or if the stored value is corrupted (invalid JSON), it returns `null`.
|
|
81
76
|
|
|
82
77
|
<!-- end list -->
|
|
83
78
|
|
|
84
79
|
```typescript
|
|
85
80
|
const currentSettings = userSettingsProvider.read();
|
|
86
|
-
|
|
81
|
+
if (currentSettings) {
|
|
82
|
+
console.log(currentSettings.theme); // "dark"
|
|
83
|
+
} else {
|
|
84
|
+
// Handle the case where no data exists
|
|
85
|
+
}
|
|
87
86
|
```
|
|
88
87
|
|
|
89
88
|
### 4\. Checking for Data Existence (The Recommended Way)
|
|
90
89
|
|
|
91
90
|
This is a critical feature for many applications. Before rendering a component or creating a full provider instance, you might need to check if the user has already saved data. Use the static `LocalStorageProvider.has()` method for this.
|
|
92
91
|
|
|
93
|
-
This method is highly efficient as it **does not** require
|
|
92
|
+
This method is highly efficient as it **does not** require creating a class instance.
|
|
94
93
|
|
|
95
94
|
```typescript
|
|
96
95
|
import {LocalStorageProvider} from '@alwatr/local-storage';
|
|
@@ -118,7 +117,7 @@ userSettingsProvider.remove();
|
|
|
118
117
|
## Best Practices
|
|
119
118
|
|
|
120
119
|
- **Always use the `createLocalStorageProvider` factory function.** It provides a stable API that protects your code from internal library changes.
|
|
121
|
-
- **Prefer `LocalStorageProvider.has()` for existence checks.** It's the most performant and cleanest way to check for data without the overhead of creating an instance
|
|
120
|
+
- **Prefer `LocalStorageProvider.has()` for existence checks.** It's the most performant and cleanest way to check for data without the overhead of creating an instance.
|
|
122
121
|
- **Increment the `schemaVersion` number** whenever you make a breaking change to your data structure. The library will handle the cleanup of old data automatically.
|
|
123
122
|
|
|
124
123
|
---
|
|
@@ -152,13 +151,13 @@ Contributions are welcome! Please read our [contribution guidelines](https://git
|
|
|
152
151
|
|
|
153
152
|
این کتابخانه بر پایه چند مفهوم ساده اما قدرتمند بنا شده است:
|
|
154
153
|
|
|
155
|
-
1. **الگوی Provider (ارائهدهنده)**: به جای استفاده از توابع استاتیک، شما برای هر آیتم دادهای که میخواهید مدیریت کنید، یک _نمونه (instance)_ از `LocalStorageProvider` میسازید. این نمونه یک بار با `name
|
|
154
|
+
1. **الگوی Provider (ارائهدهنده)**: به جای استفاده از توابع استاتیک، شما برای هر آیتم دادهای که میخواهید مدیریت کنید، یک _نمونه (instance)_ از `LocalStorageProvider` میسازید. این نمونه یک بار با `name` و `schemaVersion` پیکربندی شده و سپس برای تعامل با آن آیتم خاص استفاده میشود.
|
|
156
155
|
|
|
157
156
|
2. **نسخهبندی و مهاجرت خودکار**: هنگامی که شما یک Provider را با شماره `schemaVersion` جدیدی مقداردهی اولیه میکنید، این کتابخانه به طور خودکار تمام نسخههای قدیمیتر آن داده را از `localStorage` حذف میکند. این کار از تداخل جلوگیری کرده و تضمین میکند که اپلیکیشن همیشه با ساختار داده صحیح کار میکند.
|
|
158
157
|
|
|
159
158
|
3. **تابع سازنده Facade**: تابع `createLocalStorageProvider` به عنوان یک نقطه ورود تمیز (Facade) به کتابخانه عمل میکند. این کار API را ساده کرده و کد شما را از پیادهسازی داخلی کلاسها جدا (decouple) میسازد، که باعث میشود ارتقاء کتابخانه در آینده امنتر و آسانتر باشد.
|
|
160
159
|
|
|
161
|
-
4. **بررسی استاتیک وجود داده**: متد استاتیک `LocalStorageProvider.has()` به شما اجازه میدهد وجود داده را _قبل_ از ساختن یک نمونه از Provider بررسی کنید. این روش برای سناریوهایی که فقط نیاز دارید بدانید دادهای وجود دارد یا نه
|
|
160
|
+
4. **بررسی استاتیک وجود داده**: متد استاتیک `LocalStorageProvider.has()` به شما اجازه میدهد وجود داده را _قبل_ از ساختن یک نمونه از Provider بررسی کنید. این روش برای سناریوهایی که فقط نیاز دارید بدانید دادهای وجود دارد یا نه بسیار کارآمد است.
|
|
162
161
|
|
|
163
162
|
## نصب
|
|
164
163
|
|
|
@@ -190,11 +189,6 @@ interface UserSettings {
|
|
|
190
189
|
const userSettingsProvider = createLocalStorageProvider<UserSettings>({
|
|
191
190
|
name: 'user-settings',
|
|
192
191
|
schemaVersion: 1,
|
|
193
|
-
defaultValue: {
|
|
194
|
-
theme: 'light',
|
|
195
|
-
notifications: true,
|
|
196
|
-
lastLogin: null,
|
|
197
|
-
},
|
|
198
192
|
});
|
|
199
193
|
```
|
|
200
194
|
|
|
@@ -215,20 +209,24 @@ userSettingsProvider.write({
|
|
|
215
209
|
از متد `.read()` برای بازیابی داده استفاده کنید.
|
|
216
210
|
|
|
217
211
|
- اگر مقداری در `localStorage` وجود داشته باشد و JSON معتبر باشد، آن مقدار parse شده و برگردانده میشود.
|
|
218
|
-
- اگر مقداری وجود نداشته باشد یا مقدار ذخیره شده خراب باشد (JSON نامعتبر)، `
|
|
212
|
+
- اگر مقداری وجود نداشته باشد یا مقدار ذخیره شده خراب باشد (JSON نامعتبر)، `null` برگردانده میشود.
|
|
219
213
|
|
|
220
214
|
<!-- end list -->
|
|
221
215
|
|
|
222
216
|
```typescript
|
|
223
217
|
const currentSettings = userSettingsProvider.read();
|
|
224
|
-
|
|
218
|
+
if (currentSettings) {
|
|
219
|
+
console.log(currentSettings.theme); // "dark"
|
|
220
|
+
} else {
|
|
221
|
+
// مدیریت حالت عدم وجود داده
|
|
222
|
+
}
|
|
225
223
|
```
|
|
226
224
|
|
|
227
225
|
### ۴. بررسی وجود داده (روش پیشنهادی)
|
|
228
226
|
|
|
229
227
|
این یک قابلیت حیاتی برای بسیاری از اپلیکیشنها است. قبل از رندر کردن یک کامپوننت یا ساختن یک نمونه کامل از Provider، ممکن است لازم باشد بررسی کنید که آیا کاربر قبلاً دادهای ذخیره کرده است یا خیر. برای این کار از متد استاتیک `LocalStorageProvider.has()` استفاده کنید.
|
|
230
228
|
|
|
231
|
-
این متد بسیار کارآمد است زیرا
|
|
229
|
+
این متد بسیار کارآمد است زیرا یک نمونه از کلاس نمیسازد.
|
|
232
230
|
|
|
233
231
|
```typescript
|
|
234
232
|
import {LocalStorageProvider} from '@alwatr/local-storage';
|
|
@@ -256,7 +254,7 @@ userSettingsProvider.remove();
|
|
|
256
254
|
## بهترین روشها (Best Practices)
|
|
257
255
|
|
|
258
256
|
- **همیشه از تابع سازنده `createLocalStorageProvider` استفاده کنید.** این تابع یک API پایدار فراهم میکند که کد شما را در برابر تغییرات داخلی کتابخانه محافظت میکند.
|
|
259
|
-
- **برای بررسی وجود داده، `LocalStorageProvider.has()` را ترجیح دهید.** این کارآمدترین و تمیزترین روش برای بررسی وجود داده بدون سربار ساختن یک نمونه
|
|
257
|
+
- **برای بررسی وجود داده، `LocalStorageProvider.has()` را ترجیح دهید.** این کارآمدترین و تمیزترین روش برای بررسی وجود داده بدون سربار ساختن یک نمونه است.
|
|
260
258
|
- **هر زمان که یک تغییر ساختاری در دادههای خود ایجاد کردید که با نسخههای قبلی ناسازگار است، شماره `schemaVersion` را افزایش دهید.** کتابخانه پاکسازی دادههای قدیمی را به صورت خودکار انجام خواهد داد.
|
|
261
259
|
|
|
262
260
|
## حامیان (Sponsors)
|
package/dist/facade.d.ts
CHANGED
|
@@ -10,8 +10,7 @@ import type { LocalStorageProviderConfig } from './type.js';
|
|
|
10
10
|
* ```typescript
|
|
11
11
|
* const userSettings = createLocalStorageProvider({
|
|
12
12
|
* name: 'user-settings',
|
|
13
|
-
* schemaVersion: 1
|
|
14
|
-
* defaultValue: { theme: 'light', notifications: true }
|
|
13
|
+
* schemaVersion: 1
|
|
15
14
|
* });
|
|
16
15
|
*
|
|
17
16
|
* // Write new settings
|
|
@@ -22,5 +21,5 @@ import type { LocalStorageProviderConfig } from './type.js';
|
|
|
22
21
|
* console.log(currentSettings); // { theme: 'dark', notifications: false }
|
|
23
22
|
* ```
|
|
24
23
|
*/
|
|
25
|
-
export declare function createLocalStorageProvider<T extends JsonValue>(config: LocalStorageProviderConfig
|
|
24
|
+
export declare function createLocalStorageProvider<T extends JsonValue>(config: LocalStorageProviderConfig): LocalStorageProvider<T>;
|
|
26
25
|
//# sourceMappingURL=facade.d.ts.map
|
package/dist/facade.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"facade.d.ts","sourceRoot":"","sources":["../src/facade.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,oBAAoB,EAAC,MAAM,6BAA6B,CAAC;AAEjE,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,WAAW,CAAC;AAE1D
|
|
1
|
+
{"version":3,"file":"facade.d.ts","sourceRoot":"","sources":["../src/facade.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,oBAAoB,EAAC,MAAM,6BAA6B,CAAC;AAEjE,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,WAAW,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,0BAA0B,GAAG,oBAAoB,CAAC,CAAC,CAAC,CAE3H"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LocalStorageProviderConfig
|
|
1
|
+
import type { LocalStorageProviderConfig } from './type.js';
|
|
2
2
|
/**
|
|
3
3
|
* A provider class for managing a specific, versioned item in localStorage.
|
|
4
4
|
* It encapsulates the logic for key generation, serialization, and migration.
|
|
@@ -7,8 +7,7 @@ import type { LocalStorageProviderConfig, StorageMeta } from './type.js';
|
|
|
7
7
|
* ```typescript
|
|
8
8
|
* const userSettings = new LocalStorageProvider({
|
|
9
9
|
* name: 'user-settings',
|
|
10
|
-
* version: 1
|
|
11
|
-
* defaultValue: { theme: 'light', notifications: true }
|
|
10
|
+
* version: 1
|
|
12
11
|
* });
|
|
13
12
|
*
|
|
14
13
|
* // Write new settings
|
|
@@ -23,54 +22,50 @@ export declare class LocalStorageProvider<T extends JsonValue> {
|
|
|
23
22
|
static readonly version: string;
|
|
24
23
|
private readonly key__;
|
|
25
24
|
protected readonly logger_: import("@alwatr/logger").AlwatrLogger;
|
|
26
|
-
|
|
27
|
-
protected readonly defaultValue__: T;
|
|
28
|
-
constructor(config: LocalStorageProviderConfig<T>);
|
|
25
|
+
constructor(config: LocalStorageProviderConfig);
|
|
29
26
|
/**
|
|
30
27
|
* Generates the versioned storage key.
|
|
31
28
|
* @param meta - An object containing the name and schemaVersion.
|
|
32
29
|
* @returns The versioned key string.
|
|
33
30
|
*/
|
|
34
|
-
static getKey(
|
|
31
|
+
static getKey(config: LocalStorageProviderConfig): string;
|
|
35
32
|
/**
|
|
36
|
-
*
|
|
37
|
-
|
|
33
|
+
* Manages data migration by removing all previous versions of the item.
|
|
34
|
+
*/
|
|
35
|
+
static clearPreviousStorageVersions(config: LocalStorageProviderConfig): void;
|
|
36
|
+
/**
|
|
37
|
+
* Checks if a versioned item exists in localStorage for the given configuration.
|
|
38
|
+
* This static method allows checking for the existence of a specific versioned item
|
|
39
|
+
* without instantiating the provider.
|
|
38
40
|
*
|
|
39
|
-
* @param
|
|
40
|
-
* @returns `true` if the item exists, otherwise `false`.
|
|
41
|
+
* @param config - The configuration object containing the name and schemaVersion.
|
|
42
|
+
* @returns `true` if the item exists in localStorage, otherwise `false`.
|
|
41
43
|
*
|
|
42
44
|
* @example
|
|
43
45
|
* ```typescript
|
|
44
|
-
* const
|
|
45
|
-
* if (formExists) {
|
|
46
|
-
* // Show the "Thank you" message
|
|
47
|
-
* } else {
|
|
48
|
-
* // Show the form
|
|
49
|
-
* }
|
|
46
|
+
* const exists = LocalStorageProvider.has({ name: 'user-form', schemaVersion: 1 });
|
|
50
47
|
* ```
|
|
51
48
|
*/
|
|
52
|
-
static has(
|
|
49
|
+
static has(config: LocalStorageProviderConfig): boolean;
|
|
53
50
|
/**
|
|
54
|
-
*
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Converts the provided data to a JSON-compatible format by simulating
|
|
59
|
-
* a serialization/deserialization cycle. This ensures that the data
|
|
60
|
-
* conforms to the `T` type.
|
|
51
|
+
* Checks if the current versioned item exists in localStorage.
|
|
52
|
+
*
|
|
53
|
+
* @returns `true` if the item exists in localStorage, otherwise `false`.
|
|
61
54
|
*
|
|
62
|
-
* @
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```typescript
|
|
57
|
+
* const provider = new LocalStorageProvider({ name: 'profile', schemaVersion: 2 });
|
|
58
|
+
* if (provider.has()) {
|
|
59
|
+
* // Item exists
|
|
60
|
+
* }
|
|
61
|
+
* ```
|
|
66
62
|
*/
|
|
67
|
-
|
|
63
|
+
has(): boolean;
|
|
68
64
|
/**
|
|
69
65
|
* Reads and parses the value from localStorage.
|
|
70
|
-
* If the item doesn't exist
|
|
71
|
-
* it writes and returns the default value.
|
|
66
|
+
* If the item doesn't exist or is invalid JSON, returns null.
|
|
72
67
|
*/
|
|
73
|
-
read(): T;
|
|
68
|
+
read(): T | null;
|
|
74
69
|
/**
|
|
75
70
|
* Serializes and writes a value to localStorage.
|
|
76
71
|
*/
|
|
@@ -79,9 +74,5 @@ export declare class LocalStorageProvider<T extends JsonValue> {
|
|
|
79
74
|
* Removes the item from localStorage.
|
|
80
75
|
*/
|
|
81
76
|
remove(): void;
|
|
82
|
-
/**
|
|
83
|
-
* Manages data migration by removing all previous versions of the item.
|
|
84
|
-
*/
|
|
85
|
-
private migrate__;
|
|
86
77
|
}
|
|
87
78
|
//# sourceMappingURL=local-storage.provider.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-storage.provider.d.ts","sourceRoot":"","sources":["../src/local-storage.provider.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,0BAA0B,
|
|
1
|
+
{"version":3,"file":"local-storage.provider.d.ts","sourceRoot":"","sources":["../src/local-storage.provider.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,WAAW,CAAC;AAE1D;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,oBAAoB,CAAC,CAAC,SAAS,SAAS;IACnD,gBAAuB,OAAO,SAAuB;IAErD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,SAAS,CAAC,QAAQ,CAAC,OAAO,wCAAC;gBAEf,MAAM,EAAE,0BAA0B;IAO9C;;;;OAIG;WACW,MAAM,CAAC,MAAM,EAAE,0BAA0B,GAAG,MAAM;IAIhE;;OAEG;WACW,4BAA4B,CAAC,MAAM,EAAE,0BAA0B,GAAG,IAAI;IAUpF;;;;;;;;;;;;OAYG;WACW,GAAG,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO;IAK9D;;;;;;;;;;;;OAYG;IACI,GAAG,IAAI,OAAO;IAIrB;;;OAGG;IACI,IAAI,IAAI,CAAC,GAAG,IAAI;IA0BvB;;OAEG;IACI,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI;IAmB5B;;OAEG;IACI,MAAM,IAAI,IAAI;CAGtB"}
|
package/dist/main.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** 📦 @alwatr/local-storage
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/local-storage
|
|
3
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{LocalStorageProvider:()=>LocalStorageProvider,createLocalStorageProvider:()=>createLocalStorageProvider});module.exports=__toCommonJS(main_exports);var import_logger=require("@alwatr/logger");var LocalStorageProvider=class _LocalStorageProvider{static{this.version="
|
|
1
|
+
/** 📦 @alwatr/local-storage v7.0.0 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/local-storage v7.0.0");
|
|
3
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{LocalStorageProvider:()=>LocalStorageProvider,createLocalStorageProvider:()=>createLocalStorageProvider});module.exports=__toCommonJS(main_exports);var import_logger=require("@alwatr/logger");var LocalStorageProvider=class _LocalStorageProvider{static{this.version="7.0.0"}constructor(config){this.logger_=(0,import_logger.createLogger)(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);this.logger_.logMethodArgs?.("constructor",{config});this.key__=_LocalStorageProvider.getKey(config);_LocalStorageProvider.clearPreviousStorageVersions(config)}static getKey(config){return`${config.name}.v${config.schemaVersion}`}static clearPreviousStorageVersions(config){if(config.schemaVersion<1)return;for(let i=0;i<config.schemaVersion;i++){const oldKey=_LocalStorageProvider.getKey({name:config.name,schemaVersion:i});localStorage.removeItem(oldKey)}}static has(config){const key=_LocalStorageProvider.getKey(config);return localStorage.getItem(key)!==null}has(){return localStorage.getItem(this.key__)!==null}read(){let value=null;try{value=localStorage.getItem(this.key__)}catch(err){this.logger_.error("read","read_local_storage_error",{err})}if(!value){this.logger_.logMethod?.("read//no_value");return null}try{const parsedValue=JSON.parse(value);this.logger_.logMethodFull?.("read//value",void 0,{parsedValue});return parsedValue}catch(err){this.logger_.error("read","read_parse_error",{err});return null}}write(value){this.logger_.logMethodArgs?.("write",{value});let valueStr;try{valueStr=JSON.stringify(value)}catch(err){this.logger_.error("write","write_stringify_error",{err});throw new Error("write_stringify_error")}try{localStorage.setItem(this.key__,valueStr)}catch(err){this.logger_.error("write","write_local_storage_error",{err})}}remove(){localStorage.removeItem(this.key__)}};function createLocalStorageProvider(config){return new LocalStorageProvider(config)}0&&(module.exports={LocalStorageProvider,createLocalStorageProvider});
|
|
4
4
|
//# sourceMappingURL=main.cjs.map
|
package/dist/main.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/main.ts", "../src/local-storage.provider.ts", "../src/facade.ts"],
|
|
4
|
-
"sourcesContent": ["export * from './local-storage.provider.js';\nexport * from './facade.js';\nexport type * from './type.js';\n", "import {createLogger} from '@alwatr/logger';\n\nimport type {LocalStorageProviderConfig
|
|
5
|
-
"mappings": ";;qqBAAA,+LCAA,kBAA2B,
|
|
4
|
+
"sourcesContent": ["export * from './local-storage.provider.js';\nexport * from './facade.js';\nexport type * from './type.js';\n", "import {createLogger} from '@alwatr/logger';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * A provider class for managing a specific, versioned item in localStorage.\n * It encapsulates the logic for key generation, serialization, and migration.\n *\n * @example\n * ```typescript\n * const userSettings = new LocalStorageProvider({\n * name: 'user-settings',\n * version: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport class LocalStorageProvider<T extends JsonValue> {\n public static readonly version = __package_version__;\n\n private readonly key__: string;\n protected readonly logger_;\n\n constructor(config: LocalStorageProviderConfig) {\n this.logger_ = createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);\n this.logger_.logMethodArgs?.('constructor', {config});\n this.key__ = LocalStorageProvider.getKey(config);\n LocalStorageProvider.clearPreviousStorageVersions(config);\n }\n\n /**\n * Generates the versioned storage key.\n * @param meta - An object containing the name and schemaVersion.\n * @returns The versioned key string.\n */\n public static getKey(config: LocalStorageProviderConfig): string {\n return `${config.name}.v${config.schemaVersion}`;\n }\n\n /**\n * Manages data migration by removing all previous versions of the item.\n */\n public static clearPreviousStorageVersions(config: LocalStorageProviderConfig): void {\n if (config.schemaVersion < 1) return;\n\n // Iterate from v1 up to the version just before the current one and remove them.\n for (let i = 0; i < config.schemaVersion; i++) {\n const oldKey = LocalStorageProvider.getKey({name: config.name, schemaVersion: i});\n localStorage.removeItem(oldKey);\n }\n }\n\n /**\n * Checks if a versioned item exists in localStorage for the given configuration.\n * This static method allows checking for the existence of a specific versioned item\n * without instantiating the provider.\n *\n * @param config - The configuration object containing the name and schemaVersion.\n * @returns `true` if the item exists in localStorage, otherwise `false`.\n *\n * @example\n * ```typescript\n * const exists = LocalStorageProvider.has({ name: 'user-form', schemaVersion: 1 });\n * ```\n */\n public static has(config: LocalStorageProviderConfig): boolean {\n const key = LocalStorageProvider.getKey(config);\n return localStorage.getItem(key) !== null;\n }\n\n /**\n * Checks if the current versioned item exists in localStorage.\n *\n * @returns `true` if the item exists in localStorage, otherwise `false`.\n *\n * @example\n * ```typescript\n * const provider = new LocalStorageProvider({ name: 'profile', schemaVersion: 2 });\n * if (provider.has()) {\n * // Item exists\n * }\n * ```\n */\n public has(): boolean {\n return localStorage.getItem(this.key__) !== null;\n }\n\n /**\n * Reads and parses the value from localStorage.\n * If the item doesn't exist or is invalid JSON, returns null.\n */\n public read(): T | null {\n let value: string | null = null;\n\n try {\n value = localStorage.getItem(this.key__);\n }\n catch (err) {\n this.logger_.error('read', 'read_local_storage_error', {err});\n }\n\n if (!value) {\n this.logger_.logMethod?.('read//no_value');\n return null;\n }\n\n try {\n const parsedValue = JSON.parse(value) as T;\n this.logger_.logMethodFull?.('read//value', undefined, {parsedValue});\n return parsedValue;\n }\n catch (err) {\n this.logger_.error('read', 'read_parse_error', {err});\n return null;\n }\n }\n\n /**\n * Serializes and writes a value to localStorage.\n */\n public write(value: T): void {\n this.logger_.logMethodArgs?.('write', {value});\n let valueStr: string;\n try {\n valueStr = JSON.stringify(value);\n }\n catch (err) {\n this.logger_.error('write', 'write_stringify_error', {err});\n throw new Error('write_stringify_error');\n }\n\n try {\n localStorage.setItem(this.key__, valueStr);\n }\n catch (err) {\n this.logger_.error('write', 'write_local_storage_error', {err});\n }\n }\n\n /**\n * Removes the item from localStorage.\n */\n public remove(): void {\n localStorage.removeItem(this.key__);\n }\n}\n", "import {LocalStorageProvider} from './local-storage.provider.js';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * Factory function to create a new LocalStorageProvider.\n *\n * @param config - The configuration for the provider.\n * @returns An instance of LocalStorageProvider.\n *\n * @example\n * ```typescript\n * const userSettings = createLocalStorageProvider({\n * name: 'user-settings',\n * schemaVersion: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport function createLocalStorageProvider<T extends JsonValue>(config: LocalStorageProviderConfig): LocalStorageProvider<T> {\n return new LocalStorageProvider<T>(config);\n}\n"],
|
|
5
|
+
"mappings": ";;qqBAAA,+LCAA,kBAA2B,0BAuBpB,IAAM,qBAAN,MAAM,qBAA0C,CACrD,YAAuB,QAAU,QAKjC,YAAY,OAAoC,CAC9C,KAAK,WAAU,4BAAa,2BAA2B,OAAO,IAAI,QAAQ,OAAO,aAAa,EAAE,EAChG,KAAK,QAAQ,gBAAgB,cAAe,CAAC,MAAM,CAAC,EACpD,KAAK,MAAQ,sBAAqB,OAAO,MAAM,EAC/C,sBAAqB,6BAA6B,MAAM,CAC1D,CAOA,OAAc,OAAO,OAA4C,CAC/D,MAAO,GAAG,OAAO,IAAI,KAAK,OAAO,aAAa,EAChD,CAKA,OAAc,6BAA6B,OAA0C,CACnF,GAAI,OAAO,cAAgB,EAAG,OAG9B,QAAS,EAAI,EAAG,EAAI,OAAO,cAAe,IAAK,CAC7C,MAAM,OAAS,sBAAqB,OAAO,CAAC,KAAM,OAAO,KAAM,cAAe,CAAC,CAAC,EAChF,aAAa,WAAW,MAAM,CAChC,CACF,CAeA,OAAc,IAAI,OAA6C,CAC7D,MAAM,IAAM,sBAAqB,OAAO,MAAM,EAC9C,OAAO,aAAa,QAAQ,GAAG,IAAM,IACvC,CAeO,KAAe,CACpB,OAAO,aAAa,QAAQ,KAAK,KAAK,IAAM,IAC9C,CAMO,MAAiB,CACtB,IAAI,MAAuB,KAE3B,GAAI,CACF,MAAQ,aAAa,QAAQ,KAAK,KAAK,CACzC,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,OAAQ,2BAA4B,CAAC,GAAG,CAAC,CAC9D,CAEA,GAAI,CAAC,MAAO,CACV,KAAK,QAAQ,YAAY,gBAAgB,EACzC,OAAO,IACT,CAEA,GAAI,CACF,MAAM,YAAc,KAAK,MAAM,KAAK,EACpC,KAAK,QAAQ,gBAAgB,cAAe,OAAW,CAAC,WAAW,CAAC,EACpE,OAAO,WACT,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,OAAQ,mBAAoB,CAAC,GAAG,CAAC,EACpD,OAAO,IACT,CACF,CAKO,MAAM,MAAgB,CAC3B,KAAK,QAAQ,gBAAgB,QAAS,CAAC,KAAK,CAAC,EAC7C,IAAI,SACJ,GAAI,CACF,SAAW,KAAK,UAAU,KAAK,CACjC,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,QAAS,wBAAyB,CAAC,GAAG,CAAC,EAC1D,MAAM,IAAI,MAAM,uBAAuB,CACzC,CAEA,GAAI,CACF,aAAa,QAAQ,KAAK,MAAO,QAAQ,CAC3C,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,QAAS,4BAA6B,CAAC,GAAG,CAAC,CAChE,CACF,CAKO,QAAe,CACpB,aAAa,WAAW,KAAK,KAAK,CACpC,CACF,EC9HO,SAAS,2BAAgD,OAA6D,CAC3H,OAAO,IAAI,qBAAwB,MAAM,CAC3C",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** 📦 @alwatr/local-storage
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/local-storage
|
|
3
|
-
import{createLogger}from"@alwatr/logger";var LocalStorageProvider=class _LocalStorageProvider{static{this.version="
|
|
1
|
+
/** 📦 @alwatr/local-storage v7.0.0 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/local-storage v7.0.0");
|
|
3
|
+
import{createLogger}from"@alwatr/logger";var LocalStorageProvider=class _LocalStorageProvider{static{this.version="7.0.0"}constructor(config){this.logger_=createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);this.logger_.logMethodArgs?.("constructor",{config});this.key__=_LocalStorageProvider.getKey(config);_LocalStorageProvider.clearPreviousStorageVersions(config)}static getKey(config){return`${config.name}.v${config.schemaVersion}`}static clearPreviousStorageVersions(config){if(config.schemaVersion<1)return;for(let i=0;i<config.schemaVersion;i++){const oldKey=_LocalStorageProvider.getKey({name:config.name,schemaVersion:i});localStorage.removeItem(oldKey)}}static has(config){const key=_LocalStorageProvider.getKey(config);return localStorage.getItem(key)!==null}has(){return localStorage.getItem(this.key__)!==null}read(){let value=null;try{value=localStorage.getItem(this.key__)}catch(err){this.logger_.error("read","read_local_storage_error",{err})}if(!value){this.logger_.logMethod?.("read//no_value");return null}try{const parsedValue=JSON.parse(value);this.logger_.logMethodFull?.("read//value",void 0,{parsedValue});return parsedValue}catch(err){this.logger_.error("read","read_parse_error",{err});return null}}write(value){this.logger_.logMethodArgs?.("write",{value});let valueStr;try{valueStr=JSON.stringify(value)}catch(err){this.logger_.error("write","write_stringify_error",{err});throw new Error("write_stringify_error")}try{localStorage.setItem(this.key__,valueStr)}catch(err){this.logger_.error("write","write_local_storage_error",{err})}}remove(){localStorage.removeItem(this.key__)}};function createLocalStorageProvider(config){return new LocalStorageProvider(config)}export{LocalStorageProvider,createLocalStorageProvider};
|
|
4
4
|
//# sourceMappingURL=main.mjs.map
|
package/dist/main.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/local-storage.provider.ts", "../src/facade.ts"],
|
|
4
|
-
"sourcesContent": ["import {createLogger} from '@alwatr/logger';\n\nimport type {LocalStorageProviderConfig
|
|
5
|
-
"mappings": ";;AAAA,OAAQ,iBAAmB,
|
|
4
|
+
"sourcesContent": ["import {createLogger} from '@alwatr/logger';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * A provider class for managing a specific, versioned item in localStorage.\n * It encapsulates the logic for key generation, serialization, and migration.\n *\n * @example\n * ```typescript\n * const userSettings = new LocalStorageProvider({\n * name: 'user-settings',\n * version: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport class LocalStorageProvider<T extends JsonValue> {\n public static readonly version = __package_version__;\n\n private readonly key__: string;\n protected readonly logger_;\n\n constructor(config: LocalStorageProviderConfig) {\n this.logger_ = createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);\n this.logger_.logMethodArgs?.('constructor', {config});\n this.key__ = LocalStorageProvider.getKey(config);\n LocalStorageProvider.clearPreviousStorageVersions(config);\n }\n\n /**\n * Generates the versioned storage key.\n * @param meta - An object containing the name and schemaVersion.\n * @returns The versioned key string.\n */\n public static getKey(config: LocalStorageProviderConfig): string {\n return `${config.name}.v${config.schemaVersion}`;\n }\n\n /**\n * Manages data migration by removing all previous versions of the item.\n */\n public static clearPreviousStorageVersions(config: LocalStorageProviderConfig): void {\n if (config.schemaVersion < 1) return;\n\n // Iterate from v1 up to the version just before the current one and remove them.\n for (let i = 0; i < config.schemaVersion; i++) {\n const oldKey = LocalStorageProvider.getKey({name: config.name, schemaVersion: i});\n localStorage.removeItem(oldKey);\n }\n }\n\n /**\n * Checks if a versioned item exists in localStorage for the given configuration.\n * This static method allows checking for the existence of a specific versioned item\n * without instantiating the provider.\n *\n * @param config - The configuration object containing the name and schemaVersion.\n * @returns `true` if the item exists in localStorage, otherwise `false`.\n *\n * @example\n * ```typescript\n * const exists = LocalStorageProvider.has({ name: 'user-form', schemaVersion: 1 });\n * ```\n */\n public static has(config: LocalStorageProviderConfig): boolean {\n const key = LocalStorageProvider.getKey(config);\n return localStorage.getItem(key) !== null;\n }\n\n /**\n * Checks if the current versioned item exists in localStorage.\n *\n * @returns `true` if the item exists in localStorage, otherwise `false`.\n *\n * @example\n * ```typescript\n * const provider = new LocalStorageProvider({ name: 'profile', schemaVersion: 2 });\n * if (provider.has()) {\n * // Item exists\n * }\n * ```\n */\n public has(): boolean {\n return localStorage.getItem(this.key__) !== null;\n }\n\n /**\n * Reads and parses the value from localStorage.\n * If the item doesn't exist or is invalid JSON, returns null.\n */\n public read(): T | null {\n let value: string | null = null;\n\n try {\n value = localStorage.getItem(this.key__);\n }\n catch (err) {\n this.logger_.error('read', 'read_local_storage_error', {err});\n }\n\n if (!value) {\n this.logger_.logMethod?.('read//no_value');\n return null;\n }\n\n try {\n const parsedValue = JSON.parse(value) as T;\n this.logger_.logMethodFull?.('read//value', undefined, {parsedValue});\n return parsedValue;\n }\n catch (err) {\n this.logger_.error('read', 'read_parse_error', {err});\n return null;\n }\n }\n\n /**\n * Serializes and writes a value to localStorage.\n */\n public write(value: T): void {\n this.logger_.logMethodArgs?.('write', {value});\n let valueStr: string;\n try {\n valueStr = JSON.stringify(value);\n }\n catch (err) {\n this.logger_.error('write', 'write_stringify_error', {err});\n throw new Error('write_stringify_error');\n }\n\n try {\n localStorage.setItem(this.key__, valueStr);\n }\n catch (err) {\n this.logger_.error('write', 'write_local_storage_error', {err});\n }\n }\n\n /**\n * Removes the item from localStorage.\n */\n public remove(): void {\n localStorage.removeItem(this.key__);\n }\n}\n", "import {LocalStorageProvider} from './local-storage.provider.js';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * Factory function to create a new LocalStorageProvider.\n *\n * @param config - The configuration for the provider.\n * @returns An instance of LocalStorageProvider.\n *\n * @example\n * ```typescript\n * const userSettings = createLocalStorageProvider({\n * name: 'user-settings',\n * schemaVersion: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport function createLocalStorageProvider<T extends JsonValue>(config: LocalStorageProviderConfig): LocalStorageProvider<T> {\n return new LocalStorageProvider<T>(config);\n}\n"],
|
|
5
|
+
"mappings": ";;AAAA,OAAQ,iBAAmB,iBAuBpB,IAAM,qBAAN,MAAM,qBAA0C,CACrD,YAAuB,QAAU,QAKjC,YAAY,OAAoC,CAC9C,KAAK,QAAU,aAAa,2BAA2B,OAAO,IAAI,QAAQ,OAAO,aAAa,EAAE,EAChG,KAAK,QAAQ,gBAAgB,cAAe,CAAC,MAAM,CAAC,EACpD,KAAK,MAAQ,sBAAqB,OAAO,MAAM,EAC/C,sBAAqB,6BAA6B,MAAM,CAC1D,CAOA,OAAc,OAAO,OAA4C,CAC/D,MAAO,GAAG,OAAO,IAAI,KAAK,OAAO,aAAa,EAChD,CAKA,OAAc,6BAA6B,OAA0C,CACnF,GAAI,OAAO,cAAgB,EAAG,OAG9B,QAAS,EAAI,EAAG,EAAI,OAAO,cAAe,IAAK,CAC7C,MAAM,OAAS,sBAAqB,OAAO,CAAC,KAAM,OAAO,KAAM,cAAe,CAAC,CAAC,EAChF,aAAa,WAAW,MAAM,CAChC,CACF,CAeA,OAAc,IAAI,OAA6C,CAC7D,MAAM,IAAM,sBAAqB,OAAO,MAAM,EAC9C,OAAO,aAAa,QAAQ,GAAG,IAAM,IACvC,CAeO,KAAe,CACpB,OAAO,aAAa,QAAQ,KAAK,KAAK,IAAM,IAC9C,CAMO,MAAiB,CACtB,IAAI,MAAuB,KAE3B,GAAI,CACF,MAAQ,aAAa,QAAQ,KAAK,KAAK,CACzC,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,OAAQ,2BAA4B,CAAC,GAAG,CAAC,CAC9D,CAEA,GAAI,CAAC,MAAO,CACV,KAAK,QAAQ,YAAY,gBAAgB,EACzC,OAAO,IACT,CAEA,GAAI,CACF,MAAM,YAAc,KAAK,MAAM,KAAK,EACpC,KAAK,QAAQ,gBAAgB,cAAe,OAAW,CAAC,WAAW,CAAC,EACpE,OAAO,WACT,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,OAAQ,mBAAoB,CAAC,GAAG,CAAC,EACpD,OAAO,IACT,CACF,CAKO,MAAM,MAAgB,CAC3B,KAAK,QAAQ,gBAAgB,QAAS,CAAC,KAAK,CAAC,EAC7C,IAAI,SACJ,GAAI,CACF,SAAW,KAAK,UAAU,KAAK,CACjC,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,QAAS,wBAAyB,CAAC,GAAG,CAAC,EAC1D,MAAM,IAAI,MAAM,uBAAuB,CACzC,CAEA,GAAI,CACF,aAAa,QAAQ,KAAK,MAAO,QAAQ,CAC3C,OACO,IAAK,CACV,KAAK,QAAQ,MAAM,QAAS,4BAA6B,CAAC,GAAG,CAAC,CAChE,CACF,CAKO,QAAe,CACpB,aAAa,WAAW,KAAK,KAAK,CACpC,CACF,EC9HO,SAAS,2BAAgD,OAA6D,CAC3H,OAAO,IAAI,qBAAwB,MAAM,CAC3C",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/type.d.ts
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Configuration options for a local storage provider.
|
|
3
|
+
*/
|
|
4
|
+
export interface LocalStorageProviderConfig {
|
|
2
5
|
/**
|
|
3
6
|
* The unique name for the storage item.
|
|
4
7
|
*/
|
|
5
8
|
name: string;
|
|
6
9
|
/**
|
|
7
|
-
* The data structure
|
|
8
|
-
*
|
|
10
|
+
* The version of the data structure.
|
|
11
|
+
* Start from 1 for production, 0 for development mode, and increment by 1 for each new data schema change.
|
|
9
12
|
*/
|
|
10
13
|
schemaVersion: number;
|
|
11
14
|
}
|
|
12
|
-
export interface LocalStorageProviderConfig<T extends JsonValue> extends StorageMeta {
|
|
13
|
-
/**
|
|
14
|
-
* The default value to use if no value is stored.
|
|
15
|
-
*/
|
|
16
|
-
defaultValue: T;
|
|
17
|
-
}
|
|
18
15
|
//# sourceMappingURL=type.d.ts.map
|
package/dist/type.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;CACvB"}
|
package/package.json
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/local-storage",
|
|
3
3
|
"description": "A modern, simple, and robust solution for managing versioned JSON objects in the browser's `localStorage`. This package provides a clean, class-based API with a factory function to ensure your application's data persistence is safe, maintainable, and future-proof.",
|
|
4
|
-
"version": "
|
|
4
|
+
"version": "7.0.0",
|
|
5
5
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
|
|
6
6
|
"bugs": "https://github.com/Alwatr/nanolib/issues",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@alwatr/logger": "6.0.
|
|
8
|
+
"@alwatr/logger": "6.0.9"
|
|
9
9
|
},
|
|
10
10
|
"devDependencies": {
|
|
11
|
-
"@alwatr/nano-build": "6.3.
|
|
12
|
-
"@alwatr/prettier-config": "5.0.
|
|
13
|
-
"@alwatr/tsconfig-base": "6.0.
|
|
14
|
-
"@alwatr/type-helper": "6.1.
|
|
15
|
-
"@jest/globals": "^30.
|
|
16
|
-
"typescript": "^5.9.
|
|
11
|
+
"@alwatr/nano-build": "6.3.5",
|
|
12
|
+
"@alwatr/prettier-config": "5.0.5",
|
|
13
|
+
"@alwatr/tsconfig-base": "6.0.3",
|
|
14
|
+
"@alwatr/type-helper": "6.1.5",
|
|
15
|
+
"@jest/globals": "^30.2.0",
|
|
16
|
+
"typescript": "^5.9.3"
|
|
17
17
|
},
|
|
18
18
|
"exports": {
|
|
19
19
|
".": {
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"files": [
|
|
26
26
|
"**/*.{js,mjs,cjs,map,d.ts,html,md,LEGAL.txt}",
|
|
27
27
|
"LICENSE",
|
|
28
|
-
"!demo/**/*"
|
|
28
|
+
"!demo/**/*",
|
|
29
|
+
"!**/*.test.js"
|
|
29
30
|
],
|
|
30
31
|
"homepage": "https://github.com/Alwatr/nanolib/tree/next/packages/local-storage#readme",
|
|
31
32
|
"keywords": [
|
|
@@ -75,5 +76,5 @@
|
|
|
75
76
|
"sideEffects": false,
|
|
76
77
|
"type": "module",
|
|
77
78
|
"types": "./dist/main.d.ts",
|
|
78
|
-
"gitHead": "
|
|
79
|
+
"gitHead": "b141732f4dab13542e3cc99926a250fd5c74bad3"
|
|
79
80
|
}
|
package/src/main.test.js
DELETED
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
import {describe, beforeEach, afterEach, it, expect, jest} from '@jest/globals';
|
|
2
|
-
import {createLocalStorageProvider, LocalStorageProvider} from '@alwatr/local-storage';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* @jest-environment jsdom
|
|
6
|
-
*/
|
|
7
|
-
describe('LocalStorageProvider', () => {
|
|
8
|
-
/**
|
|
9
|
-
* @type {jest.Mocked<Pick<Storage, "getItem" | "setItem" | "removeItem">>}
|
|
10
|
-
*/
|
|
11
|
-
let mockLocalStorage;
|
|
12
|
-
|
|
13
|
-
beforeEach(() => {
|
|
14
|
-
mockLocalStorage = {
|
|
15
|
-
getItem: jest.fn(),
|
|
16
|
-
setItem: jest.fn(),
|
|
17
|
-
removeItem: jest.fn(),
|
|
18
|
-
};
|
|
19
|
-
Object.defineProperty(globalThis, 'localStorage', {
|
|
20
|
-
value: mockLocalStorage,
|
|
21
|
-
writable: true,
|
|
22
|
-
});
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
afterEach(() => {
|
|
26
|
-
jest.clearAllMocks();
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
describe('static getKey', () => {
|
|
30
|
-
it('should generate the correct versioned key', () => {
|
|
31
|
-
const key = LocalStorageProvider.getKey({name: 'test', schemaVersion: 1});
|
|
32
|
-
expect(key).toBe('test.v1');
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
it('should handle different names and versions', () => {
|
|
36
|
-
const key1 = LocalStorageProvider.getKey({name: 'user-settings', schemaVersion: 2});
|
|
37
|
-
expect(key1).toBe('user-settings.v2');
|
|
38
|
-
const key2 = LocalStorageProvider.getKey({name: 'form-data', schemaVersion: 5});
|
|
39
|
-
expect(key2).toBe('form-data.v5');
|
|
40
|
-
});
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
describe('static has', () => {
|
|
44
|
-
it('should return true if item exists', () => {
|
|
45
|
-
mockLocalStorage.getItem.mockReturnValue('{"value": "test"}');
|
|
46
|
-
const exists = LocalStorageProvider.has({name: 'test', schemaVersion: 1});
|
|
47
|
-
expect(exists).toBe(true);
|
|
48
|
-
expect(mockLocalStorage.getItem).toHaveBeenCalledWith('test.v1');
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
it('should return false if item does not exist', () => {
|
|
52
|
-
mockLocalStorage.getItem.mockReturnValue(null);
|
|
53
|
-
const exists = LocalStorageProvider.has({name: 'test', schemaVersion: 1});
|
|
54
|
-
expect(exists).toBe(false);
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
it('should return false for null value', () => {
|
|
58
|
-
mockLocalStorage.getItem.mockReturnValue(null);
|
|
59
|
-
const exists = LocalStorageProvider.has({name: 'test', schemaVersion: 1});
|
|
60
|
-
expect(exists).toBe(false);
|
|
61
|
-
});
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
describe('constructor and migration', () => {
|
|
65
|
-
it('should initialize with config and migrate old versions', () => {
|
|
66
|
-
const provider = createLocalStorageProvider({
|
|
67
|
-
name: 'test',
|
|
68
|
-
schemaVersion: 3,
|
|
69
|
-
defaultValue: {key: 'value'},
|
|
70
|
-
});
|
|
71
|
-
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test.v1');
|
|
72
|
-
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test.v2');
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
it('should not migrate if schemaVersion is 1', () => {
|
|
76
|
-
const provider = createLocalStorageProvider({
|
|
77
|
-
name: 'test',
|
|
78
|
-
schemaVersion: 1,
|
|
79
|
-
defaultValue: {key: 'value'},
|
|
80
|
-
});
|
|
81
|
-
expect(mockLocalStorage.removeItem).not.toHaveBeenCalled();
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
it('should migrate multiple old versions for higher schemaVersion', () => {
|
|
85
|
-
const provider = createLocalStorageProvider({
|
|
86
|
-
name: 'test',
|
|
87
|
-
schemaVersion: 5,
|
|
88
|
-
defaultValue: {key: 'value'},
|
|
89
|
-
});
|
|
90
|
-
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test.v1');
|
|
91
|
-
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test.v2');
|
|
92
|
-
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test.v3');
|
|
93
|
-
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test.v4');
|
|
94
|
-
});
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
describe('read', () => {
|
|
98
|
-
it('should return default value if no item exists', () => {
|
|
99
|
-
mockLocalStorage.getItem.mockReturnValue(null);
|
|
100
|
-
const provider = createLocalStorageProvider({
|
|
101
|
-
name: 'test',
|
|
102
|
-
schemaVersion: 1,
|
|
103
|
-
defaultValue: {key: 'default'},
|
|
104
|
-
});
|
|
105
|
-
const result = provider.read();
|
|
106
|
-
expect(result).toEqual({key: 'default'});
|
|
107
|
-
expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test.v1', '{"key":"default"}');
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
it('should return parsed value if item exists', () => {
|
|
111
|
-
mockLocalStorage.getItem.mockReturnValue('{"key":"stored"}');
|
|
112
|
-
const provider = createLocalStorageProvider({
|
|
113
|
-
name: 'test',
|
|
114
|
-
schemaVersion: 1,
|
|
115
|
-
defaultValue: {key: 'default'},
|
|
116
|
-
});
|
|
117
|
-
const result = provider.read();
|
|
118
|
-
expect(result).toEqual({key: 'stored'});
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
it('should return default value on invalid JSON', () => {
|
|
122
|
-
mockLocalStorage.getItem.mockReturnValue('invalid json');
|
|
123
|
-
const provider = createLocalStorageProvider({
|
|
124
|
-
name: 'test',
|
|
125
|
-
schemaVersion: 1,
|
|
126
|
-
defaultValue: {key: 'default'},
|
|
127
|
-
});
|
|
128
|
-
const result = provider.read();
|
|
129
|
-
expect(result).toEqual({key: 'default'});
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
it('should handle complex default values', () => {
|
|
133
|
-
mockLocalStorage.getItem.mockReturnValue(null);
|
|
134
|
-
const provider = createLocalStorageProvider({
|
|
135
|
-
name: 'test',
|
|
136
|
-
schemaVersion: 1,
|
|
137
|
-
defaultValue: {theme: 'dark', lastLogin: Date.now(), settings: [1, 2, 3]},
|
|
138
|
-
});
|
|
139
|
-
const result = provider.read();
|
|
140
|
-
expect(result.theme).toBe('dark');
|
|
141
|
-
expect(Array.isArray(result.settings)).toBe(true);
|
|
142
|
-
});
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
describe('write', () => {
|
|
146
|
-
it('should serialize and store the value', () => {
|
|
147
|
-
const provider = createLocalStorageProvider({
|
|
148
|
-
name: 'test',
|
|
149
|
-
schemaVersion: 1,
|
|
150
|
-
defaultValue: {key: 'default'},
|
|
151
|
-
});
|
|
152
|
-
provider.write({key: 'newValue'});
|
|
153
|
-
expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test.v1', '{"key":"newValue"}');
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
it('should handle write errors gracefully', () => {
|
|
157
|
-
mockLocalStorage.setItem.mockImplementation(() => {
|
|
158
|
-
throw new Error('Storage full');
|
|
159
|
-
});
|
|
160
|
-
const provider = createLocalStorageProvider({
|
|
161
|
-
name: 'test',
|
|
162
|
-
schemaVersion: 1,
|
|
163
|
-
defaultValue: {key: 'default'},
|
|
164
|
-
});
|
|
165
|
-
expect(() => provider.write({key: 'value'})).not.toThrow();
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
it('should write different data types', () => {
|
|
169
|
-
const provider = createLocalStorageProvider({
|
|
170
|
-
name: 'test',
|
|
171
|
-
schemaVersion: 1,
|
|
172
|
-
/**
|
|
173
|
-
* @type {string|number|Array<number>}
|
|
174
|
-
*/
|
|
175
|
-
defaultValue: '',
|
|
176
|
-
});
|
|
177
|
-
provider.write('string value');
|
|
178
|
-
expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test.v1', '"string value"');
|
|
179
|
-
provider.write(42);
|
|
180
|
-
expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test.v1', '42');
|
|
181
|
-
provider.write([1, 2, 3]);
|
|
182
|
-
expect(mockLocalStorage.setItem).toHaveBeenCalledWith('test.v1', '[1,2,3]');
|
|
183
|
-
});
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
describe('remove', () => {
|
|
187
|
-
it('should remove the item from storage', () => {
|
|
188
|
-
const provider = createLocalStorageProvider({
|
|
189
|
-
name: 'test',
|
|
190
|
-
schemaVersion: 1,
|
|
191
|
-
defaultValue: {key: 'default'},
|
|
192
|
-
});
|
|
193
|
-
provider.remove();
|
|
194
|
-
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('test.v1');
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
it('should not throw if item does not exist', () => {
|
|
198
|
-
const provider = createLocalStorageProvider({
|
|
199
|
-
name: 'test',
|
|
200
|
-
schemaVersion: 1,
|
|
201
|
-
defaultValue: {key: 'default'},
|
|
202
|
-
});
|
|
203
|
-
expect(() => provider.remove()).not.toThrow();
|
|
204
|
-
});
|
|
205
|
-
});
|
|
206
|
-
|
|
207
|
-
describe('createLocalStorageProvider factory', () => {
|
|
208
|
-
it('should create a provider instance', () => {
|
|
209
|
-
const provider = createLocalStorageProvider({
|
|
210
|
-
name: 'factory-test',
|
|
211
|
-
schemaVersion: 1,
|
|
212
|
-
defaultValue: {created: true},
|
|
213
|
-
});
|
|
214
|
-
expect(provider).toBeInstanceOf(LocalStorageProvider);
|
|
215
|
-
const result = provider.read();
|
|
216
|
-
expect(result.created).toBe(true);
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
it('should handle different configurations', () => {
|
|
220
|
-
const provider1 = createLocalStorageProvider({
|
|
221
|
-
name: 'config1',
|
|
222
|
-
schemaVersion: 2,
|
|
223
|
-
defaultValue: 'default1',
|
|
224
|
-
});
|
|
225
|
-
const provider2 = createLocalStorageProvider({
|
|
226
|
-
name: 'config2',
|
|
227
|
-
schemaVersion: 1,
|
|
228
|
-
defaultValue: {key: 'default2'},
|
|
229
|
-
});
|
|
230
|
-
expect(provider1.read()).toBe('default1');
|
|
231
|
-
expect(provider2.read().key).toBe('default2');
|
|
232
|
-
});
|
|
233
|
-
});
|
|
234
|
-
});
|