@ort-fe/storage-cache-kit
Version:
Unified client-side cache and storage manager with expiration control
3 lines (2 loc) • 11.7 kB
JavaScript
"use strict";var E=Object.defineProperty;var b=(a,e,t)=>e in a?E(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var n=(a,e,t)=>b(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function I(a){try{return btoa(encodeURIComponent(a))}catch(e){return console.error("Encryption failed:",e),a}}function k(a){try{return decodeURIComponent(atob(a))}catch(e){return console.error("Decryption failed:",e),a}}function O(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function C(){return typeof window<"u"&&typeof document<"u"}function $(){return typeof process<"u"&&process.env&&(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)}const d=(()=>{const a={};return function(e){a[e]||(console.warn(e),a[e]=!0)}})();function R(a){return a.expires?Date.now()-a.timestamp>a.expires:!1}function p(a,e=!1){const t=JSON.stringify(a);return e?I(t):t}function _(a,e=!1){try{const t=e?k(a):a;return JSON.parse(t)}catch(t){throw console.error("Failed to deserialize item:",t),new Error("Invalid storage item format")}}function h(a,e=!1){if(!a)return;try{const r=_(a,e);if(r&&typeof r=="object"&&"value"in r&&"timestamp"in r)return r}catch(r){process.env.NODE_ENV==="development"&&console.debug("Item not in standard format, trying alternative parsing:",r)}let t;try{t=JSON.parse(a),process.env.NODE_ENV==="development"&&console.debug("Successfully parsed as JSON:",t)}catch{t=a,process.env.NODE_ENV==="development"&&console.debug("Using raw string as value:",a)}return{value:t,timestamp:Date.now(),expires:void 0}}function u(a,e){return e?`${e}:${a}`:a}function M(){try{if(typeof localStorage>"u")return!1;const a="__test_localStorage__";return localStorage.setItem(a,"test"),localStorage.removeItem(a),!0}catch{return!1}}class f{constructor(e=!1){n(this,"encrypt");n(this,"available");this.encrypt=e,this.available=M(),this.available||d("localStorage is not available in this environment.")}async setItem(e,t){if(!this.available)throw new Error("localStorage is not available in this environment");try{const r=p(t,this.encrypt);localStorage.setItem(e,r)}catch(r){throw console.error(`Failed to set item '${e}':`,r),new Error(`Failed to set item '${e}'`)}}async getItem(e){if(!this.available)throw new Error("localStorage is not available in this environment");try{const t=localStorage.getItem(e);return t?h(t,this.encrypt):void 0}catch(t){console.error(`Failed to get item '${e}':`,t);return}}async removeItem(e){if(!this.available)throw new Error("localStorage is not available in this environment");localStorage.removeItem(e)}async clear(){if(!this.available)throw new Error("localStorage is not available in this environment");localStorage.clear()}async keys(){if(!this.available)throw new Error("localStorage is not available in this environment");const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&e.push(r)}return e}}function T(){try{if(typeof sessionStorage>"u")return!1;const a="__test_sessionStorage__";return sessionStorage.setItem(a,"test"),sessionStorage.removeItem(a),!0}catch{return!1}}class g{constructor(e=!1){n(this,"encrypt");n(this,"available");this.encrypt=e,this.available=T(),this.available||d("sessionStorage is not available in this environment.")}async setItem(e,t){if(!this.available)throw new Error("sessionStorage is not available in this environment");try{const r=p(t,this.encrypt);sessionStorage.setItem(e,r)}catch(r){throw console.error(`Failed to set item '${e}':`,r),new Error(`Failed to set item '${e}'`)}}async getItem(e){if(!this.available)throw new Error("sessionStorage is not available in this environment");try{const t=sessionStorage.getItem(e);return t?h(t,this.encrypt):void 0}catch(t){console.error(`Failed to get item '${e}':`,t);return}}async removeItem(e){if(!this.available)throw new Error("sessionStorage is not available in this environment");sessionStorage.removeItem(e)}async clear(){if(!this.available)throw new Error("sessionStorage is not available in this environment");sessionStorage.clear()}async keys(){if(!this.available)throw new Error("sessionStorage is not available in this environment");const e=[];for(let t=0;t<sessionStorage.length;t++){const r=sessionStorage.key(t);r&&e.push(r)}return e}}class y{constructor(e=!1){n(this,"storage",new Map);n(this,"encrypt");this.encrypt=e}async setItem(e,t){try{const r=p(t,this.encrypt);this.storage.set(e,r)}catch(r){throw console.error(`Failed to set item '${e}':`,r),new Error(`Failed to set item '${e}'`)}}async getItem(e){try{const t=this.storage.get(e);return t?h(t,this.encrypt):void 0}catch(t){console.error(`Failed to get item '${e}':`,t);return}}async removeItem(e){this.storage.delete(e)}async clear(){this.storage.clear()}async keys(){return Array.from(this.storage.keys())}}function N(){try{if(typeof document>"u"||typeof document.cookie>"u")return!1;const a="__test_cookie__",e="test",t=new Date;t.setTime(t.getTime()+1e3),document.cookie=`${a}=${e}; expires=${t.toUTCString()}; path=/`;const r=document.cookie.indexOf(a)!==-1;return document.cookie=`${a}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`,r}catch{return!1}}class v{constructor(e={}){n(this,"encrypt");n(this,"defaultDays");n(this,"path");n(this,"domain");n(this,"secure");n(this,"sameSite");n(this,"available");this.encrypt=e.encrypt||!1,this.defaultDays=e.defaultDays||7,this.path=e.path||"/",this.domain=e.domain,this.secure=e.secure||!1,this.sameSite=e.sameSite||"lax",this.available=N(),this.available||d("Cookie is not available in this environment.")}async setItem(e,t){if(!this.available)throw new Error("Cookie is not available in this environment");try{const r=p(t,this.encrypt),s=t.expires?Math.ceil(t.expires/(24*60*60*1e3)):this.defaultDays,i=new Date;i.setTime(i.getTime()+s*24*60*60*1e3);let o=`${encodeURIComponent(e)}=${encodeURIComponent(r)}; expires=${i.toUTCString()}; path=${this.path}`;this.domain&&(o+=`; domain=${this.domain}`),this.secure&&(o+="; secure"),o+=`; samesite=${this.sameSite}`,document.cookie=o}catch(r){throw console.error(`Failed to set cookie '${e}':`,r),new Error(`Failed to set cookie '${e}'`)}}async getItem(e){if(!this.available)throw new Error("Cookie is not available in this environment");try{const t=document.cookie.split(";"),r=encodeURIComponent(e);for(const s of t){const[i,o]=s.trim().split("=");if(i===r&&o){const m=decodeURIComponent(o);return h(m,this.encrypt)}}return}catch(t){console.error(`Failed to get cookie '${e}':`,t);return}}async removeItem(e){if(!this.available)throw new Error("Cookie is not available in this environment");document.cookie=`${encodeURIComponent(e)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${this.path}`,this.domain&&(document.cookie=`${encodeURIComponent(e)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${this.path}; domain=${this.domain}`)}async clear(){if(!this.available)throw new Error("Cookie is not available in this environment");const e=document.cookie.split(";");for(const t of e){const r=t.split("=")[0].trim();await this.removeItem(r)}}async keys(){if(!this.available)throw new Error("Cookie is not available in this environment");const e=document.cookie.split(";"),t=[];for(const r of e)if(r.trim()){const s=r.split("=")[0].trim();t.push(decodeURIComponent(s))}return t}}const c={LOCAL_STORAGE:"localStorage",SESSION_STORAGE:"sessionStorage",MEMORY:"memory",COOKIE:"cookie"};function D(){try{return typeof process<"u"&&process.env?process.env.NODE_ENV==="development":!1}catch{return!1}}function l(...a){D()&&console.debug(...a)}class S{constructor(e={}){n(this,"adapters",new Map);n(this,"options");const t=O(),r=$(),s=C()||r;let i;typeof e.defaultAdapter=="string"?i=this.mapAdapterString(e.defaultAdapter):i=!s||t?c.MEMORY:e.defaultAdapter||c.LOCAL_STORAGE;const o={...e};delete o.defaultAdapter,this.options={defaultAdapter:i,defaultExpires:0,defaultEncrypt:!1,namespace:"",...o},this.registerAdapters(),l("Registered adapters:",Array.from(this.adapters.keys())),this.adapters.has(this.options.defaultAdapter.toLowerCase())||(d(`Default adapter '${this.options.defaultAdapter}' is not available, falling back to memory adapter.`),this.options.defaultAdapter=c.MEMORY)}registerAdapters(){const e=new y(this.options.defaultEncrypt);this.registerAdapterWithAliases(c.MEMORY,e,["memory","mem"]);try{const t=new f(this.options.defaultEncrypt);this.registerAdapterWithAliases(c.LOCAL_STORAGE,t,["localStorage","local","localstorage"])}catch(t){l("localStorage adapter registration failed:",t instanceof Error?t.message:String(t))}try{const t=new g(this.options.defaultEncrypt);this.registerAdapterWithAliases(c.SESSION_STORAGE,t,["sessionStorage","session","sessionstorage"])}catch(t){l("sessionStorage adapter registration failed:",t instanceof Error?t.message:String(t))}try{const t=new v({encrypt:this.options.defaultEncrypt});this.registerAdapterWithAliases(c.COOKIE,t,["cookie","cookies"])}catch(t){l("cookie adapter registration failed:",t instanceof Error?t.message:String(t))}}registerAdapterWithAliases(e,t,r){const s=e.toLowerCase();this.adapters.set(s,t);for(const i of r){const o=i.toLowerCase();o!==s&&this.adapters.set(o,t)}l(`Registered adapter '${e}' with aliases:`,r)}mapAdapterString(e){if(!e)return c.MEMORY;const t=e.toLowerCase();return{localstorage:c.LOCAL_STORAGE,local:c.LOCAL_STORAGE,sessionstorage:c.SESSION_STORAGE,session:c.SESSION_STORAGE,cookie:c.COOKIE,cookies:c.COOKIE,memory:c.MEMORY,mem:c.MEMORY}[t]||e}registerAdapter(e,t){this.adapters.set(e.toLowerCase(),t)}getAdapter(e=this.options.defaultAdapter){e||(e=this.options.defaultAdapter);const r=this.mapAdapterString(e).toLowerCase(),s=this.adapters.get(r);if(!s)throw l("Available adapters:",Array.from(this.adapters.keys())),l("Requested adapter:",e,"Mapped to:",r),new Error(`Adapter '${e}' not found`);return s}async set(e,t,r={}){const{expires:s=this.options.defaultExpires}=r;let i;r.adapter?i=this.mapAdapterString(r.adapter):i=this.options.defaultAdapter;const o=this.getAdapter(i),m=u(e,this.options.namespace),A={value:t,timestamp:Date.now(),expires:s};await o.setItem(m,A)}async get(e,t={}){let r;t.adapter?r=this.mapAdapterString(t.adapter):r=this.options.defaultAdapter;const s=this.getAdapter(r),i=u(e,this.options.namespace),o=await s.getItem(i);if(o){if(R(o)){await this.remove(e,{adapter:r});return}return o.value}}async remove(e,t={}){let r;t.adapter?r=this.mapAdapterString(t.adapter):r=this.options.defaultAdapter;const s=this.getAdapter(r),i=u(e,this.options.namespace);await s.removeItem(i)}async clear(e={}){let t;e.adapter?t=this.mapAdapterString(e.adapter):t=this.options.defaultAdapter,await this.getAdapter(t).clear()}async keys(e={}){let t;e.adapter?t=this.mapAdapterString(e.adapter):t=this.options.defaultAdapter;const s=await this.getAdapter(t).keys();if(this.options.namespace){const i=`${this.options.namespace}:`;return s.filter(o=>o.startsWith(i)).map(o=>o.slice(i.length))}return s}async has(e,t={}){return await this.get(e,t)!==void 0}}class w{constructor(e){n(this,"manager");this.manager=new S(e)}async put(e,t,r){return this.manager.set(e,t,r)}async get(e,t){return this.manager.get(e,t)}async del(e,t){return this.manager.remove(e,t)}async has(e,t){return this.manager.has(e,t)}async keys(e){return this.manager.keys(e)}async clear(e){return this.manager.clear(e)}getManager(){return this.manager}getRegisteredAdapters(){return Array.from(this.manager.adapters.keys())}}const L=new w;exports.ADAPTER_TYPES=c;exports.CookieStorageAdapter=v;exports.LocalStorageAdapter=f;exports.MemoryStorageAdapter=y;exports.SessionStorageAdapter=g;exports.SimpleStore=w;exports.StorageManager=S;exports.store=L;
//# sourceMappingURL=index.cjs.map