react-shared-states 1.0.8 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.min.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /*!
2
- * react-shared-states v1.0.8
2
+ * react-shared-states v1.0.11
3
3
  * (c) Hichem Taboukouyout
4
4
  * Released under the MIT License.
5
5
  * Github: github.com/HichemTab-tech/react-shared-states
6
6
  */
7
7
 
8
- (function(h,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],g):(h=typeof globalThis<"u"?globalThis:h||self,g(h.ReactSharedStates={},h.React))})(this,function(h,g){"use strict";var M={exports:{}},V={};/**
8
+ (function(f,p){typeof exports=="object"&&typeof module<"u"?p(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],p):(f=typeof globalThis<"u"?globalThis:f||self,p(f.ReactSharedStates={},f.React))})(this,function(f,p){"use strict";var N={exports:{}},D={};/**
9
9
  * @license React
10
10
  * react-jsx-runtime.production.js
11
11
  *
@@ -13,7 +13,7 @@
13
13
  *
14
14
  * This source code is licensed under the MIT license found in the
15
15
  * LICENSE file in the root directory of this source tree.
16
- */var J;function se(){if(J)return V;J=1;var a=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(t,s,f){var o=null;if(f!==void 0&&(o=""+f),s.key!==void 0&&(o=""+s.key),"key"in s){f={};for(var A in s)A!=="key"&&(f[A]=s[A])}else f=s;return s=f.ref,{$$typeof:a,type:t,key:o,ref:s!==void 0?s:null,props:f}}return V.Fragment=e,V.jsx=r,V.jsxs=r,V}var C={};/**
16
+ */var J;function ie(){if(J)return D;J=1;var i=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(t,s,c){var a=null;if(c!==void 0&&(a=""+c),s.key!==void 0&&(a=""+s.key),"key"in s){c={};for(var b in s)b!=="key"&&(c[b]=s[b])}else c=s;return s=c.ref,{$$typeof:i,type:t,key:a,ref:s!==void 0?s:null,props:c}}return D.Fragment=e,D.jsx=r,D.jsxs=r,D}var C={};/**
17
17
  * @license React
18
18
  * react-jsx-runtime.development.js
19
19
  *
@@ -21,9 +21,9 @@
21
21
  *
22
22
  * This source code is licensed under the MIT license found in the
23
23
  * LICENSE file in the root directory of this source tree.
24
- */var z;function ae(){return z||(z=1,process.env.NODE_ENV!=="production"&&function(){function a(n){if(n==null)return null;if(typeof n=="function")return n.$$typeof===ye?null:n.displayName||n.name||null;if(typeof n=="string")return n;switch(n){case c:return"Fragment";case Re:return"Profiler";case _:return"StrictMode";case Pe:return"Suspense";case Oe:return"SuspenseList";case Le:return"Activity"}if(typeof n=="object")switch(typeof n.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),n.$$typeof){case d:return"Portal";case Ae:return(n.displayName||"Context")+".Provider";case Te:return(n._context.displayName||"Context")+".Consumer";case we:var i=n.render;return n=n.displayName,n||(n=i.displayName||i.name||"",n=n!==""?"ForwardRef("+n+")":"ForwardRef"),n;case je:return i=n.displayName||null,i!==null?i:a(n.type)||"Memo";case K:i=n._payload,n=n._init;try{return a(n(i))}catch{}}return null}function e(n){return""+n}function r(n){try{e(n);var i=!1}catch{i=!0}if(i){i=console;var b=i.error,p=typeof Symbol=="function"&&Symbol.toStringTag&&n[Symbol.toStringTag]||n.constructor.name||"Object";return b.call(i,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",p),e(n)}}function t(n){if(n===c)return"<>";if(typeof n=="object"&&n!==null&&n.$$typeof===K)return"<...>";try{var i=a(n);return i?"<"+i+">":"<...>"}catch{return"<...>"}}function s(){var n=D.A;return n===null?null:n.getOwner()}function f(){return Error("react-stack-top-frame")}function o(n){if(q.call(n,"key")){var i=Object.getOwnPropertyDescriptor(n,"key").get;if(i&&i.isReactWarning)return!1}return n.key!==void 0}function A(n,i){function b(){$||($=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",i))}b.isReactWarning=!0,Object.defineProperty(n,"key",{get:b,configurable:!0})}function L(){var n=a(this.type);return ee[n]||(ee[n]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),n=this.props.ref,n!==void 0?n:null}function O(n,i,b,p,j,w,W,U){return b=w.ref,n={$$typeof:S,type:n,key:i,props:w,_owner:j},(b!==void 0?b:null)!==null?Object.defineProperty(n,"ref",{enumerable:!1,get:L}):Object.defineProperty(n,"ref",{enumerable:!1,value:null}),n._store={},Object.defineProperty(n._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(n,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(n,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:W}),Object.defineProperty(n,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(n.props),Object.freeze(n)),n}function P(n,i,b,p,j,w,W,U){var v=i.children;if(v!==void 0)if(p)if(Ve(v)){for(p=0;p<v.length;p++)u(v[p]);Object.freeze&&Object.freeze(v)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else u(v);if(q.call(i,"key")){v=a(n);var y=Object.keys(i).filter(function(Ce){return Ce!=="key"});p=0<y.length?"{key: someKey, "+y.join(": ..., ")+": ...}":"{key: someKey}",ne[v+p]||(y=0<y.length?"{"+y.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
24
+ */var z;function oe(){return z||(z=1,process.env.NODE_ENV!=="production"&&function(){function i(n){if(n==null)return null;if(typeof n=="function")return n.$$typeof===De?null:n.displayName||n.name||null;if(typeof n=="string")return n;switch(n){case v:return"Fragment";case O:return"Profiler";case L:return"StrictMode";case Pe:return"Suspense";case Le:return"SuspenseList";case je:return"Activity"}if(typeof n=="object")switch(typeof n.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),n.$$typeof){case h:return"Portal";case we:return(n.displayName||"Context")+".Provider";case Ae:return(n._context.displayName||"Context")+".Consumer";case ye:var o=n.render;return n=n.displayName,n||(n=o.displayName||o.name||"",n=n!==""?"ForwardRef("+n+")":"ForwardRef"),n;case Oe:return o=n.displayName||null,o!==null?o:i(n.type)||"Memo";case $:o=n._payload,n=n._init;try{return i(n(o))}catch{}}return null}function e(n){return""+n}function r(n){try{e(n);var o=!1}catch{o=!0}if(o){o=console;var d=o.error,m=typeof Symbol=="function"&&Symbol.toStringTag&&n[Symbol.toStringTag]||n.constructor.name||"Object";return d.call(o,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",m),e(n)}}function t(n){if(n===v)return"<>";if(typeof n=="object"&&n!==null&&n.$$typeof===$)return"<...>";try{var o=i(n);return o?"<"+o+">":"<...>"}catch{return"<...>"}}function s(){var n=V.A;return n===null?null:n.getOwner()}function c(){return Error("react-stack-top-frame")}function a(n){if(ee.call(n,"key")){var o=Object.getOwnPropertyDescriptor(n,"key").get;if(o&&o.isReactWarning)return!1}return n.key!==void 0}function b(n,o){function d(){te||(te=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",o))}d.isReactWarning=!0,Object.defineProperty(n,"key",{get:d,configurable:!0})}function _(){var n=i(this.type);return re[n]||(re[n]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),n=this.props.ref,n!==void 0?n:null}function y(n,o,d,m,P,A,M,U){return d=A.ref,n={$$typeof:g,type:n,key:o,props:A,_owner:P},(d!==void 0?d:null)!==null?Object.defineProperty(n,"ref",{enumerable:!1,get:_}):Object.defineProperty(n,"ref",{enumerable:!1,value:null}),n._store={},Object.defineProperty(n._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(n,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(n,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(n,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(n.props),Object.freeze(n)),n}function w(n,o,d,m,P,A,M,U){var E=o.children;if(E!==void 0)if(m)if(Ce(E)){for(m=0;m<E.length;m++)l(E[m]);Object.freeze&&Object.freeze(E)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else l(E);if(ee.call(o,"key")){E=i(n);var j=Object.keys(o).filter(function(ke){return ke!=="key"});m=0<j.length?"{key: someKey, "+j.join(": ..., ")+": ...}":"{key: someKey}",ae[E+m]||(j=0<j.length?"{"+j.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
25
25
  let props = %s;
26
26
  <%s {...props} />
27
27
  React keys must be passed directly to JSX without using spread:
28
28
  let props = %s;
29
- <%s key={someKey} {...props} />`,p,v,y,v),ne[v+p]=!0)}if(v=null,b!==void 0&&(r(b),v=""+b),o(i)&&(r(i.key),v=""+i.key),"key"in i){b={};for(var G in i)G!=="key"&&(b[G]=i[G])}else b=i;return v&&A(b,typeof n=="function"?n.displayName||n.name||"Unknown":n),O(n,v,w,j,s(),b,W,U)}function u(n){typeof n=="object"&&n!==null&&n.$$typeof===S&&n._store&&(n._store.validated=1)}var m=g,S=Symbol.for("react.transitional.element"),d=Symbol.for("react.portal"),c=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),Re=Symbol.for("react.profiler"),Te=Symbol.for("react.consumer"),Ae=Symbol.for("react.context"),we=Symbol.for("react.forward_ref"),Pe=Symbol.for("react.suspense"),Oe=Symbol.for("react.suspense_list"),je=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),Le=Symbol.for("react.activity"),ye=Symbol.for("react.client.reference"),D=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q=Object.prototype.hasOwnProperty,Ve=Array.isArray,I=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(n){return n()}};var $,ee={},te=m.react_stack_bottom_frame.bind(m,f)(),re=I(t(f)),ne={};C.Fragment=c,C.jsx=function(n,i,b,p,j){var w=1e4>D.recentlyCreatedOwnerStacks++;return P(n,i,b,!1,p,j,w?Error("react-stack-top-frame"):te,w?I(t(n)):re)},C.jsxs=function(n,i,b,p,j){var w=1e4>D.recentlyCreatedOwnerStacks++;return P(n,i,b,!0,p,j,w?Error("react-stack-top-frame"):te,w?I(t(n)):re)}}()),C}var X;function oe(){return X||(X=1,process.env.NODE_ENV==="production"?M.exports=se():M.exports=ae()),M.exports}var ie=oe();h.isDevMode=!1;const ce=a=>{h.isDevMode=a},N=(...a)=>{h.isDevMode&&console.log("%c[react-shared-states]","color: #007acc; font-weight: bold",...a)},T=a=>{if(!a)throw new Error("Value is empty");return a},F=()=>Math.random().toString(36).substring(2,15),B=g.createContext(void 0),le=({children:a,scopeName:e})=>{if(e&&e.includes("//"))throw new Error("scopeName cannot contain '//'");return e||(e=g.useMemo(()=>F(),[])),ie.jsx(B.Provider,{value:{scopeName:e},children:a})},ue=()=>g.useContext(B);class l{data=new Map;defaultValue(){return{}}addListener(e,r,t){this.data.has(l.prefix(e,r))||this.data.set(l.prefix(e,r),{...this.defaultValue,listeners:[]}),this.data.get(l.prefix(e,r)).listeners.push(t)}removeListener(e,r,t){this.data.has(l.prefix(e,r))&&(this.data.get(l.prefix(e,r)).listeners=this.data.get(l.prefix(e,r)).listeners.filter(s=>s!==t))}callListeners(e,r){this.data.has(l.prefix(e,r))&&this.data.get(l.prefix(e,r)).listeners.forEach(t=>t())}init(e,r,t){this.data.has(l.prefix(e,r))||this.data.set(l.prefix(e,r),{...t,listeners:[]})}clearAll(e=!1){e||this.data.forEach(r=>{r.listeners.forEach(t=>t())}),this.data.clear()}clear(e,r,t=!1){t||this.callListeners(e,r),this.data.delete(l.prefix(e,r))}get(e,r){let t=this.has(e,r);if(t)return this.data.get(t)}setValue(e,r,t){this.data.has(l.prefix(e,r))&&this.data.set(l.prefix(e,r),{...this.data.get(l.prefix(e,r)),...t})}has(e,r){return this.data.has(l.prefix(e,r))?l.prefix(e,r):this.data.has(l.prefix(e,"_global"))?l.prefix(e,"_global"):void 0}static prefix(e,r){if(e.includes("//"))throw new Error("key cannot contain '//'");return`${r}//${e}`}static extractPrefix(e){return e.split("//")}useEffect(e,r,t=null){g.useEffect(()=>()=>{t?.(),N(`[${l.prefix(e,r)}]`,"unmount effect"),this.data.get(l.prefix(e,r)).listeners?.length===0&&this.clear(e,r)},[])}}class Y{constructor(e){this.sharedData=e}get(e,r){e=T(e);const t=r||"_global";return this.sharedData.get(e,t)}set(e,r,t){e=T(e);const s=t||"_global";this.sharedData.setValue(e,s,r)}clearAll(){this.sharedData.clearAll()}clearScope(e){const r=e||"_global";this.sharedData.data.forEach((t,s)=>{const[f]=l.extractPrefix(s);if(f===r){this.sharedData.clear(s,f);return}})}resolve(e){const{key:r,prefix:t}=e;return this.get(r,t)}clear(e,r){let t,s;typeof e=="string"?(t=e,s=r||"_global"):(t=e.key,s=e.prefix),this.sharedData.clear(t,s)}has(e,r="_global"){const t=r||"_global";return!!this.sharedData.has(e,t)}getAll(){const e={};return this.sharedData.data.forEach((r,t)=>{const[s,f]=l.extractPrefix(t);e[s]=e[s]||{},e[s][f]=r}),e}}const k=a=>{const e=ue();return{prefix:a??e?.scopeName??"_global"}};class fe extends l{defaultValue(){return{value:void 0}}init(e,r,t){super.init(e,r,{value:t})}setValue(e,r,t){super.setValue(e,r,{value:t})}removeListener(e,r,t){super.removeListener(e,r,t)}}class H extends Y{get(e,r="_global"){e=T(e);const t=r||"_global";return R.get(e,t)?.value}set(e,r,t="_global"){e=T(e);const s=t||"_global";R.setValue(e,s,{value:r})}}const R=new fe,de=new H(R),he=(a,e)=>{const r=e??e??"_global";return{key:F(),prefix:r,initialValue:a}};function be(a,e,r){let t,s,f=r;if(typeof a!="string"){const{key:u,initialValue:m,prefix:S}=a;t=u,s=m,f=S}else t=T(a),s=e;const{prefix:o}=k(f);R.init(t,o,s);const A=g.useMemo(()=>u=>(R.init(t,o,e),R.addListener(t,o,u),()=>{R.removeListener(t,o,u)}),[]),L=g.useMemo(()=>()=>R.get(t,o)?.value,[]),O=g.useSyncExternalStore(A,L),P=u=>{const m=typeof u=="function"?u(R.get(t,o)?.value):u;m!==O&&(R.setValue(t,o,m),R.callListeners(t,o))};return R.useEffect(t,o),[O,P]}class Se extends l{defaultValue(){return{fnState:{results:void 0,isLoading:!1,error:void 0}}}init(e,r){super.init(e,r,this.defaultValue())}setValue(e,r,t){super.setValue(e,r,t)}}class Z extends Y{get(e,r="_global"){e=T(e);const t=r||"_global";return x.get(e,t)?.fnState}set(e,r,t="_global"){e=T(e);const s=t||"_global";x.setValue(e,s,r)}}const x=new Se,ge=new Z(x),pe=(a,e)=>{const r=e??e??"_global";return{key:F(),prefix:r,fn:a}};function ve(a,e,r){let t,s,f=r;if(typeof a!="string"){const{key:u,fn:m,prefix:S}=a;t=u,s=m,f=S}else t=T(a),s=e;const{prefix:o}=k(f);x.init(t,o);const A=g.useMemo(()=>u=>(x.init(t,o),x.addListener(t,o,u),()=>{x.removeListener(t,o,u)}),[]),L=g.useMemo(()=>()=>x.get(t,o).fnState,[]),O=g.useSyncExternalStore(A,L),P=async(u,...m)=>{const S=x.get(t,o);if(!u&&(S.fnState.isLoading||S.fnState.results!==void 0))return S.fnState;S.fnState={...S.fnState,isLoading:!0,error:void 0},S.listeners.forEach(d=>d());try{const d=await s(...m);S.fnState={results:d,isLoading:!1,error:void 0}}catch(d){S.fnState={...S.fnState,isLoading:!1,error:d}}S.listeners.forEach(d=>d())};return x.useEffect(t,o),{state:O,trigger:(...u)=>{P(!1,...u)},forceTrigger:(...u)=>{P(!0,...u)},clear:()=>{const u=x.get(t,o);u&&(u.fnState=x.defaultValue().fnState,x.callListeners(t,o))}}}class Ee extends l{defaultValue(){return{fnState:{data:void 0,isLoading:!1,error:void 0,subscribed:!1}}}init(e,r){super.init(e,r,this.defaultValue())}setValue(e,r,t){super.setValue(e,r,t)}useEffect(e,r){g.useEffect(()=>()=>{N(`[${l.prefix(e,r)}]`,"unmount effect2"),this.get(e,r)?.listeners.length===0&&this.unsubscribe(e,r)},[]),super.useEffect(e,r)}async unsubscribe(e,r){const t=this.get(e,r);t&&(t.unsubscribe&&(t.unsubscribe(),t.unsubscribe=void 0),t.fnState={...t.fnState,subscribed:!1},this.callListeners(e,r))}}class Q extends Y{get(e,r="_global"){e=T(e);const t=r||"_global";return E.get(e,t)?.fnState}set(e,r,t="_global"){e=T(e);const s=t||"_global";E.setValue(e,s,r)}}const E=new Ee,me=new Q(E),xe=(a,e)=>{const r=e??e??"_global";return{key:F(),prefix:r,subscriber:a}};function _e(a,e,r){let t,s,f=r;if(typeof a!="string"){const{key:d,subscriber:c,prefix:_}=a;t=d,s=c,f=_}else t=T(a),s=e;const{prefix:o}=k(f);E.init(t,o);const A=g.useMemo(()=>d=>(E.init(t,o),E.addListener(t,o,d),()=>{E.removeListener(t,o,d)}),[]),L=g.useMemo(()=>()=>E.get(t,o).fnState,[]),O=g.useSyncExternalStore(A,L),P=d=>{const c=E.get(t,o);c.fnState={...c.fnState,data:d},c.listeners.forEach(_=>_())},u=d=>{const c=E.get(t,o);c.fnState={...c.fnState,isLoading:!1,data:void 0,error:d},c.listeners.forEach(_=>_())},m=()=>{const d=E.get(t,o);d.fnState={...d.fnState,isLoading:!1},d.listeners.forEach(c=>c())},S=async d=>{const c=E.get(t,o);if(d&&(await E.unsubscribe(t,o),c.fnState={...c.fnState,isLoading:!1,data:void 0,error:void 0,subscribed:!1}),c.fnState.subscribed)return c.fnState;N("triggered !!"),c.fnState={...c.fnState,isLoading:!0,error:void 0},c.listeners.forEach(_=>_());try{c.unsubscribe=await s(P,u,m),c.fnState.subscribed=!0}catch(_){c.fnState={...c.fnState,isLoading:!1,error:_}}c.listeners.forEach(_=>_())};return E.useEffect(t,o),{state:O,trigger:()=>{S(!1)},forceTrigger:()=>{S(!0)},unsubscribe:()=>{E.unsubscribe(t,o)}}}h.SharedFunctionsApi=Z,h.SharedStatesApi=H,h.SharedStatesProvider=le,h.SharedSubscriptionsApi=Q,h.createSharedFunction=pe,h.createSharedState=he,h.createSharedSubscription=xe,h.setDevMode=ce,h.sharedFunctionsApi=ge,h.sharedStatesApi=de,h.sharedSubscriptionsApi=me,h.useSharedFunction=ve,h.useSharedState=be,h.useSharedSubscription=_e,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});
29
+ <%s key={someKey} {...props} />`,m,E,j,E),ae[E+m]=!0)}if(E=null,d!==void 0&&(r(d),E=""+d),a(o)&&(r(o.key),E=""+o.key),"key"in o){d={};for(var G in o)G!=="key"&&(d[G]=o[G])}else d=o;return E&&b(d,typeof n=="function"?n.displayName||n.name||"Unknown":n),y(n,E,A,P,s(),d,M,U)}function l(n){typeof n=="object"&&n!==null&&n.$$typeof===g&&n._store&&(n._store.validated=1)}var x=p,g=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),L=Symbol.for("react.strict_mode"),O=Symbol.for("react.profiler"),Ae=Symbol.for("react.consumer"),we=Symbol.for("react.context"),ye=Symbol.for("react.forward_ref"),Pe=Symbol.for("react.suspense"),Le=Symbol.for("react.suspense_list"),Oe=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),je=Symbol.for("react.activity"),De=Symbol.for("react.client.reference"),V=x.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ee=Object.prototype.hasOwnProperty,Ce=Array.isArray,W=console.createTask?console.createTask:function(){return null};x={react_stack_bottom_frame:function(n){return n()}};var te,re={},ne=x.react_stack_bottom_frame.bind(x,c)(),se=W(t(c)),ae={};C.Fragment=v,C.jsx=function(n,o,d,m,P){var A=1e4>V.recentlyCreatedOwnerStacks++;return w(n,o,d,!1,m,P,A?Error("react-stack-top-frame"):ne,A?W(t(n)):se)},C.jsxs=function(n,o,d,m,P){var A=1e4>V.recentlyCreatedOwnerStacks++;return w(n,o,d,!0,m,P,A?Error("react-stack-top-frame"):ne,A?W(t(n)):se)}}()),C}var X;function ce(){return X||(X=1,process.env.NODE_ENV==="production"?N.exports=ie():N.exports=oe()),N.exports}var ue=ce();f.isDevMode=!1;const le=i=>{f.isDevMode=i},F=(...i)=>{f.isDevMode&&console.log("%c[react-shared-states]","color: #007acc; font-weight: bold",...i)},k=i=>{if(!i)throw new Error("Value is empty");return i},B=()=>Math.random().toString(36).substring(2,15),H=p.createContext(void 0),fe=({children:i,scopeName:e})=>{if(e&&e.includes("//"))throw new Error("scopeName cannot contain '//'");return e||(e=p.useMemo(()=>B(),[])),ue.jsx(H.Provider,{value:{scopeName:e},children:i})},de=()=>p.useContext(H),Z=[];class u{data=new Map;defaultValue(){return{}}addListener(e,r,t){this.data.has(u.prefix(e,r))||this.data.set(u.prefix(e,r),{...this.defaultValue(),listeners:[]}),this.data.get(u.prefix(e,r)).listeners.push(t)}removeListener(e,r,t){this.data.has(u.prefix(e,r))&&(this.data.get(u.prefix(e,r)).listeners=this.data.get(u.prefix(e,r)).listeners.filter(s=>s!==t))}callListeners(e,r){this.data.has(u.prefix(e,r))&&this.data.get(u.prefix(e,r)).listeners.forEach(t=>t())}init(e,r,t,s=!1){this.data.has(u.prefix(e,r))||this.data.set(u.prefix(e,r),{...t,isStatic:s,listeners:[]})}createStatic(e,r){const t=r??r??"_global",s={key:B(),prefix:t,...e};return Z.push(s),this.initStatic(s),s}initStatic(e){const{key:r,prefix:t}=e;this.init(r,t,this.defaultValue(),!0)}clearAll(e=!1,r=!1){this.data.forEach((t,s)=>{const[c,a]=u.extractPrefix(s);this.clear(a,c,e,r)})}clear(e,r,t=!1,s=!1){t||this.callListeners(e,r);const c=this.data.get(u.prefix(e,r));if(!c)return;const a={...c};if(this.data.delete(u.prefix(e,r)),a.isStatic&&!s){const b=Z.find(_=>_.key===e&&_.prefix===r);b&&this.initStatic(b)}}get(e,r){let t=this.has(e,r);if(t)return this.data.get(t)}setValue(e,r,t){this.data.has(u.prefix(e,r))&&this.data.set(u.prefix(e,r),{...this.data.get(u.prefix(e,r)),...t})}has(e,r){return this.data.has(u.prefix(e,r))?u.prefix(e,r):this.data.has(u.prefix(e,"_global"))?u.prefix(e,"_global"):void 0}static prefix(e,r){if(e.includes("//"))throw new Error("key cannot contain '//'");return`${r}//${e}`}static extractPrefix(e){return e.split("//")}useEffect(e,r,t=null){p.useEffect(()=>()=>{t?.(),F(`[${u.prefix(e,r)}]`,"unmount effect"),this.data.get(u.prefix(e,r)).listeners?.length===0&&this.clear(e,r)},[])}}class Y{constructor(e){this.sharedData=e}get(e,r){let t,s=r;if(typeof e!="string"){const{key:b,prefix:_}=e;t=b,s=_}else t=k(e);const c=s||"_global";return this.sharedData.get(t,c)}set(e,r,t){let s,c=t;if(typeof e!="string"){const{key:b,prefix:_}=e;s=b,c=_}else s=k(e);const a=c||"_global";this.sharedData.setValue(s,a,r)}clearAll(){this.sharedData.clearAll()}clearScope(e){const r=e||"_global";this.sharedData.data.forEach((t,s)=>{const[c,a]=u.extractPrefix(s);if(c===r){this.sharedData.clear(a,c);return}})}resolve(e){const{key:r,prefix:t}=e;return this.get(r,t)}clear(e,r){let t,s;typeof e=="string"?(t=e,s=r||"_global"):(t=e.key,s=e.prefix),this.sharedData.clear(t,s)}has(e,r="_global"){const t=r||"_global";return!!this.sharedData.has(e,t)}getAll(){const e={};return this.sharedData.data.forEach((r,t)=>{const[s,c]=u.extractPrefix(t);e[s]=e[s]||{},e[s][c]=r}),e}}const I=i=>{const e=de();return{prefix:i??e?.scopeName??"_global"}};class Se extends u{defaultValue(){return{value:void 0}}initValue(e,r,t,s=!1){super.init(e,r,{value:t},s)}initStatic(e){const{key:r,prefix:t,initialValue:s}=e;this.initValue(r,t,s,!0)}}class Q extends Y{constructor(e){super(e)}get(e,r="_global"){return typeof e!="string"?super.get(e)?.value:super.get(e,r)?.value}set(e,r,t="_global"){if(typeof e!="string"){super.set(e,{value:r});return}super.set(e,{value:r},t)}}const T=new Se,pe=new Q(T),he=(i,e)=>T.createStatic({initialValue:i},e);function be(i,e,r){let t,s,c=r;if(typeof i!="string"){const{key:l,initialValue:x,prefix:g}=i;t=l,s=x,c=g}else t=k(i),s=e;const{prefix:a}=I(c);T.initValue(t,a,s);const b=p.useMemo(()=>l=>(T.initValue(t,a,e),T.addListener(t,a,l),()=>{T.removeListener(t,a,l)}),[]),_=p.useMemo(()=>()=>T.get(t,a)?.value,[]),y=p.useSyncExternalStore(b,_),w=l=>{const x=typeof l=="function"?l(T.get(t,a)?.value):l;x!==y&&(T.setValue(t,a,{value:x}),T.callListeners(t,a))};return T.useEffect(t,a),[y,w]}class ge extends u{defaultValue(){return{fnState:{results:void 0,isLoading:!1,error:void 0}}}initValue(e,r,t=!1){super.init(e,r,this.defaultValue(),t)}setValue(e,r,t){super.setValue(e,r,t)}}class K extends Y{constructor(e){super(e)}get(e,r="_global"){return typeof e!="string"?super.get(e)?.fnState:super.get(e,r)?.fnState}set(e,r,t="_global"){if(typeof e!="string"){super.set(e,r);return}super.set(e,r,t)}}const R=new ge,ve=new K(R),me=(i,e)=>R.createStatic({fn:i},e);function Ee(i,e,r){let t,s,c=r;if(typeof i!="string"){const{key:l,fn:x,prefix:g}=i;t=l,s=x,c=g}else t=k(i),s=e;const{prefix:a}=I(c);R.initValue(t,a);const b=p.useMemo(()=>l=>(R.initValue(t,a),R.addListener(t,a,l),()=>{R.removeListener(t,a,l)}),[]),_=p.useMemo(()=>()=>R.get(t,a).fnState,[]),y=p.useSyncExternalStore(b,_),w=async(l,...x)=>{const g=R.get(t,a);if(!l&&(g.fnState.isLoading||g.fnState.results!==void 0))return g.fnState;g.fnState={...g.fnState,isLoading:!0,error:void 0},R.callListeners(t,a);try{const h=await s(...x);g.fnState={results:h,isLoading:!1,error:void 0}}catch(h){g.fnState={...g.fnState,isLoading:!1,error:h}}R.callListeners(t,a)};return R.useEffect(t,a),{state:y,trigger:(...l)=>{w(!1,...l)},forceTrigger:(...l)=>{w(!0,...l)},clear:()=>{const l=R.get(t,a);l&&(l.fnState=R.defaultValue().fnState,R.callListeners(t,a))}}}class xe extends u{defaultValue(){return{fnState:{data:void 0,isLoading:!1,error:void 0,subscribed:!1}}}initValue(e,r,t=!1){super.init(e,r,this.defaultValue(),t)}setValue(e,r,t){super.setValue(e,r,t)}useEffect(e,r){p.useEffect(()=>()=>{F(`[${u.prefix(e,r)}]`,"unmount effect2"),this.get(e,r)?.listeners.length===0&&this.unsubscribe(e,r)},[]),super.useEffect(e,r)}async unsubscribe(e,r){const t=this.get(e,r);t&&(t.unsubscribe&&(t.unsubscribe(),t.unsubscribe=void 0),t.fnState={...t.fnState,subscribed:!1},this.callListeners(e,r))}}class q extends Y{constructor(e){super(e)}get(e,r="_global"){return typeof e!="string"?super.get(e)?.fnState:super.get(e,r)?.fnState}set(e,r,t="_global"){if(typeof e!="string"){super.set(e,r);return}super.set(e,r,t)}}const S=new xe,Re=new q(S),_e=(i,e)=>S.createStatic({subscriber:i},e);function Te(i,e,r){let t,s,c=r;if(typeof i!="string"){const{key:h,subscriber:v,prefix:L}=i;t=h,s=v,c=L}else t=k(i),s=e;const{prefix:a}=I(c);S.initValue(t,a);const b=p.useMemo(()=>h=>(S.initValue(t,a),S.addListener(t,a,h),()=>{S.removeListener(t,a,h)}),[]),_=p.useMemo(()=>()=>S.get(t,a).fnState,[]),y=p.useSyncExternalStore(b,_),w=h=>{const v=S.get(t,a);v.fnState={...v.fnState,data:h},S.callListeners(t,a)},l=h=>{const v=S.get(t,a);v.fnState={...v.fnState,isLoading:!1,data:void 0,error:h},S.callListeners(t,a)},x=()=>{const h=S.get(t,a);h.fnState={...h.fnState,isLoading:!1},S.callListeners(t,a)},g=async h=>{const v=S.get(t,a);if(h&&(await S.unsubscribe(t,a),v.fnState={...v.fnState,isLoading:!1,data:void 0,error:void 0,subscribed:!1}),v.fnState.subscribed)return v.fnState;F("triggered !!"),v.fnState={...v.fnState,isLoading:!0,error:void 0},S.callListeners(t,a);try{const L=await s(w,l,x),O=S.get(t,a);O.unsubscribe=L,O.fnState.subscribed=!0}catch(L){const O=S.get(t,a);O.fnState={...O.fnState,isLoading:!1,error:L}}S.callListeners(t,a)};return S.useEffect(t,a),{state:y,trigger:()=>{g(!1)},forceTrigger:()=>{g(!0)},unsubscribe:()=>{S.unsubscribe(t,a)}}}f.SharedFunctionsApi=K,f.SharedStatesApi=Q,f.SharedStatesProvider=fe,f.SharedSubscriptionsApi=q,f.createSharedFunction=me,f.createSharedState=he,f.createSharedSubscription=_e,f.setDevMode=le,f.sharedFunctionsApi=ve,f.sharedStatesApi=pe,f.sharedSubscriptionsApi=Re,f.useSharedFunction=Ee,f.useSharedState=be,f.useSharedSubscription=Te,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
package/dist/types.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  export type PotentialPromise<T> = T | Promise<T>;
2
2
  export type AFunction<R = unknown, Args extends unknown[] = unknown[]> = (...args: Args) => PotentialPromise<R>;
3
3
  export type Prefix = "_global" | ({} & string);
4
- export interface DataMapValue {
4
+ export interface SharedValue {
5
5
  listeners: AFunction[];
6
+ isStatic?: true;
6
7
  }
7
8
  export interface SharedCreated {
8
9
  key: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-shared-states",
3
- "version": "1.0.8",
3
+ "version": "1.0.11",
4
4
  "type": "module",
5
5
  "description": "Global state made as simple as useState, with zero config, built-in async caching, and automatic scoping.",
6
6
  "keywords": [
@@ -1,15 +1,19 @@
1
- import {describe, it, expect, beforeEach, vi, afterEach} from 'vitest'
2
- import React from 'react'
3
- import {render, screen, fireEvent, act, cleanup} from '@testing-library/react'
1
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
2
+ import React, {useEffect} from 'react'
3
+ import {act, cleanup, fireEvent, render, screen} from '@testing-library/react'
4
4
  import {
5
5
  createSharedFunction,
6
- createSharedState, createSharedSubscription,
6
+ createSharedState,
7
+ createSharedSubscription,
8
+ sharedFunctionsApi,
9
+ sharedStatesApi,
7
10
  SharedStatesProvider,
11
+ sharedSubscriptionsApi,
8
12
  useSharedFunction,
9
13
  useSharedState,
10
14
  useSharedSubscription
11
15
  } from "../src";
12
- import type {SubscriberEvents} from "../src/hooks/use-shared-subscription";
16
+ import type {Subscriber, SubscriberEvents} from "../src/hooks/use-shared-subscription";
13
17
 
14
18
  // Mocking random to have predictable keys for created states/functions/subscriptions
15
19
  vi.mock('../src/lib/utils', async (importActual) => {
@@ -139,6 +143,29 @@ describe('useSharedState', () => {
139
143
 
140
144
  expect(screen.getByTestId('value1').textContent).toBe('15');
141
145
  });
146
+
147
+ it('should allow direct api manipulation with createSharedState objects', () => {
148
+ const sharedCounter = createSharedState(100);
149
+
150
+ // Get initial value
151
+ expect(sharedStatesApi.get(sharedCounter)).toBe(100);
152
+
153
+ // Set a new value
154
+ act(() => {
155
+ sharedStatesApi.set(sharedCounter, 200);
156
+ });
157
+
158
+ // Get updated value
159
+ expect(sharedStatesApi.get(sharedCounter)).toBe(200);
160
+
161
+ // Clear the value
162
+ act(() => {
163
+ sharedStatesApi.clear(sharedCounter);
164
+ });
165
+
166
+ // Get value after clear (should be initial value because createSharedState re-initializes it)
167
+ expect(sharedStatesApi.get(sharedCounter)).toBe(100);
168
+ });
142
169
  });
143
170
 
144
171
  describe('useSharedFunction', () => {
@@ -255,6 +282,108 @@ describe('useSharedFunction', () => {
255
282
  expect(mockApiCall).toHaveBeenCalledTimes(1);
256
283
  expect(screen.getByTestId('result').textContent).toBe('result: arg1');
257
284
  });
285
+
286
+ it('should allow direct api manipulation with createSharedFunction objects', () => {
287
+ const sharedFunction = createSharedFunction(async (arg: string) => `result: ${arg}`);
288
+
289
+ // Get initial state
290
+ const initialState = sharedFunctionsApi.get(sharedFunction);
291
+ expect(initialState.results).toBeUndefined();
292
+ expect(initialState.isLoading).toBe(false);
293
+ expect(initialState.error).toBeUndefined();
294
+
295
+ // Set a new state
296
+ act(() => {
297
+ sharedFunctionsApi.set(sharedFunction, {
298
+ fnState: {
299
+ results: 'test data',
300
+ isLoading: true,
301
+ error: 'test error',
302
+ }
303
+ });
304
+ });
305
+
306
+ // Get updated state
307
+ const updatedState = sharedFunctionsApi.get(sharedFunction);
308
+ expect(updatedState.results).toBe('test data');
309
+ expect(updatedState.isLoading).toBe(true);
310
+ expect(updatedState.error).toBe('test error');
311
+
312
+ // Clear the value
313
+ act(() => {
314
+ sharedFunctionsApi.clear(sharedFunction);
315
+ });
316
+
317
+ // Get value after clear (should be initial value)
318
+ const clearedState = sharedFunctionsApi.get(sharedFunction);
319
+ expect(clearedState.results).toBeUndefined();
320
+ expect(clearedState.isLoading).toBe(false);
321
+ expect(clearedState.error).toBeUndefined();
322
+ });
323
+ });
324
+
325
+ describe('useSharedSubscription', () => {
326
+ it('should handle subscription lifecycle', () => {
327
+ const mockSubscriber = vi.fn<Subscriber<string>>((set) => {
328
+ set('initial data');
329
+ return () => {
330
+ };
331
+ });
332
+
333
+ const TestComponent = () => {
334
+ const {state: {data}, trigger} = useSharedSubscription('test-sub', mockSubscriber);
335
+
336
+ useEffect(() => {
337
+ trigger();
338
+ }, []);
339
+
340
+ return <span data-testid="data">{data}</span>;
341
+ };
342
+
343
+ render(<TestComponent/>);
344
+
345
+ expect(mockSubscriber).toHaveBeenCalledTimes(1);
346
+ expect(screen.getByTestId('data').textContent).toBe('initial data');
347
+ });
348
+
349
+ it('should allow direct api manipulation with createSharedSubscription objects', () => {
350
+ const mockSubscriber = vi.fn();
351
+ const sharedSubscription = createSharedSubscription(mockSubscriber);
352
+
353
+ // Get initial state
354
+ const initialState = sharedSubscriptionsApi.get(sharedSubscription);
355
+ expect(initialState.data).toBeUndefined();
356
+ expect(initialState.isLoading).toBe(false);
357
+ expect(initialState.error).toBeUndefined();
358
+
359
+ // Set a new state
360
+ act(() => {
361
+ sharedSubscriptionsApi.set(sharedSubscription, {
362
+ fnState: {
363
+ data: 'test data',
364
+ isLoading: true,
365
+ error: 'test error',
366
+ }
367
+ });
368
+ });
369
+
370
+ // Get updated state
371
+ const updatedState = sharedSubscriptionsApi.get(sharedSubscription);
372
+ expect(updatedState.data).toBe('test data');
373
+ expect(updatedState.isLoading).toBe(true);
374
+ expect(updatedState.error).toBe('test error');
375
+
376
+ // Clear the value
377
+ act(() => {
378
+ sharedSubscriptionsApi.clear(sharedSubscription);
379
+ });
380
+
381
+ // Get value after clear (should be initial value)
382
+ const clearedState = sharedSubscriptionsApi.get(sharedSubscription);
383
+ expect(clearedState.data).toBeUndefined();
384
+ expect(clearedState.isLoading).toBe(false);
385
+ expect(clearedState.error).toBeUndefined();
386
+ });
258
387
  });
259
388
 
260
389
  describe('useSharedSubscription', () => {
@@ -355,4 +484,43 @@ describe('useSharedSubscription', () => {
355
484
  expect(mockSubscriber).toHaveBeenCalledTimes(1);
356
485
  expect(screen.getByTestId('data').textContent).toBe('initial data');
357
486
  });
487
+
488
+ it('should allow direct api manipulation with createSharedSubscription objects', () => {
489
+ const mockSubscriber = vi.fn();
490
+ const sharedSubscription = createSharedSubscription(mockSubscriber);
491
+
492
+ // Get initial state
493
+ const initialState = sharedSubscriptionsApi.get(sharedSubscription);
494
+ expect(initialState.data).toBeUndefined();
495
+ expect(initialState.isLoading).toBe(false);
496
+ expect(initialState.error).toBeUndefined();
497
+
498
+ // Set a new state
499
+ act(() => {
500
+ sharedSubscriptionsApi.set(sharedSubscription, {
501
+ fnState: {
502
+ data: 'test data',
503
+ isLoading: true,
504
+ error: 'test error',
505
+ }
506
+ });
507
+ });
508
+
509
+ // Get updated state
510
+ const updatedState = sharedSubscriptionsApi.get(sharedSubscription);
511
+ expect(updatedState.data).toBe('test data');
512
+ expect(updatedState.isLoading).toBe(true);
513
+ expect(updatedState.error).toBe('test error');
514
+
515
+ // Clear the value
516
+ act(() => {
517
+ sharedSubscriptionsApi.clear(sharedSubscription);
518
+ });
519
+
520
+ // Get value after clear (should be initial value)
521
+ const clearedState = sharedSubscriptionsApi.get(sharedSubscription);
522
+ expect(clearedState.data).toBeUndefined();
523
+ expect(clearedState.isLoading).toBe(false);
524
+ expect(clearedState.error).toBeUndefined();
525
+ });
358
526
  });