UNPKG

pinia-plugin-persistedstate-2

Version:

Persist and rehydrate your Pinia state between page reloads

2 lines (1 loc) 2.51 kB
(function(a,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(a=typeof globalThis<"u"?globalThis:a||self,d(a.PiniaPluginPersistedstate_2={}))})(this,function(a){"use strict";function d(s,e,f){return(s=(e.split?e.split("."):e).reduce(function(i,n){return i&&i[n]},s))===void 0?f:s}function P(s,e,f,i){return(e=e.split?e.split("."):e.slice(0)).slice(0,-1).reduce(function(n,l){return/^(__proto__|constructor|prototype)$/.test(l)?{}:n[l]=n[l]||{}},s)[e.pop()]=f,s}function S(s,e){return s===void 0||s===null?e:s}function u(s,e,f,i){return S(S(f[e],i[e]),s)}function _(s){const e=s||{};function f(i){const n=function(){try{return i.options.persistedState||{}}catch{return{}}}();if(u(!0,"persist",n,e)===!1)return;const l=u(i.store.$id,"key",n,{}),b=u(!1,"overwrite",n,e),g=u(function(){try{return window.localStorage}catch{return{getItem:function(){},setItem:function(){},removeItem:function(){}}}}(),"storage",n,e),E=u(function(){return!0},"filter",n,e),v=u(JSON.stringify,"serialize",n,e),O=u(JSON.parse,"deserialize",n,e),N=u(function(t){return t},"migrate",n,{}),z=u(function(t,r){return r},"merge",n,{}),A=u(function(t){const r="@@",o=t.setItem(r,"1"),c=function(){t.removeItem(r)};o instanceof Promise?o.then(c):c()},"assertStorage",n,e);function $(t){(n.beforeHydrate||function(){})(i.store.$state);const r=z(i.store.$state,t);b?i.store.$patch(o=>{Object.keys(o).forEach(c=>{o[c]=r[c]})}):i.store.$patch(r),p()}function I(t){if(t!=null){const r=O(t),o=N(r);o instanceof Promise?o.then($):$(o)}else p()}let p;const T=new Promise(function(t){p=t});let m=0;i.store.$persistedState={isReady:function(){return T},pending:!1};try{if(process.env.NODE_ENV!=="production"){const t=A(g);t instanceof Promise?t.then(()=>h()).catch(r=>console.warn(r)):h()}else h()}catch(t){process.env.NODE_ENV!=="production"&&console.warn(t),p()}function h(){const t=g.getItem(l);t instanceof Promise?t.then(I):I(t)}i.store.$subscribe(function(t,r){if(E(t,r)===!1)return;Array.isArray(n.includePaths)&&(r=n.includePaths.reduce(function(y,w){return P(y,w,d(r,w,void 0))},{})),Array.isArray(n.excludePaths)&&(r=O(v(r)),n.excludePaths.forEach(function(y){return P(r,y,void 0)},{}));const o=v(r),c=g.setItem(l,o);c instanceof Promise&&(++m,i.store.$persistedState.pending=m!==0,c.catch(function(){}).finally(function(){--m,i.store.$persistedState.pending=m!==0}))})}return f}a.createPersistedStatePlugin=_,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});