state-jet
Version:
Ultra-lightweight global state management for React
20 lines (19 loc) • 15.9 kB
JavaScript
import e,{useRef as t}from"react";var r=Symbol.for("immer-nothing"),n=Symbol.for("immer-draftable"),o=Symbol.for("immer-state"),a="production"!==process.env.NODE_ENV?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function s(e,...t){if("production"!==process.env.NODE_ENV){const r=a[e],n="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var i=Object.getPrototypeOf;function c(e){return!!e&&!!e[o]}function u(e){return!!e&&(l(e)||Array.isArray(e)||!!e[n]||!!e.constructor?.[n]||h(e)||b(e))}var f=Object.prototype.constructor.toString();function l(e){if(!e||"object"!=typeof e)return!1;const t=i(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===f}function p(e,t){0===d(e)?Reflect.ownKeys(e).forEach((r=>{t(r,e[r],e)})):e.forEach(((r,n)=>t(n,r,e)))}function d(e){const t=e[o];return t?t.type_:Array.isArray(e)?1:h(e)?2:b(e)?3:0}function _(e,t){return 2===d(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function y(e,t,r){const n=d(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function h(e){return e instanceof Map}function b(e){return e instanceof Set}function m(e){return e.copy_||e.base_}function S(e,t){if(h(e))return new Map(e);if(b(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=l(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[o];let r=Reflect.ownKeys(t);for(let n=0;n<r.length;n++){const o=r[n],a=t[o];!1===a.writable&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(t[o]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[o]})}return Object.create(i(e),t)}{const t=i(e);if(null!==t&&r)return{...e};const n=Object.create(t);return Object.assign(n,e)}}function g(e,t=!1){return w(e)||c(e)||!u(e)||(d(e)>1&&(e.set=e.add=e.clear=e.delete=v),Object.freeze(e),t&&Object.entries(e).forEach((([e,t])=>g(t,!0)))),e}function v(){s(2)}function w(e){return Object.isFrozen(e)}var O,E={};function P(e){const t=E[e];return t||s(0,e),t}function j(){return O}function D(e,t){t&&(P("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function A(e){T(e),e.drafts_.forEach(z),e.drafts_=null}function T(e){e===O&&(O=e.parent_)}function N(e){return O=function(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}(O,e)}function z(e){const t=e[o];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function L(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return void 0!==e&&e!==n?(n[o].modified_&&(A(t),s(4)),u(e)&&(e=x(t,e),t.parent_||F(t,e)),t.patches_&&P("Patches").generateReplacementPatches_(n[o].base_,e,t.patches_,t.inversePatches_)):e=x(t,n,[]),A(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==r?e:void 0}function x(e,t,r){if(w(t))return t;const n=t[o];if(!n)return p(t,((o,a)=>$(e,n,t,o,a,r))),t;if(n.scope_!==e)return t;if(!n.modified_)return F(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let o=t,a=!1;3===n.type_&&(o=new Set(t),t.clear(),a=!0),p(o,((o,s)=>$(e,n,t,o,s,r,a))),F(e,t,!1),r&&e.patches_&&P("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function $(e,t,r,n,o,a,i){if("production"!==process.env.NODE_ENV&&o===r&&s(5),c(o)){const s=x(e,o,a&&t&&3!==t.type_&&!_(t.assigned_,n)?a.concat(n):void 0);if(y(r,n,s),!c(s))return;e.canAutoFreeze_=!1}else i&&r.add(o);if(u(o)&&!w(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;x(e,o),(!t||!t.scope_.parent_)&&"symbol"!=typeof n&&Object.prototype.propertyIsEnumerable.call(r,n)&&F(e,o)}}function F(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&g(t,r)}var I={get(e,t){if(t===o)return e;const r=m(e);if(!_(r,t))return function(e,t,r){const n=M(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,r,t);const n=r[t];return e.finalized_||!u(n)?n:n===R(e.base_,t)?(k(e),e.copy_[t]=K(n,e)):n},has:(e,t)=>t in m(e),ownKeys:e=>Reflect.ownKeys(m(e)),set(e,t,r){const n=M(m(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=R(m(e),t),a=n?.[o];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(r,n)&&(void 0!==r||_(e.base_,t)))return!0;k(e),V(e)}return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==R(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,k(e),V(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=m(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}},defineProperty(){s(11)},getPrototypeOf:e=>i(e.base_),setPrototypeOf(){s(12)}},C={};function R(e,t){const r=e[o];return(r?m(r):e)[t]}function M(e,t){if(!(t in e))return;let r=i(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=i(r)}}function V(e){e.modified_||(e.modified_=!0,e.parent_&&V(e.parent_))}function k(e){e.copy_||(e.copy_=S(e.base_,e.scope_.immer_.useStrictShallowCopy_))}p(I,((e,t)=>{C[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),C.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&s(13),C.set.call(this,e,t,void 0)},C.set=function(e,t,r){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&s(14),I.set.call(this,e[0],t,r,e[0])};function K(e,t){const r=h(e)?P("MapSet").proxyMap_(e,t):b(e)?P("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:j(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=n,a=I;r&&(o=[n],a=C);const{revoke:s,proxy:i}=Proxy.revocable(o,a);return n.draft_=i,n.revoke_=s,i}(e,t);return(t?t.scope_:j()).drafts_.push(r),r}function G(e){if(!u(e)||w(e))return e;const t=e[o];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=S(e,t.scope_.immer_.useStrictShallowCopy_)}else r=S(e,!0);return p(r,((e,t)=>{y(r,e,G(t))})),t&&(t.finalized_=!1),r}var U=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const n=this;return function(e=r,...o){return n.produce(e,(e=>t.call(this,e,...o)))}}let o;if("function"!=typeof t&&s(6),void 0!==n&&"function"!=typeof n&&s(7),u(e)){const r=N(this),a=K(e,void 0);let s=!0;try{o=t(a),s=!1}finally{s?A(r):T(r)}return D(r,n),L(o,r)}if(!e||"object"!=typeof e){if(o=t(e),void 0===o&&(o=e),o===r&&(o=void 0),this.autoFreeze_&&g(o,!0),n){const t=[],r=[];P("Patches").generateReplacementPatches_(e,o,t,r),n(t,r)}return o}s(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,(t=>e(t,...r)));let r,n;return[this.produce(e,t,((e,t)=>{r=e,n=t})),r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){u(e)||s(8),c(e)&&(e=function(e){return c(e)||s(10,e),G(e)}(e));const t=N(this),r=K(e,void 0);return r[o].isManual_=!0,T(t),r}finishDraft(e,t){const r=e&&e[o];(!r||!r.isManual_)&&s(9);const{scope_:n}=r;return D(n,t),L(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=P("Patches").applyPatches_;return c(e)?n(e,t):this.produce(e,(e=>n(e,t)))}},B=U.produce;U.produceWithPatches.bind(U),U.setAutoFreeze.bind(U),U.setUseStrictShallowCopy.bind(U),U.applyPatches.bind(U),U.createDraft.bind(U),U.finishDraft.bind(U);const H=(()=>{if("object"==typeof globalThis&&globalThis)return globalThis;if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;if(typeof global<"u"&&"object"==typeof global&&global)return global;throw new Error("Unable to locate global `this`")})(),J=(e,t)=>{typeof H?.localStorage<"u"&&H.localStorage.setItem(e,JSON.stringify(t))},W=(e,t)=>{if(typeof H?.localStorage<"u"){const r=H.localStorage?.getItem(e);return r?JSON.parse(r):t}return t},q=(e,t)=>{typeof H?.localStorage<"u"&&H.localStorage.setItem(e,(e=>btoa(JSON.stringify(e)))(t))},X=(e,t)=>{if(typeof H?.localStorage<"u"){const r=H.localStorage?.getItem(e);return r?(e=>JSON.parse(atob(e)))(r):t}return t};var Y,Q={exports:{}},Z={};
/**
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ee,te,re={};
/**
* @license React
* use-sync-external-store-shim.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ne=(te||(te=1,"production"===process.env.NODE_ENV?Q.exports=function(){if(Y)return Z;Y=1;var t=e,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=t.useState,o=t.useEffect,a=t.useLayoutEffect,s=t.useDebugValue;function i(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}var c=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?function(e,t){return t()}:function(e,t){var r=t(),c=n({inst:{value:r,getSnapshot:t}}),u=c[0].inst,f=c[1];return a((function(){u.value=r,u.getSnapshot=t,i(u)&&f({inst:u})}),[e,r,t]),o((function(){return i(u)&&f({inst:u}),e((function(){i(u)&&f({inst:u})}))}),[e]),s(r),r};return Z.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:c,Z}():Q.exports=(ee||(ee=1,"production"!==process.env.NODE_ENV&&function(){function t(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!n(e,r)}catch{return!0}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=e,n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},o=r.useState,a=r.useEffect,s=r.useLayoutEffect,i=r.useDebugValue,c=!1,u=!1,f=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?function(e,t){return t()}:function(e,f){c||void 0===r.startTransition||(c=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var l=f();if(!u){var p=f();n(l,p)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),u=!0)}var d=(p=o({inst:{value:l,getSnapshot:f}}))[0].inst,_=p[1];return s((function(){d.value=l,d.getSnapshot=f,t(d)&&_({inst:d})}),[e,l,f]),a((function(){return t(d)&&_({inst:d}),e((function(){t(d)&&_({inst:d})}))}),[e]),i(l),l};re.useSyncExternalStore=void 0!==r.useSyncExternalStore?r.useSyncExternalStore:f,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),re)),Q.exports);const oe={},ae={},se={},ie=H.__STATE_JET_DEVTOOLS__,ce=(e,t)=>{oe[e]||(oe[e]=[]),void 0===ae[e]&&(ae[e]=-1),oe[e]=oe[e].slice(0,ae[e]+1),oe[e].push(t),ae[e]++,ie?.updateState&&ie.updateState(e,t,[...oe[e]])},ue=(e,t)=>{se[e]||(se[e]=[]);const r=performance.now();t();const n=performance.now()-r;se[e].push(n),ie?.updatePerformance&&ie.updatePerformance(e,n)},fe=new Set,le=new Map,pe=new Map,de={};let _e=!1;const ye=(e,t,r)=>he("global")(e,t,r),he=e=>(le.has(e)||le.set(e,{}),(t,r,n)=>{const o=le.get(e),a=`${e}:${t}`;if(!o[t]){let e=r;n?.persist&&(e=n?.encrypt?X(a,r):W(a,r)),o[t]={value:e,listeners:new Set,...n}}const s=o[t],i=async()=>{_e=!1;const e=Array.from(pe.entries());pe.clear();for(const[t,r]of e){const[e,n]=t.split(":"),o=le.get(e);if(!o)continue;const a=o[n];if(!a)continue;if(fe.has(t)){console.warn(`[state-jet] Skipping recursive middleware for: ${t}`);continue}let s=r;const i=a.value;if(de[t]||(de[t]={past:[],present:i,future:[]}),de[t].past.push(i),de[t].present=s,de[t].future=[],fe.add(t),a?.middleware)for(const e of a.middleware)try{console.log(`[state-jet] Running middleware for ${t}`);const r=e(t,i,s,(e=>{s=e}));if(void 0!==r)if(r instanceof Promise){const e=await r;void 0!==e&&(s=e)}else s=r}catch(e){console.error(`[state-jet] Middleware error in ${t}:`,e)}fe.delete(t),"function"==typeof s?a.value=B(a.value,s):i!==s&&(a.value=s,a.listeners.forEach((e=>e())),ce(`${e}.${n}`,s),ue(`${e}.${n}`,(()=>{})),a?.persist&&(a?.encrypt?q(t,s):J(t,s)))}};return{useState:()=>ne.useSyncExternalStore((e=>(s.listeners.add(e),()=>s.listeners.delete(e))),(()=>s.value)),set:async(r,n=!1)=>{const o=s.value,c="function"==typeof r?r(o):r;if(n)return s.value=c,s.listeners.forEach((e=>e())),void ce(`${e}.${t}`,c);pe.set(a,c),_e||(_e=!0,s.frameSync&&H?.requestAnimationFrame?await new Promise((e=>H.requestAnimationFrame((()=>e(i()))))):await i())},get:()=>s.value,undo:()=>{de[a]?.past.length&&(de[a].future.unshift(de[a].present),de[a].present=de[a].past.pop(),s.value=de[a].present,s.listeners.forEach((e=>e())),(e=>{if(ae[e]>0)ae[e]--,oe[e][ae[e]]})(a),ce(`${e}.undo`,de[a].present))},redo:()=>{de[a]?.future.length&&(de[a].past.push(de[a].present),de[a].present=de[a].future.shift(),s.value=de[a].present,s.listeners.forEach((e=>e())),(e=>{if(ae[e]<oe[e]?.length-1)ae[e]++,oe[e][ae[e]]})(a),ce(`${e}.redo`,de[a].present))},clear:()=>{s.value=r,le.clear(),Object.keys(de).forEach((e=>delete de[e])),ce(`${e}.clear`,r)}}}),be=e=>{const r=t(null);return r.current||(r.current=e()),r.current},me=async(e,t,r,n)=>{const o=e.useState(),a=t(o);e.set(a);try{await r()}catch(t){console.error("API request failed:",t),e.set(n?n(o):o)}},Se=(e,t)=>({...e,...t,lastUpdated:Date.now()}),ge=(e,t)=>{const r=t.useState(),n=Se(r,e);t.set(n)},ve=(e,t)=>()=>{const r=e.map((e=>e.useState()));return t(...r)};export{ve as derivedState,Se as mergeCRDT,me as optimisticUpdate,X as restoreEncryptedState,W as restoreState,q as saveEncryptedState,J as saveState,ge as syncCRDT,he as useSlice,ye as useStateGlobal,be as useStore};