UNPKG

stunk

Version:

Stunk is a lightweight, framework-agnostic state management library for JavaScript and TypeScript. It uses chunk-based state units for efficient updates, reactivity, and performance optimization in React, Vue(WIP), Svelte(Coming soon), and Vanilla JS/TS a

1 lines 2.25 kB
import {b}from'../chunk-PZ7A72TA.js';function u(){return r=>(console.log("Setting value:",r),r)}var m=r=>{if(r<0)throw new Error("Value must be non-negative!");return r};function T(r,c={}){let{maxHistory:n=100,skipDuplicates:p=false}=c,e=[r.get()],t=0;return {...r,get:()=>r.get(),peek:()=>r.peek(),set:i=>{let l;if(typeof i=="function"?l=i(r.get()):l=i,p){let a=e[t];if(l===a||p==="shallow"&&typeof l=="object"&&typeof a=="object"&&l!==null&&a!==null&&b(l,a))return}if(e.splice(t+1),e.push(l),e.length>n){let a=e.length-n;e.splice(0,a);}t=e.length-1,r.set(l);},undo:()=>{t<=0||(t--,r.set(e[t]));},redo:()=>{t>=e.length-1||(t++,r.set(e[t]));},canUndo:()=>t>0,canRedo:()=>t<e.length-1,getHistory:()=>[...e],clearHistory:()=>{let i=r.get();e.length=0,e.push(i),t=0;},reset:()=>{r.reset(),e.length=0,e.push(r.get()),t=0;},destroy:()=>{e.length=0,r.destroy();},subscribe:i=>r.subscribe(i)}}function h(r,c){let{key:n,serialize:p=JSON.stringify,deserialize:e=JSON.parse,onError:t}=c,d="storage"in c?c.storage:typeof window<"u"?localStorage:void 0;if(!d)return console.warn(`persist: Storage not available for key "${n}". Persistence disabled.`),{...r,clearStorage:()=>{}};let i=r.get();try{let o=d.getItem(n);if(o!==null){let s=e(o);if(s!==null&&i!==null&&(typeof s!=typeof i||Array.isArray(s)!==Array.isArray(i))){let y=`persist: Type mismatch for "${n}". Expected ${Array.isArray(i)?"array":typeof i}, got ${Array.isArray(s)?"array":typeof s}. Using initial value.`;console.warn(y),t?.(new Error(y),"load");}else r.set(s);}}catch(o){let s=o instanceof Error?o:new Error(String(o));console.error(`persist: Failed to load state for "${n}":`,s),t?.(s,"load");}let l=r.subscribe(o=>{try{d.setItem(n,p(o));}catch(s){let g=s instanceof Error?s:new Error(String(s));console.error(`persist: Failed to save state for "${n}":`,g),t?.(g,"save");}});return {...r,get:()=>r.get(),peek:()=>r.peek(),set:o=>r.set(o),subscribe:o=>r.subscribe(o),derive:o=>r.derive(o),reset:()=>r.reset(),destroy:()=>{l(),r.destroy();},clearStorage:()=>{try{d.removeItem(n);}catch(o){let s=o instanceof Error?o:new Error(String(o));console.error(`persist: Failed to clear storage for "${n}":`,s),t?.(s,"save");}}}}export{T as history,u as logger,m as nonNegativeValidator,h as persist};