@alwatr/local-storage 6.3.1 → 6.3.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/CHANGELOG.md +15 -0
- package/dist/local-storage.provider.d.ts +8 -8
- 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 +1 -1
- package/dist/type.d.ts.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,21 @@
|
|
|
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
|
+
## [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
|
+
|
|
8
|
+
### 🐛 Bug Fixes
|
|
9
|
+
|
|
10
|
+
* add constraint to createLocalStorageProvider generic type to extend JsonValue ([198ca49](https://github.com/Alwatr/nanolib/commit/198ca49042780aff15d3979bea3951bf094b3b15))
|
|
11
|
+
* add generic type constraint to LocalStorageProviderConfig to extend JsonValue ([9b97692](https://github.com/Alwatr/nanolib/commit/9b9769254613aac6ad94a0c2dd885c44e63b6ed2))
|
|
12
|
+
* refine generic type constraints in LocalStorageProvider to extend JsonValue ([6a05c12](https://github.com/Alwatr/nanolib/commit/6a05c12583326dbea8784f79f7c559b9a31d3cef))
|
|
13
|
+
* rename convertDataType method to convertDataType__ for consistency ([83ccb56](https://github.com/Alwatr/nanolib/commit/83ccb56a9ff95ba0c4e8e6a77cb67a010d60701a))
|
|
14
|
+
|
|
15
|
+
## [6.3.2](https://github.com/Alwatr/nanolib/compare/@alwatr/local-storage@6.3.1...@alwatr/local-storage@6.3.2) (2025-09-22)
|
|
16
|
+
|
|
17
|
+
### 🐛 Bug Fixes
|
|
18
|
+
|
|
19
|
+
* remove unnecessary constraint from createLocalStorageProvider generic type ([960467f](https://github.com/Alwatr/nanolib/commit/960467fd161a80bf4e90cb3070054cee58182bfb))
|
|
20
|
+
|
|
6
21
|
## [6.3.1](https://github.com/Alwatr/nanolib/compare/@alwatr/local-storage@6.3.0...@alwatr/local-storage@6.3.1) (2025-09-22)
|
|
7
22
|
|
|
8
23
|
### 🐛 Bug Fixes
|
|
@@ -19,12 +19,12 @@ import type { LocalStorageProviderConfig, StorageMeta } from './type.js';
|
|
|
19
19
|
* console.log(currentSettings); // { theme: 'dark', notifications: false }
|
|
20
20
|
* ```
|
|
21
21
|
*/
|
|
22
|
-
export declare class LocalStorageProvider<T> {
|
|
22
|
+
export declare class LocalStorageProvider<T extends JsonValue> {
|
|
23
23
|
static readonly version: string;
|
|
24
24
|
private readonly key__;
|
|
25
25
|
protected readonly logger_: import("@alwatr/logger").AlwatrLogger;
|
|
26
|
-
private meta__;
|
|
27
|
-
protected readonly defaultValue__:
|
|
26
|
+
private readonly meta__;
|
|
27
|
+
protected readonly defaultValue__: T;
|
|
28
28
|
constructor(config: LocalStorageProviderConfig<T>);
|
|
29
29
|
/**
|
|
30
30
|
* Generates the versioned storage key.
|
|
@@ -57,24 +57,24 @@ export declare class LocalStorageProvider<T> {
|
|
|
57
57
|
/**
|
|
58
58
|
* Converts the provided data to a JSON-compatible format by simulating
|
|
59
59
|
* a serialization/deserialization cycle. This ensures that the data
|
|
60
|
-
* conforms to the `
|
|
60
|
+
* conforms to the `T` type.
|
|
61
61
|
*
|
|
62
62
|
* @template T - The type of the input data.
|
|
63
63
|
* @param data - The data to be converted to a JSON-compatible format.
|
|
64
|
-
* @returns The converted data as `
|
|
64
|
+
* @returns The converted data as `T`.
|
|
65
65
|
* @throws {Error} If the serialization/deserialization process fails.
|
|
66
66
|
*/
|
|
67
|
-
|
|
67
|
+
private convertDataType__;
|
|
68
68
|
/**
|
|
69
69
|
* Reads and parses the value from localStorage.
|
|
70
70
|
* If the item doesn't exist, is invalid JSON, or doesn't match the expected type,
|
|
71
71
|
* it writes and returns the default value.
|
|
72
72
|
*/
|
|
73
|
-
read():
|
|
73
|
+
read(): T;
|
|
74
74
|
/**
|
|
75
75
|
* Serializes and writes a value to localStorage.
|
|
76
76
|
*/
|
|
77
|
-
write(value: T
|
|
77
|
+
write(value: T): void;
|
|
78
78
|
/**
|
|
79
79
|
* Removes the item from localStorage.
|
|
80
80
|
*/
|
|
@@ -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,EAAE,WAAW,EAAC,MAAM,WAAW,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,oBAAoB,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"local-storage.provider.d.ts","sourceRoot":"","sources":["../src/local-storage.provider.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,0BAA0B,EAAE,WAAW,EAAC,MAAM,WAAW,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;GAmBG;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;IAE3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwB;IAE/C,SAAS,CAAC,QAAQ,CAAC,cAAc,EAAE,CAAC,CAAC;gBAEzB,MAAM,EAAE,0BAA0B,CAAC,CAAC,CAAC;IAYjD;;;;OAIG;WACW,MAAM,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM;IAI/C;;;;;;;;;;;;;;;;OAgBG;WACW,GAAG,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO;IAK7C;;OAEG;IACH,OAAO,CAAC,eAAe;IAWvB;;;;;;;;;OASG;IACH,OAAO,CAAC,iBAAiB;IAYzB;;;;OAIG;IACI,IAAI,IAAI,CAAC;IAyBhB;;OAEG;IACI,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI;IAmB5B;;OAEG;IACI,MAAM,IAAI,IAAI;IAIrB;;OAEG;IACH,OAAO,CAAC,SAAS;CASlB"}
|
package/dist/main.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** 📦 @alwatr/local-storage v6.3.
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/local-storage v6.3.
|
|
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="6.3.
|
|
1
|
+
/** 📦 @alwatr/local-storage v6.3.3 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/local-storage v6.3.3");
|
|
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="6.3.3"}constructor(config){this.logger_=(0,import_logger.createLogger)(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);this.logger_.logMethodArgs?.("constructor",{config});this.meta__={name:config.name,schemaVersion:config.schemaVersion};this.key__=_LocalStorageProvider.getKey(this.meta__);this.defaultValue__=this.convertDataType__(config.defaultValue);this.migrate__()}static getKey(meta){return`${meta.name}.v${meta.schemaVersion}`}static has(meta){const key=_LocalStorageProvider.getKey(meta);return localStorage.getItem(key)!==null}handleDefault__(){this.logger_.logMethodArgs?.("handleDefault__",this.defaultValue__);try{this.write(this.defaultValue__)}catch(err){this.logger_.error("write","write_default_error",{err})}return this.defaultValue__}convertDataType__(data){this.logger_.logMethod?.("convertDataType");try{return JSON.parse(JSON.stringify(data))}catch(err){this.logger_.error("convertDataType__","convert_data_type_error",{err});throw new Error("convert_data_type_error")}}read(){let value=null;try{value=localStorage.getItem(this.key__)}catch(err){this.logger_.error("read","read_local_storage_error",{err})}if(value===null){this.logger_.logMethod?.("read//no_value");return this.handleDefault__()}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 this.handleDefault__()}}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__)}migrate__(){if(this.meta__.schemaVersion<=1)return;for(let i=1;i<this.meta__.schemaVersion;i++){const oldKey=_LocalStorageProvider.getKey({name:this.meta__.name,schemaVersion:i});localStorage.removeItem(oldKey)}}};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, StorageMeta} 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 * defaultValue: { theme: 'light', notifications: true }\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> {\n public static readonly version = __package_version__;\n\n private readonly key__: string;\n protected readonly logger_;\n\n private meta__: StorageMeta
|
|
5
|
-
"mappings": ";;qqBAAA,+LCAA,kBAA2B,0BAwBpB,IAAM,qBAAN,MAAM,
|
|
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, StorageMeta} 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 * defaultValue: { theme: 'light', notifications: true }\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 private readonly meta__: Readonly<StorageMeta>;\n\n protected readonly defaultValue__: T;\n\n constructor(config: LocalStorageProviderConfig<T>) {\n this.logger_ = createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);\n this.logger_.logMethodArgs?.('constructor', {config});\n this.meta__ = {\n name: config.name,\n schemaVersion: config.schemaVersion,\n };\n this.key__ = LocalStorageProvider.getKey(this.meta__);\n this.defaultValue__ = this.convertDataType__(config.defaultValue);\n this.migrate__();\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(meta: StorageMeta): string {\n return `${meta.name}.v${meta.schemaVersion}`;\n }\n\n /**\n * Statically checks if a versioned item exists in localStorage.\n * This method provides a high-performance way to check for data existence without the overhead of creating a full provider instance.\n *\n * @param meta - An object containing the name and version of the item to check.\n * @returns `true` if the item exists, otherwise `false`.\n *\n * @example\n * ```typescript\n * const formExists = LocalStorageProvider.has({ name: 'user-form', schemaVersion: 1 });\n * if (formExists) {\n * // Show the \"Thank you\" message\n * } else {\n * // Show the form\n * }\n * ```\n */\n public static has(meta: StorageMeta): boolean {\n const key = LocalStorageProvider.getKey(meta);\n return localStorage.getItem(key) !== null;\n }\n\n /**\n * Writes the default value to localStorage and returns it.\n */\n private handleDefault__(): T {\n this.logger_.logMethodArgs?.('handleDefault__', this.defaultValue__);\n try {\n this.write(this.defaultValue__);\n }\n catch (err) {\n this.logger_.error('write', 'write_default_error', {err});\n }\n return this.defaultValue__;\n }\n\n /**\n * Converts the provided data to a JSON-compatible format by simulating\n * a serialization/deserialization cycle. This ensures that the data\n * conforms to the `T` type.\n *\n * @template T - The type of the input data.\n * @param data - The data to be converted to a JSON-compatible format.\n * @returns The converted data as `T`.\n * @throws {Error} If the serialization/deserialization process fails.\n */\n private convertDataType__(data: T): T {\n this.logger_.logMethod?.('convertDataType');\n // Simulate real serialization/deserialization cycle for real types\n try {\n return JSON.parse(JSON.stringify(data)) as T;\n }\n catch (err) {\n this.logger_.error('convertDataType__', 'convert_data_type_error', {err});\n throw new Error('convert_data_type_error');\n }\n }\n\n /**\n * Reads and parses the value from localStorage.\n * If the item doesn't exist, is invalid JSON, or doesn't match the expected type,\n * it writes and returns the default value.\n */\n public read(): T {\n let value: string | null = null;\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 === null) {\n this.logger_.logMethod?.('read//no_value');\n return this.handleDefault__();\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 this.handleDefault__();\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 /**\n * Manages data migration by removing all previous versions of the item.\n */\n private migrate__(): void {\n if (this.meta__.schemaVersion <= 1) return;\n\n // Iterate from v1 up to the version just before the current one and remove them.\n for (let i = 1; i < this.meta__.schemaVersion; i++) {\n const oldKey = LocalStorageProvider.getKey({name: this.meta__.name, schemaVersion: i});\n localStorage.removeItem(oldKey);\n }\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 * defaultValue: { theme: 'light', notifications: true }\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<T>): LocalStorageProvider<T> {\n return new LocalStorageProvider<T>(config);\n}\n"],
|
|
5
|
+
"mappings": ";;qqBAAA,+LCAA,kBAA2B,0BAwBpB,IAAM,qBAAN,MAAM,qBAA0C,CACrD,YAAuB,QAAU,QASjC,YAAY,OAAuC,CACjD,KAAK,WAAU,4BAAa,2BAA2B,OAAO,IAAI,QAAQ,OAAO,aAAa,EAAE,EAChG,KAAK,QAAQ,gBAAgB,cAAe,CAAC,MAAM,CAAC,EACpD,KAAK,OAAS,CACZ,KAAM,OAAO,KACb,cAAe,OAAO,aACxB,EACA,KAAK,MAAQ,sBAAqB,OAAO,KAAK,MAAM,EACpD,KAAK,eAAiB,KAAK,kBAAkB,OAAO,YAAY,EAChE,KAAK,UAAU,CACjB,CAOA,OAAc,OAAO,KAA2B,CAC9C,MAAO,GAAG,KAAK,IAAI,KAAK,KAAK,aAAa,EAC5C,CAmBA,OAAc,IAAI,KAA4B,CAC5C,MAAM,IAAM,sBAAqB,OAAO,IAAI,EAC5C,OAAO,aAAa,QAAQ,GAAG,IAAM,IACvC,CAKQ,iBAAqB,CAC3B,KAAK,QAAQ,gBAAgB,kBAAmB,KAAK,cAAc,EACnE,GAAI,CACF,KAAK,MA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a,WAAW,KAAK,KAAK,CACpC,CAKQ,WAAkB,CACxB,GAAI,KAAK,OAAO,eAAiB,EAAG,OAGpC,QAAS,EAAI,EAAG,EAAI,KAAK,OAAO,cAAe,IAAK,CAClD,MAAM,OAAS,sBAAqB,OAAO,CAAC,KAAM,KAAK,OAAO,KAAM,cAAe,CAAC,CAAC,EACrF,aAAa,WAAW,MAAM,CAChC,CACF,CACF,EC9JO,SAAS,2BAAgD,OAAgE,CAC9H,OAAO,IAAI,qBAAwB,MAAM,CAC3C",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** 📦 @alwatr/local-storage v6.3.
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/local-storage v6.3.
|
|
3
|
-
import{createLogger}from"@alwatr/logger";var LocalStorageProvider=class _LocalStorageProvider{static{this.version="6.3.
|
|
1
|
+
/** 📦 @alwatr/local-storage v6.3.3 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/local-storage v6.3.3");
|
|
3
|
+
import{createLogger}from"@alwatr/logger";var LocalStorageProvider=class _LocalStorageProvider{static{this.version="6.3.3"}constructor(config){this.logger_=createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);this.logger_.logMethodArgs?.("constructor",{config});this.meta__={name:config.name,schemaVersion:config.schemaVersion};this.key__=_LocalStorageProvider.getKey(this.meta__);this.defaultValue__=this.convertDataType__(config.defaultValue);this.migrate__()}static getKey(meta){return`${meta.name}.v${meta.schemaVersion}`}static has(meta){const key=_LocalStorageProvider.getKey(meta);return localStorage.getItem(key)!==null}handleDefault__(){this.logger_.logMethodArgs?.("handleDefault__",this.defaultValue__);try{this.write(this.defaultValue__)}catch(err){this.logger_.error("write","write_default_error",{err})}return this.defaultValue__}convertDataType__(data){this.logger_.logMethod?.("convertDataType");try{return JSON.parse(JSON.stringify(data))}catch(err){this.logger_.error("convertDataType__","convert_data_type_error",{err});throw new Error("convert_data_type_error")}}read(){let value=null;try{value=localStorage.getItem(this.key__)}catch(err){this.logger_.error("read","read_local_storage_error",{err})}if(value===null){this.logger_.logMethod?.("read//no_value");return this.handleDefault__()}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 this.handleDefault__()}}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__)}migrate__(){if(this.meta__.schemaVersion<=1)return;for(let i=1;i<this.meta__.schemaVersion;i++){const oldKey=_LocalStorageProvider.getKey({name:this.meta__.name,schemaVersion:i});localStorage.removeItem(oldKey)}}};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, StorageMeta} 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 * defaultValue: { theme: 'light', notifications: true }\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> {\n public static readonly version = __package_version__;\n\n private readonly key__: string;\n protected readonly logger_;\n\n private meta__: StorageMeta
|
|
5
|
-
"mappings": ";;AAAA,OAAQ,iBAAmB,iBAwBpB,IAAM,qBAAN,MAAM,
|
|
4
|
+
"sourcesContent": ["import {createLogger} from '@alwatr/logger';\n\nimport type {LocalStorageProviderConfig, StorageMeta} 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 * defaultValue: { theme: 'light', notifications: true }\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 private readonly meta__: Readonly<StorageMeta>;\n\n protected readonly defaultValue__: T;\n\n constructor(config: LocalStorageProviderConfig<T>) {\n this.logger_ = createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);\n this.logger_.logMethodArgs?.('constructor', {config});\n this.meta__ = {\n name: config.name,\n schemaVersion: config.schemaVersion,\n };\n this.key__ = LocalStorageProvider.getKey(this.meta__);\n this.defaultValue__ = this.convertDataType__(config.defaultValue);\n this.migrate__();\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(meta: StorageMeta): string {\n return `${meta.name}.v${meta.schemaVersion}`;\n }\n\n /**\n * Statically checks if a versioned item exists in localStorage.\n * This method provides a high-performance way to check for data existence without the overhead of creating a full provider instance.\n *\n * @param meta - An object containing the name and version of the item to check.\n * @returns `true` if the item exists, otherwise `false`.\n *\n * @example\n * ```typescript\n * const formExists = LocalStorageProvider.has({ name: 'user-form', schemaVersion: 1 });\n * if (formExists) {\n * // Show the \"Thank you\" message\n * } else {\n * // Show the form\n * }\n * ```\n */\n public static has(meta: StorageMeta): boolean {\n const key = LocalStorageProvider.getKey(meta);\n return localStorage.getItem(key) !== null;\n }\n\n /**\n * Writes the default value to localStorage and returns it.\n */\n private handleDefault__(): T {\n this.logger_.logMethodArgs?.('handleDefault__', this.defaultValue__);\n try {\n this.write(this.defaultValue__);\n }\n catch (err) {\n this.logger_.error('write', 'write_default_error', {err});\n }\n return this.defaultValue__;\n }\n\n /**\n * Converts the provided data to a JSON-compatible format by simulating\n * a serialization/deserialization cycle. This ensures that the data\n * conforms to the `T` type.\n *\n * @template T - The type of the input data.\n * @param data - The data to be converted to a JSON-compatible format.\n * @returns The converted data as `T`.\n * @throws {Error} If the serialization/deserialization process fails.\n */\n private convertDataType__(data: T): T {\n this.logger_.logMethod?.('convertDataType');\n // Simulate real serialization/deserialization cycle for real types\n try {\n return JSON.parse(JSON.stringify(data)) as T;\n }\n catch (err) {\n this.logger_.error('convertDataType__', 'convert_data_type_error', {err});\n throw new Error('convert_data_type_error');\n }\n }\n\n /**\n * Reads and parses the value from localStorage.\n * If the item doesn't exist, is invalid JSON, or doesn't match the expected type,\n * it writes and returns the default value.\n */\n public read(): T {\n let value: string | null = null;\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 === null) {\n this.logger_.logMethod?.('read//no_value');\n return this.handleDefault__();\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 this.handleDefault__();\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 /**\n * Manages data migration by removing all previous versions of the item.\n */\n private migrate__(): void {\n if (this.meta__.schemaVersion <= 1) return;\n\n // Iterate from v1 up to the version just before the current one and remove them.\n for (let i = 1; i < this.meta__.schemaVersion; i++) {\n const oldKey = LocalStorageProvider.getKey({name: this.meta__.name, schemaVersion: i});\n localStorage.removeItem(oldKey);\n }\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 * defaultValue: { theme: 'light', notifications: true }\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<T>): LocalStorageProvider<T> {\n return new LocalStorageProvider<T>(config);\n}\n"],
|
|
5
|
+
"mappings": ";;AAAA,OAAQ,iBAAmB,iBAwBpB,IAAM,qBAAN,MAAM,qBAA0C,CACrD,YAAuB,QAAU,QASjC,YAAY,OAAuC,CACjD,KAAK,QAAU,aAAa,2BAA2B,OAAO,IAAI,QAAQ,OAAO,aAAa,EAAE,EAChG,KAAK,QAAQ,gBAAgB,cAAe,CAAC,MAAM,CAAC,EACpD,KAAK,OAAS,CACZ,KAAM,OAAO,KACb,cAAe,OAAO,aACxB,EACA,KAAK,MAAQ,sBAAqB,OAAO,KAAK,MAAM,EACpD,KAAK,eAAiB,KAAK,kBAAkB,OAAO,YAAY,EAChE,KAAK,UAAU,CACjB,CAOA,OAAc,O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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,CAKQ,WAAkB,CACxB,GAAI,KAAK,OAAO,eAAiB,EAAG,OAGpC,QAAS,EAAI,EAAG,EAAI,KAAK,OAAO,cAAe,IAAK,CAClD,MAAM,OAAS,sBAAqB,OAAO,CAAC,KAAM,KAAK,OAAO,KAAM,cAAe,CAAC,CAAC,EACrF,aAAa,WAAW,MAAM,CAChC,CACF,CACF,EC9JO,SAAS,2BAAgD,OAAgE,CAC9H,OAAO,IAAI,qBAAwB,MAAM,CAC3C",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/type.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export interface StorageMeta {
|
|
|
9
9
|
*/
|
|
10
10
|
schemaVersion: number;
|
|
11
11
|
}
|
|
12
|
-
export interface LocalStorageProviderConfig<T> extends StorageMeta {
|
|
12
|
+
export interface LocalStorageProviderConfig<T extends JsonValue> extends StorageMeta {
|
|
13
13
|
/**
|
|
14
14
|
* The default value to use if no value is stored.
|
|
15
15
|
*/
|
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,WAAW;IAC1B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,0BAA0B,CAAC,CAAC,CAAE,SAAQ,WAAW;
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,0BAA0B,CAAC,CAAC,SAAS,SAAS,CAAE,SAAQ,WAAW;IAClF;;OAEG;IACH,YAAY,EAAE,CAAC,CAAC;CACjB"}
|
package/package.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
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": "6.3.
|
|
4
|
+
"version": "6.3.3",
|
|
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.7"
|
|
9
9
|
},
|
|
10
10
|
"devDependencies": {
|
|
11
|
-
"@alwatr/nano-build": "6.3.
|
|
11
|
+
"@alwatr/nano-build": "6.3.3",
|
|
12
12
|
"@alwatr/prettier-config": "5.0.4",
|
|
13
13
|
"@alwatr/tsconfig-base": "6.0.2",
|
|
14
|
-
"@alwatr/type-helper": "6.1.
|
|
14
|
+
"@alwatr/type-helper": "6.1.3",
|
|
15
15
|
"@jest/globals": "^30.1.2",
|
|
16
16
|
"typescript": "^5.9.2"
|
|
17
17
|
},
|
|
@@ -75,5 +75,5 @@
|
|
|
75
75
|
"sideEffects": false,
|
|
76
76
|
"type": "module",
|
|
77
77
|
"types": "./dist/main.d.ts",
|
|
78
|
-
"gitHead": "
|
|
78
|
+
"gitHead": "a0c8605949969959c8226e54b8c8c0fc7276819a"
|
|
79
79
|
}
|