react-understate
Version:
A lightweight, reactive signals library for React 18+ with automatic dependency tracking and optimized performance
2 lines (1 loc) • 15.1 kB
JavaScript
function e(e){return e.split("\n").slice(1).find(e=>!e.includes("core.ts")&&!e.includes("derived.ts")&&!e.includes("effects.ts")&&!e.includes("react.ts")&&!e.includes("node_modules")&&!e.includes("dist/react-understate")&&!e.includes(".js?t=")&&!e.includes("rollup")&&!e.includes("vite")&&!e.includes("ModuleJob.run")&&!e.includes("node:internal")&&""!==e.trim()&&e.includes(":"))}function t(e){const t=e.match(/at\s+(.+):(\d+):(\d+)/);if(t){const[,e,n,o]=t;if(e&&n&&o)return{file:e,line:n,col:o}}return null}function n(e,t,n){return`%c${e}:${t}:${n}`}function o(){return"color: #0066cc; text-decoration: underline; cursor: pointer;"}function r(o,r){if(r.enabled&&r.logger){if(r.showFile){const i=Error().stack;if(i){const c=e(i);if(c){const e=t(c);return e?void r.logger(`${o} ${n(e.file,e.line,e.col)}`,"color: #0066cc; text-decoration: underline; cursor: pointer;"):void r.logger(`${o} at ${c.trim()}`)}}}r.logger(o)}}function i(e){if(e.includes("."))throw Error(`Invalid state name '${e}': Names cannot contain dots (.) as they break the code.`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid state name '${e}': Names must be valid JavaScript identifiers (start with letter, underscore, or $, followed by letters, numbers, underscores, or $).`);return e}function c(e){return void 0!==e&&(Z={...Z,...e}),{...Z}}function s(e,t){const n=t?i(t):void 0;if(n&&"undefined"!=typeof window){h();const t=window.reactUnderstate;if(t.actions[n])throw Error(`Action with name '${n}' already exists. Action names must be unique.`);t.actions[n]=e}return(...t)=>{n&&r(`action: '${n}'`,Z);const o=new AbortController,i={signal:o.signal};if(n&&B.has(n)){const o=B.get(n);return o&&"object"==typeof o&&"abort"in o&&o.abort(),G.has(n)||G.set(n,[]),new Promise((o,r)=>{G.get(n).push(()=>{try{const i=new AbortController,c={signal:i.signal},s=[...t];if(e.length>0){const e=s[s.length-1];"object"==typeof e&&null!==e&&"signal"in e?s[s.length-1]=c:s.push(c)}const u=e(...s);if(u instanceof Promise){const e=u;B.set(n,{promise:e,abort:()=>i.abort()}),e.then(o).catch(r).finally(()=>{B.delete(n);const e=G.get(n);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}})}else{o(u);const e=G.get(n);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}}}catch(i){r(i)}})})}let c;if($(()=>{if(e.length>0){const e=t[t.length-1];"object"==typeof e&&null!==e&&"signal"in e?t[t.length-1]=i:t.push(i)}c=e(...t)}),n&&c&&"object"==typeof c&&"then"in c){const e=c,t={promise:e,abort:()=>o.abort()};B.set(n,t),e.finally(()=>{B.delete(n);const e=G.get(n);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}})}return c}}function u(e,t){const n=t?i(t):void 0;let o=e;const s=new Set,u=new Set,f=()=>{s.forEach(e=>{e!==M&&e()}),u.forEach(e=>{if(0!=H?.preventLoops&&function(e){return K.has(e)}(w)&&(e===M||e===k))return;const t=function(e){return W.get(e)}(e);0!=t?.preventLoops&&function(e,t){const n=I.get(e);return!!n&&n.has(t)}(e,w)||e()})},l=async e=>{try{let i;const s=c();if("function"==typeof e){const c=e(o);if(c instanceof Promise)try{i=await c,n&&r(`state: '${n}' async resolved: ${JSON.stringify(i,null,2)}`,s)}catch(t){throw n&&r(`state: '${n}' async rejected: ${t}`,s),t}else i=c}else i=e;Object.is(o,i)||(n&&r(`state: '${n}' ${JSON.stringify(i,null,2)}`,s),o=i,function(e){if(!k)return;let t=I.get(k);t||(t=new Set,I.set(k,t)),t.add(e)}(w),P.add(f),z||a())}catch{}},w={get rawValue(){return o},update:async e=>{try{const i=e(o);if(i instanceof Promise)try{const e=await i;if(n){const t=c();r(`state: '${n}' update async resolved: ${JSON.stringify(e,null,2)}`,t)}l(e)}catch(t){if(n){const e=c();r(`state: '${n}' update async rejected: ${t}`,e)}throw t}else l(i)}catch{}},subscribe:e=>(s.add(e),()=>s.delete(e)),get value(){return M&&(d(w),u.add(M)),o},set value(e){if("function"==typeof e){const t=e(o);if(t instanceof Promise)return void t.then(e=>l(e));l(t)}else l(e)},get requiredValue(){if(M&&(d(w),u.add(M)),null==o)throw Error(`Required value${n?` '${n}'`:""} is ${null===o?"null":"undefined"}. Use .value to access the actual value or ensure the state is initialized.`);return o},set requiredValue(e){if(null==e)throw Error(`Cannot set required value${n?` '${n}'`:""} to ${null===e?"null":"undefined"}. Use .value to set null/undefined values.`);l(e)},toString:()=>o+""};if(n&&"undefined"!=typeof window){if(h(),window.reactUnderstate.states[n])throw Error(`State with name '${n}' already exists. State names must be unique.`);window.reactUnderstate.states[n]=w}return w}function a(){if(0===P.size)return;const e=Array.from(P);P.clear(),e.forEach(e=>e())}function f(e){const t=M;return M=e,t}function l(e){const t=H;return H=e,t}function d(e){M&&0!=H?.preventLoops&&M===k&&K.add(e)}function w(){K.clear()}function y(e){U.set(e,new Set(K))}function v(e){k=e}function p(e){const t=z;return z=e,t}function $(e,t){const n=t?i(t):void 0;if(n&&r(`batch: '${n}'`,Z),z)e();else{p(1);try{e()}finally{p(0),a()}}}function h(){"undefined"==typeof window||F||(window.reactUnderstate={configureDebug:c,states:{},actions:{}},F=1)}function b(e,t){const n=t?i(t):void 0;let o,s=1,u=0;const a=new Set,l=new Set,d=()=>{s=1,a.forEach(e=>{e!==d&&e()}),l.forEach(e=>{e!==d&&e()})},w=()=>{if(s&&!u){u=1;const t=f(d);try{if(o=e(),n){const e=c();r(`derived: '${n}' ${JSON.stringify(o,null,2)}`,e)}}finally{f(t),u=0}s=0}const t=f(null);return t&&l.add(t),o};try{const t=f(d);try{o=e(),s=0}finally{f(t)}}catch{o=void 0,s=1}const y={rawValue:o,update:()=>{throw Error("Cannot update derived values directly")},subscribe:e=>(a.add(e),()=>a.delete(e)),get value(){const e=f(null);return e&&l.add(e),w()},set value(e){throw Error("Cannot update derived values directly")},get requiredValue(){const e=f(null);e&&l.add(e);const t=w();if(null==t)throw Error(`Required derived value${n?` '${n}'`:""} is ${null===t?"null":"undefined"}. Use .value to access the actual value or ensure the derived value is properly computed.`);return t},set requiredValue(e){throw Error(`Cannot set required value on derived value${n?` '${n}'`:""} - they are computed from dependencies`)}};if(n&&"undefined"!=typeof window){if(window.reactUnderstate||(window.reactUnderstate={configureDebug:()=>({}),states:{},actions:{}}),window.reactUnderstate.states[n])throw Error(`Derived value with name '${n}' already exists. State names must be unique.`);window.reactUnderstate.states[n]=y}return y}function O(e,t){const n=t?i(t):void 0;let o,s=1;const u=new Set,a=new Set,l=()=>{if(!s){if(s=1,n){const e=c();r(`asyncDerived: '${n}' marked dirty`,e)}u.forEach(e=>{e!==l&&e()})}},d=async()=>{if(s){s=0;const i=f(l);try{if(n){const e=c();r(`asyncDerived: '${n}' computing`,e)}o=e();const t=await o;if(n){const e=c();r(`asyncDerived: '${n}' async resolved: ${JSON.stringify(t,null,2)}`,e)}return t}catch(t){if(n){const e=c();r(`asyncDerived: '${n}' async rejected: ${t}`,e)}throw t}finally{f(i)}}return o};try{const t=f(l);try{o=e(),s=0,o.catch(e=>{if(n){const t=c();r(`asyncDerived: '${n}' async rejected: ${e}`,t)}})}finally{f(t)}}catch(y){if(o=Promise.reject(y),s=0,n){const e=c();r(`asyncDerived: '${n}' async rejected: ${y}`,e)}}const w={get rawValue(){return o},get value(){const e=f(null);return e&&a.add(e),s&&d().catch(e=>{}),o},async update(e){throw Error("Cannot update async derived values directly - they are computed from dependencies")},subscribe:e=>(u.add(e),()=>u.delete(e)),get requiredValue(){const e=f(null);return e&&a.add(e),s&&d().catch(e=>{}),o.then(e=>{if(null==e)throw Error(`Required async derived value${n?` '${n}'`:""} is ${null===e?"null":"undefined"}. Use .value to access the actual value or ensure the async derived value is properly computed.`);return e})},set requiredValue(e){throw Error(`Cannot set required value on async derived value${n?` '${n}'`:""} - they are computed from dependencies`)}};if(n&&"undefined"!=typeof window){if(window.reactUnderstate||(window.reactUnderstate={configureDebug:()=>({}),states:{},actions:{}}),window.reactUnderstate.states[n])throw Error(`Async derived value with name '${n}' already exists. State names must be unique.`);window.reactUnderstate.states[n]=w}return w}function m(e,t,n){const o=t?i(t):void 0;let s,u=0,a=0,d=0,p=0;const h=[],b={preventLoops:1,preventOverlap:1,...n},O=(t=0)=>{if(u)return;if(b.once&&a)return;if(o&&t&&Q.has(o)){const e=Q.get(o);return e&&"object"==typeof e&&"abort"in e&&e.abort(),X.has(o)||X.set(o,[]),void X.get(o).push(()=>O(1))}if(b.preventOverlap&&d)return void(p=1);if(0!=b.preventLoops){const e=Date.now();if(h.push(e),h.length>20&&h.shift(),h.length>=5){const t=h.filter(t=>1e3>e-t);if(t.length>10)return void 0!==console&&console.error&&t.length,void(u=1)}}if(d=1,o){const e=c();r(`effect: '${o}' running`,e)}if(s){try{s()}catch(m){}s=void 0}w(),v(O),function(e){I.set(e,new Set)}(O),w();const n=l(b),i=f(O);try{if(o){const e=Q.get(o);e&&"object"==typeof e&&"abort"in e&&e.abort()}const t=new AbortController,u={signal:t.signal};let w;if($(()=>{w=e(u)}),y(O),w instanceof Promise){if(o){const e={promise:w,abort:()=>t.abort()};Q.set(o,e)}f(i),l(n),v(null),w.then(e=>{if(s=e,o){const e=c();r(`effect: '${o}' async resolved`,e)}}).catch(e=>{if(o){const t=c();r(`effect: '${o}' async rejected: ${e}`,t)}}).finally(()=>{if(d=0,a=1,o){Q.delete(o);const e=X.get(o);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}}p&&(p=0,0!=b.preventLoops&&O(1))})}else y(O),s=w,f(i),l(n),v(null),d=0,a=1,p&&(p=0,0!=b.preventLoops&&O(1))}catch(S){f(i),l(n),v(null),d=0,a=1}};if(function(e,t){W.set(e,t)}(O,b),O(),o&&"undefined"!=typeof window){window.reactUnderstate||(window.reactUnderstate={configureDebug:()=>({}),states:{},actions:{}});const e=window.reactUnderstate;if(e.states[o])throw Error(`Effect with name '${o}' already exists. State names must be unique.`);e.states[o]={value:"effect",dispose:()=>{u=1,s&&(s(),s=void 0)}}}return()=>{u=1,s&&(s(),s=void 0)}}function S(){function e(e){var t,o=e.getSnapshot;e=e.value;try{return t=o(),!n(e,t)}catch(r){return 1}}var t,n,o,r,i,c,s;return J||(J=1,n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},o=(t=R).useState,r=t.useEffect,i=t.useLayoutEffect,c=t.useDebugValue,s="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,n){var s=n(),u=o({inst:{value:s,getSnapshot:n}}),a=u[0].inst,f=u[1];return i(function(){a.value=s,a.getSnapshot=n,e(a)&&f({inst:a})},[t,s,n]),r(function(){return e(a)&&f({inst:a}),t(function(){e(a)&&f({inst:a})})},[t]),c(s),s},q.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:s),q}function _(){return C||(C=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t,o=e.getSnapshot;e=e.value;try{return t=o(),!n(e,t)}catch(r){return 1}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var t=R,n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},o=t.useState,r=t.useEffect,i=t.useLayoutEffect,c=t.useDebugValue,s=0,u=0,a="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(a,f){var l,d,w,y;return s||void 0===t.startTransition||(s=1),l=f(),u||(d=f(),n(l,d)||(u=1)),d=o({inst:{value:l,getSnapshot:f}}),w=d[0].inst,y=d[1],i(function(){w.value=l,w.getSnapshot=f,e(w)&&y({inst:w})},[a,l,f]),r(function(){return e(w)&&y({inst:w}),a(function(){e(w)&&y({inst:w})})},[a]),c(l),l};N.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:a,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),N}function g(){return V||(V=1,"production"===process.env.NODE_ENV?T.exports=S():T.exports=_()),T.exports}function E(e,...t){if(e&&"object"==typeof e&&!("value"in e)&&!("subscribe"in e)){const t=e,n=function(e){const t=[];for(const n of Object.values(e))n&&"object"==typeof n&&"value"in n&&"subscribe"in n&&t.push(n);return t}(t);return x.useSyncExternalStore(e=>{const t=n.map(t=>t.subscribe(()=>{e()}));return()=>{t.forEach(e=>e())}},()=>JSON.stringify(n.map(e=>e.value))),function(e){const t={};for(const[n,o]of Object.entries(e))t[n]=o&&"object"==typeof o&&"value"in o&&"subscribe"in o?o.value:o;return t}(t)}{const n=[e,...t];return x.useSyncExternalStore(e=>{const t=n.map(t=>t.subscribe(()=>{e()}));return()=>{t.forEach(e=>e())}},()=>JSON.stringify(n.map(e=>e.value))),n.map(e=>e.value)}}function j(e){}function A(e,t,n={}){if("undefined"==typeof window)return()=>{};const{loadInitial:o=1,syncAcrossTabs:r=1,serialize:i=JSON.stringify,deserialize:c=JSON.parse,onError:s=e=>{}}=n;if(o)try{const n=localStorage.getItem(t);if(null!==n){const t=c(n);e.value=t}}catch(f){s(f)}const u=m(()=>{try{const n=i(e.value);localStorage.setItem(t,n)}catch(f){s(f)}});let a;if(r){const n=n=>{if(n.key===t&&n.storageArea===localStorage)try{if(null!==n.newValue){const t=c(n.newValue);e.value=t}}catch(f){s(f)}};window.addEventListener("storage",n),a=()=>{window.removeEventListener("storage",n)}}return()=>{u(),a?.()}}function L(e,t,n={}){if("undefined"==typeof window)return()=>{};const{loadInitial:o=1,syncAcrossTabs:r=1,serialize:i=JSON.stringify,deserialize:c=JSON.parse,onError:s=e=>{}}=n;if(o)try{const n=sessionStorage.getItem(t);if(null!==n){const t=c(n);e.value=t}}catch(f){s(f)}const u=m(()=>{try{const n=i(e.value);sessionStorage.setItem(t,n)}catch(f){s(f)}});let a;if(r){const n=n=>{if(n.key===t&&n.storageArea===sessionStorage)try{if(null!==n.newValue){const t=c(n.newValue);e.value=t}}catch(f){s(f)}};window.addEventListener("storage",n),a=()=>{window.removeEventListener("storage",n)}}return()=>{u(),a?.()}}function D(e,t,n=("undefined"!=typeof window?sessionStorage:{})){const o=[];for(const[r,i]of Object.entries(e)){const e=`${t}.${r}`;try{const t=n.getItem(e);if(null!==t){const e=JSON.parse(t);i.value=e}}catch{}const c=m(()=>{try{const t=JSON.stringify(i.value);n.setItem(e,t)}catch{}});let s;if("undefined"!=typeof window&&(n===window.localStorage||n===window.sessionStorage)){const t=t=>{if(t.key===e&&t.storageArea===n)try{if(null!==t.newValue){const e=JSON.parse(t.newValue);i.value=e}}catch{}};window.addEventListener("storage",t),s=()=>{window.removeEventListener("storage",t)}}o.push(()=>{c(),s?.()})}return()=>o.forEach(e=>e())}var T,q,J,N,C,V,x;import R from"react";let M=null,z=0;const P=new Set,B=new Map,G=new Map;let H=null;const K=new Set;let k=null;const I=new WeakMap,U=new WeakMap,W=new WeakMap;let Z={enabled:0,logger:(...e)=>console.log(...e)},F=0;const Q=new Map,X=new Map;T={exports:{}},q={},N={},x=g();export{s as action,O as asyncDerived,$ as batch,c as configureDebug,n as createFileLocation,b as derived,m as effect,e as findUserCodeLine,o as getFileLocationStyle,r as logDebug,t as parseStackLine,A as persistLocalStorage,L as persistSessionStorage,D as persistStates,j as setReact,u as state,E as useUnderstate};//# sourceMappingURL=react-understate.esm.js.map