UNPKG

@minisss/localstorage

Version:
2 lines (1 loc) 2.24 kB
"use strict";var r="1.0.5";function e(r,e={}){const t=String(r).trim();if(!e.prefix)return t;const n=String(e.prefix||"").trim();return n?`${n}_${t}`:`${t}`}function t(){try{return!!window.localStorage}catch(r){return!1}}function n(r){if(!t())throw new Error("@minisss/localstorage is muse run in browser");return localStorage.key(r)}function o(r,n={}){if(!t())throw new Error("@minisss/localstorage is muse run in browser");return localStorage.removeItem(e(r,n))}function s(r,n){if(!t())throw new Error("@minisss/localstorage is muse run in browser");const s=localStorage.getItem(e(r,n));if(!s)return s;try{const e=JSON.parse(s);return e?e.maxAge&&e.maxAge<=Date.now()?o(r,n):e.data:null}catch(r){return s}}function i(r,n,o={}){if(!t())throw new Error("@minisss/localstorage is muse run in browser");const{maxAge:s,expires:i}=null!=o?o:{};if("number"==typeof s&&s<=0)throw new Error("maxAge must be greater than 0");if(i&&"[object Date]"===Object.prototype.toString.call(i))throw new Error("expires must be greater than now");const a=s?{maxAge:Date.now()+1e3*s}:i?{maxAge:i.getTime()}:{};return localStorage.setItem(e(r,o),JSON.stringify(Object.assign(Object.assign({},a),{data:n})))}function a(){if(!t())throw new Error("@minisss/localstorage is muse run in browser");localStorage.clear()}function c(r,n={}){if(!t())throw new Error("@minisss/localstorage is muse run in browser");const o=localStorage.length,s=[];for(let r=0;r<o;r++)s.push(localStorage.key(r));return s.some(t=>t===e(r,n))}function u(){if(!t())throw new Error("@minisss/localstorage is muse run in browser");return localStorage.length}var l={get VERSION(){return r},get length(){return u()},get isSupport(){return t()},key:n,get:s,set:i,del:o,clear:a,has:c,create:function(e={}){const l=Object.create(null);return l.VERSION=r,l.key=function(r){return n(r)},l.get=function(r,t={}){return s(r,Object.assign(Object.assign({},e),t))},l.set=function(r,t,n={}){return i(r,t,Object.assign(Object.assign({},e),n))},l.del=function(r,t={}){return o(r,Object.assign(Object.assign({},e),t))},l.clear=function(){return a()},l.has=function(r,t={}){return c(r,Object.assign(Object.assign({},e),t))},new Proxy(l,{get:(r,e)=>"length"===e?u():"isSupport"===e?t():r[e]})}};module.exports=l;