state-decorator 7.0.0-beta.0 → 7.0.0-beta.10-dev

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.
Files changed (65) hide show
  1. package/README.md +384 -192
  2. package/es/helpers.d.ts +66 -0
  3. package/es/helpers.js +163 -0
  4. package/{dist/v5_test.js.map → es/helpers.js.map} +1 -1
  5. package/es/impl.d.ts +19 -5
  6. package/es/impl.js +963 -1
  7. package/es/impl.js.map +1 -1
  8. package/es/index.d.ts +34 -36
  9. package/es/index.js +1013 -1
  10. package/es/index.js.map +1 -1
  11. package/es/middlewares.js +519 -1
  12. package/es/middlewares.js.map +1 -1
  13. package/es/test.d.ts +6 -4
  14. package/es/test.js +349 -1
  15. package/es/test.js.map +1 -1
  16. package/es/types.d.ts +32 -3
  17. package/es/v5.js +301 -1
  18. package/es/v5.js.map +1 -1
  19. package/es/v5_test.js +392 -1
  20. package/es/v5_test.js.map +1 -1
  21. package/es/v6.d.ts +18 -0
  22. package/es/v6.js +98 -0
  23. package/es/v6.js.map +1 -0
  24. package/helpers.d.ts +66 -0
  25. package/helpers.js +175 -0
  26. package/{dist/test.js.map → helpers.js.map} +1 -1
  27. package/impl.d.ts +19 -5
  28. package/impl.js +996 -1
  29. package/impl.js.map +1 -1
  30. package/index.d.ts +34 -36
  31. package/index.js +1044 -1
  32. package/index.js.map +1 -1
  33. package/middlewares.js +526 -1
  34. package/middlewares.js.map +1 -1
  35. package/package.json +5 -4
  36. package/test.d.ts +6 -4
  37. package/test.js +358 -1
  38. package/test.js.map +1 -1
  39. package/types.d.ts +32 -3
  40. package/v5.js +322 -1
  41. package/v5.js.map +1 -1
  42. package/v5_test.js +416 -1
  43. package/v5_test.js.map +1 -1
  44. package/v6.d.ts +18 -0
  45. package/v6.js +123 -0
  46. package/v6.js.map +1 -0
  47. package/dist/impl.d.ts +0 -195
  48. package/dist/impl.js +0 -2
  49. package/dist/impl.js.map +0 -1
  50. package/dist/index.d.ts +0 -168
  51. package/dist/index.js +0 -2
  52. package/dist/index.js.map +0 -1
  53. package/dist/middlewares.d.ts +0 -26
  54. package/dist/middlewares.js +0 -2
  55. package/dist/middlewares.js.map +0 -1
  56. package/dist/shallow.d.ts +0 -15
  57. package/dist/test.d.ts +0 -134
  58. package/dist/test.js +0 -2
  59. package/dist/types.d.ts +0 -352
  60. package/dist/v5.d.ts +0 -58
  61. package/dist/v5.js +0 -2
  62. package/dist/v5.js.map +0 -1
  63. package/dist/v5_test.d.ts +0 -70
  64. package/dist/v5_test.js +0 -2
  65. package/dist/v5_types.d.ts +0 -227
package/index.js CHANGED
@@ -1,2 +1,1045 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var r,e=require("react"),n=require("./impl"),t=function(){return(t=Object.assign||function(r){for(var e,n=1,t=arguments.length;n<t;n++)for(var u in e=arguments[n])Object.prototype.hasOwnProperty.call(e,u)&&(r[u]=e[u]);return r}).apply(this,arguments)};function u(r,e,n){if(n||2===arguments.length)for(var t,u=0,o=e.length;u<o;u++)!t&&u in e||(t||(t=Array.prototype.slice.call(e,0,u)),t[u]=e[u]);return r.concat(t||Array.prototype.slice.call(e))}function o(r,e,o,c){void 0===o&&(o={}),void 0===c&&(c=null);var i=n.createRef(),l=n.createRef(),a=n.createRef(),f=n.createRef(),s=n.createRef(),d=n.createRef(),p=n.createRef(),v=n.createRef(),g=n.createRef(),y=n.createRef(!1),R=n.createRef([]),b={},A=0;function E(r,e){var n=t(t({},r),e),u=t(t(t({},n),f.current),{isLoading:P,abortAction:m,loading:h(),loadingMap:x(),errorMap:j()});Object.keys(b).forEach((function(r){b[r](u)}))}function M(r){i.current=r,n.computeDerivedValues(i,a,l,o),E(i.current,l.current.state)}function S(t){var u;if(!y.current){a.current=t,y.current=!0,i.current=r(t);var b=new Set(null==o?void 0:o.initialActionsMarkedLoading);d.current=Object.keys(e).reduce((function(r,e){var t;return r[e]=b.has(e)?((t={})[n.DEFAULT_PROMISE_ID]=!0,t):{},r}),{}),p.current=Object.keys(e).reduce((function(r,e){return r[e]={},r}),{}),s.current={},v.current={},g.current={},l.current={state:null,deps:{}},R.current=[];var A={options:o,get state(){return i.current},actions:e,setState:M},S=function(r){var e,n=r();R.current.push(n),null===(e=n.init)||void 0===e||e.call(n,A)};null===(u=n.globalConfig.defaultMiddlewares)||void 0===u||u.forEach(S),null==c||c.forEach(S),n.computeDerivedValues(i,a,l,o),n.onPropChange(i,l,a,null,f,o,L,!0),(null==o?void 0:o.onMount)&&o.onMount(n.buildOnMountInvocationContext(i,l,a,f)),E(i.current,l.current.state)}}function L(r,e,t,u,c,f,s,p){void 0===s&&(s=!1),void 0===p&&(p=!1);var v=!1;if(y.current){var g=e,b=!!c&&n.isLoadingImpl(g||d.current,[t,null==f?void 0:f.promiseId]),A=n.runMiddlewares(R.current,i.current,r,b,t,u,c,f),M=A.newState,S=A.newLoading;if(null!=M&&(v=!0,i.current=M),b!==S&&(g=n.buildLoadingMap(g,t,(null==f?void 0:f.promiseId)||n.DEFAULT_PROMISE_ID,S),0===Object.keys(g).length&&(g=void 0)),null!=g&&(v=!0,d.current=g),v)n.computeDerivedValues(i,a,l,o),p||E(M||i.current,l.current.state);else if(s){n.computeDerivedValues(i,a,l,o)&&!p&&E(M||i.current,l.current.state)}}}var O=Object.keys(e);function P(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return n.isLoadingImpl.apply(void 0,u([d.current],r,!1))}function m(r,e){var t,u;void 0===e&&(e=n.DEFAULT_PROMISE_ID);var o=null===(u=null===(t=v.current[r])||void 0===t?void 0:t[e])||void 0===u?void 0:u.abortController,c=!1;return o&&(o.abort(),c=!0),c}function h(){if(y.current){var r=d.current;return null!=Object.keys(r).find((function(e){var n=r[e];return Object.keys(n).find((function(r){return!!n[r]}))}))}return null}function x(){if(y.current){var r=d.current;return Object.keys(r).reduce((function(e,n){var t=r[n];return e[n]=null!=Object.keys(t).find((function(r){return!!t[r]})),e}),{})}return null}function j(){return y.current?n.buildErrorMap(p.current):null}return f.current=O.reduce((function(r,t){var u=e[t];return n.isSimpleSyncAction(u)?r[t]=n.decorateSimpleSyncAction(t,u,i,l,a,y,L):n.isAsyncAction(u)?r[t]=n.decorateAsyncAction({actionName:t,stateRef:i,derivedStateRef:l,propsRef:a,loadingMapRef:d,errorMapRef:p,actionsRef:f,promisesRef:v,conflictActionsRef:g,initializedRef:y,options:o,setState:L,action:n.computeAsyncActionInput(u)}):n.isSyncAction(u)&&(r[t]=n.decorateSyncAction(t,u,i,l,a,f,y,s,o,L)),r}),{}),{getConfig:function(){return{getInitialState:r,options:o,actions:e}},setProps:function(r){var e=a.current;a.current=r,y.current?n.onPropChange(i,l,a,e,f,o,L,!1):S(r)},addStateListener:function(r){var e="".concat(A++);return b[e]=r,function(){delete b[e]}},init:S,destroy:function(){var r;y.current&&(null===(r=null==o?void 0:o.onUnmount)||void 0===r||r.call(o,n.buildOnMountInvocationContext(i,l,a,f)),a.current=null,i.current=null,d.current=null,p.current=null,v.current=null,g.current=null,l.current=null,Object.keys(s.current).forEach((function(r){clearTimeout(s.current[r])})),s.current=null,b={},y.current=!1,R.current.forEach((function(r){var e;null===(e=r.destroy)||void 0===e||e.call(r)})),R.current=[])},isLoading:P,abortAction:m,get actions(){return f.current},get state(){return y.current?t(t({},i.current),l.current.state):null},get loading(){return h()},get loadingMap(){return x()},get errorMap(){return j()},get loadingParallelMap(){return y.current?d.current:null},get errorParallelMap(){return y.current?p.current:null}}}function c(r,u,o){var c=e.useReducer((function(r){return r>100?0:r+1}),0)[1],i=e.useMemo((function(){return u instanceof Function?u:function(r){return a(r,u)}}),[u]),l=e.useMemo((function(){return function(r){return null!=o&&o.length>0?a(r.loadingMap,o):null}}),[o]),f=e.useRef(null),s=e.useRef(null);if(null===f.current){var d=t(t(t({},r.state),r.actions),a(r,["actions","loading","isLoading","abortAction","loadingMap","errorMap"]));f.current=i(d),s.current=l(d)}e.useLayoutEffect((function(){return r.addStateListener((function(r){var e,t=i(r),u=l(r),o=f.current,a=n.globalConfig.comparator;e=null==o||!a(t,o)||!a(u,s.current),f.current=t,s.current=u,e&&c()}))}),[]);var p=f.current,v=s.current;return null==v?p:t(t({},p),{loadingMap:v})}function i(r,n,t){void 0===n&&(n=null),void 0===t&&(t=!0);var u=e.useReducer((function(r){return r>100?0:r+1}),0)[1],o=e.useRef(r);return r.setProps(n),e.useLayoutEffect((function(){t&&o.current.addStateListener((function(){u()}))}),[t]),r}function l(r,n,t,u,c,l){void 0===l&&(l=!0);var a=e.useRef();return null==a.current&&(a.current=o(r,n,u,c)),e.useEffect((function(){return function(){var r;null===(r=a.current)||void 0===r||r.destroy()}}),[]),i(a.current,t,l)}function a(r,e){return e.reduce((function(e,n){return r.hasOwnProperty(n)&&(e[n]=r[n]),e}),{})}exports.ConflictPolicy=void 0,(r=exports.ConflictPolicy||(exports.ConflictPolicy={})).REJECT="reject",r.IGNORE="ignore",r.KEEP_LAST="keepLast",r.KEEP_ALL="keepAll",r.PARALLEL="parallel",r.REUSE="reuse",Object.defineProperty(exports,"ParallelActionError",{enumerable:!0,get:function(){return n.ParallelActionError}}),Object.defineProperty(exports,"setGlobalConfig",{enumerable:!0,get:function(){return n.setGlobalConfig}}),exports.createStore=o,exports.default=l,exports.pick=a,exports.slice=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return function(e){return a(e,r)}},exports.useLocalStore=l,exports.useStore=i,exports.useStoreContextSlice=function(r,n,t){return c(e.useContext(r),n,t)},exports.useStoreSlice=c;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var e = require('react');
6
+ var impl = require('./impl');
7
+
8
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
+
10
+ var e__default = /*#__PURE__*/_interopDefaultLegacy(e);
11
+
12
+ /*! *****************************************************************************
13
+ Copyright (c) Microsoft Corporation.
14
+
15
+ Permission to use, copy, modify, and/or distribute this software for any
16
+ purpose with or without fee is hereby granted.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
19
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
20
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
22
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
23
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
24
+ PERFORMANCE OF THIS SOFTWARE.
25
+ ***************************************************************************** */
26
+
27
+ var __assign = function() {
28
+ __assign = Object.assign || function __assign(t) {
29
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
30
+ s = arguments[i];
31
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
32
+ }
33
+ return t;
34
+ };
35
+ return __assign.apply(this, arguments);
36
+ };
37
+
38
+ function __rest(s, e) {
39
+ var t = {};
40
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
41
+ t[p] = s[p];
42
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
43
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
44
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
45
+ t[p[i]] = s[p[i]];
46
+ }
47
+ return t;
48
+ }
49
+
50
+ function __spreadArray(to, from, pack) {
51
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
52
+ if (ar || !(i in from)) {
53
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
54
+ ar[i] = from[i];
55
+ }
56
+ }
57
+ return to.concat(ar || Array.prototype.slice.call(from));
58
+ }
59
+
60
+ function createCommonjsModule(fn) {
61
+ var module = { exports: {} };
62
+ return fn(module, module.exports), module.exports;
63
+ }
64
+
65
+ /**
66
+ * @license React
67
+ * use-sync-external-store-shim.production.min.js
68
+ *
69
+ * Copyright (c) Facebook, Inc. and its affiliates.
70
+ *
71
+ * This source code is licensed under the MIT license found in the
72
+ * LICENSE file in the root directory of this source tree.
73
+ */
74
+ function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k="function"===typeof Object.is?Object.is:h,l=e__default['default'].useState,m=e__default['default'].useEffect,n=e__default['default'].useLayoutEffect,p$1=e__default['default'].useDebugValue;function q$1(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r$1(c)&&g({inst:c});},[a,d,b]);m(function(){r$1(c)&&g({inst:c});return a(function(){r$1(c)&&g({inst:c});})},[a]);p$1(d);return d}
75
+ function r$1(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k(a,d)}catch(f){return !0}}function t$1(a,b){return b()}var u$1="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t$1:q$1;var useSyncExternalStore=void 0!==e__default['default'].useSyncExternalStore?e__default['default'].useSyncExternalStore:u$1;
76
+
77
+ var useSyncExternalStoreShim_production_min = {
78
+ useSyncExternalStore: useSyncExternalStore
79
+ };
80
+
81
+ /**
82
+ * @license React
83
+ * use-sync-external-store-shim.development.js
84
+ *
85
+ * Copyright (c) Facebook, Inc. and its affiliates.
86
+ *
87
+ * This source code is licensed under the MIT license found in the
88
+ * LICENSE file in the root directory of this source tree.
89
+ */
90
+
91
+ var useSyncExternalStoreShim_development = createCommonjsModule(function (module, exports) {
92
+
93
+ if (process.env.NODE_ENV !== "production") {
94
+ (function() {
95
+
96
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
97
+ if (
98
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
99
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
100
+ 'function'
101
+ ) {
102
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
103
+ }
104
+ var React = e__default['default'];
105
+
106
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
107
+
108
+ function error(format) {
109
+ {
110
+ {
111
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
112
+ args[_key2 - 1] = arguments[_key2];
113
+ }
114
+
115
+ printWarning('error', format, args);
116
+ }
117
+ }
118
+ }
119
+
120
+ function printWarning(level, format, args) {
121
+ // When changing this logic, you might want to also
122
+ // update consoleWithStackDev.www.js as well.
123
+ {
124
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
125
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
126
+
127
+ if (stack !== '') {
128
+ format += '%s';
129
+ args = args.concat([stack]);
130
+ } // eslint-disable-next-line react-internal/safe-string-coercion
131
+
132
+
133
+ var argsWithFormat = args.map(function (item) {
134
+ return String(item);
135
+ }); // Careful: RN currently depends on this prefix
136
+
137
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
138
+ // breaks IE9: https://github.com/facebook/react/issues/13610
139
+ // eslint-disable-next-line react-internal/no-production-logging
140
+
141
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
142
+ }
143
+ }
144
+
145
+ /**
146
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
147
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
148
+ */
149
+ function is(x, y) {
150
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
151
+ ;
152
+ }
153
+
154
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
155
+
156
+ // dispatch for CommonJS interop named imports.
157
+
158
+ var useState = React.useState,
159
+ useEffect = React.useEffect,
160
+ useLayoutEffect = React.useLayoutEffect,
161
+ useDebugValue = React.useDebugValue;
162
+ var didWarnOld18Alpha = false;
163
+ var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
164
+ // because of a very particular set of implementation details and assumptions
165
+ // -- change any one of them and it will break. The most important assumption
166
+ // is that updates are always synchronous, because concurrent rendering is
167
+ // only available in versions of React that also have a built-in
168
+ // useSyncExternalStore API. And we only use this shim when the built-in API
169
+ // does not exist.
170
+ //
171
+ // Do not assume that the clever hacks used by this hook also work in general.
172
+ // The point of this shim is to replace the need for hacks by other libraries.
173
+
174
+ function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
175
+ // React do not expose a way to check if we're hydrating. So users of the shim
176
+ // will need to track that themselves and return the correct value
177
+ // from `getSnapshot`.
178
+ getServerSnapshot) {
179
+ {
180
+ if (!didWarnOld18Alpha) {
181
+ if (React.startTransition !== undefined) {
182
+ didWarnOld18Alpha = true;
183
+
184
+ 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.');
185
+ }
186
+ }
187
+ } // Read the current snapshot from the store on every render. Again, this
188
+ // breaks the rules of React, and only works here because of specific
189
+ // implementation details, most importantly that updates are
190
+ // always synchronous.
191
+
192
+
193
+ var value = getSnapshot();
194
+
195
+ {
196
+ if (!didWarnUncachedGetSnapshot) {
197
+ var cachedValue = getSnapshot();
198
+
199
+ if (!objectIs(value, cachedValue)) {
200
+ error('The result of getSnapshot should be cached to avoid an infinite loop');
201
+
202
+ didWarnUncachedGetSnapshot = true;
203
+ }
204
+ }
205
+ } // Because updates are synchronous, we don't queue them. Instead we force a
206
+ // re-render whenever the subscribed state changes by updating an some
207
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
208
+ // the current value.
209
+ //
210
+ // Because we don't actually use the state returned by the useState hook, we
211
+ // can save a bit of memory by storing other stuff in that slot.
212
+ //
213
+ // To implement the early bailout, we need to track some things on a mutable
214
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
215
+ // our useState hook instead.
216
+ //
217
+ // To force a re-render, we call forceUpdate({inst}). That works because the
218
+ // new object always fails an equality check.
219
+
220
+
221
+ var _useState = useState({
222
+ inst: {
223
+ value: value,
224
+ getSnapshot: getSnapshot
225
+ }
226
+ }),
227
+ inst = _useState[0].inst,
228
+ forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
229
+ // in the layout phase so we can access it during the tearing check that
230
+ // happens on subscribe.
231
+
232
+
233
+ useLayoutEffect(function () {
234
+ inst.value = value;
235
+ inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
236
+ // commit phase if there was an interleaved mutation. In concurrent mode
237
+ // this can happen all the time, but even in synchronous mode, an earlier
238
+ // effect may have mutated the store.
239
+
240
+ if (checkIfSnapshotChanged(inst)) {
241
+ // Force a re-render.
242
+ forceUpdate({
243
+ inst: inst
244
+ });
245
+ }
246
+ }, [subscribe, value, getSnapshot]);
247
+ useEffect(function () {
248
+ // Check for changes right before subscribing. Subsequent changes will be
249
+ // detected in the subscription handler.
250
+ if (checkIfSnapshotChanged(inst)) {
251
+ // Force a re-render.
252
+ forceUpdate({
253
+ inst: inst
254
+ });
255
+ }
256
+
257
+ var handleStoreChange = function () {
258
+ // TODO: Because there is no cross-renderer API for batching updates, it's
259
+ // up to the consumer of this library to wrap their subscription event
260
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
261
+ // the case and print a warning in development?
262
+ // The store changed. Check if the snapshot changed since the last time we
263
+ // read from the store.
264
+ if (checkIfSnapshotChanged(inst)) {
265
+ // Force a re-render.
266
+ forceUpdate({
267
+ inst: inst
268
+ });
269
+ }
270
+ }; // Subscribe to the store and return a clean-up function.
271
+
272
+
273
+ return subscribe(handleStoreChange);
274
+ }, [subscribe]);
275
+ useDebugValue(value);
276
+ return value;
277
+ }
278
+
279
+ function checkIfSnapshotChanged(inst) {
280
+ var latestGetSnapshot = inst.getSnapshot;
281
+ var prevValue = inst.value;
282
+
283
+ try {
284
+ var nextValue = latestGetSnapshot();
285
+ return !objectIs(prevValue, nextValue);
286
+ } catch (error) {
287
+ return true;
288
+ }
289
+ }
290
+
291
+ function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
292
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
293
+ // React do not expose a way to check if we're hydrating. So users of the shim
294
+ // will need to track that themselves and return the correct value
295
+ // from `getSnapshot`.
296
+ return getSnapshot();
297
+ }
298
+
299
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
300
+
301
+ var isServerEnvironment = !canUseDOM;
302
+
303
+ var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
304
+ var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
305
+
306
+ exports.useSyncExternalStore = useSyncExternalStore$2;
307
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
308
+ if (
309
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
310
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
311
+ 'function'
312
+ ) {
313
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
314
+ }
315
+
316
+ })();
317
+ }
318
+ });
319
+
320
+ var shim = createCommonjsModule(function (module) {
321
+
322
+ if (process.env.NODE_ENV === 'production') {
323
+ module.exports = useSyncExternalStoreShim_production_min;
324
+ } else {
325
+ module.exports = useSyncExternalStoreShim_development;
326
+ }
327
+ });
328
+
329
+ /**
330
+ * @license React
331
+ * use-sync-external-store-shim/with-selector.production.min.js
332
+ *
333
+ * Copyright (c) Facebook, Inc. and its affiliates.
334
+ *
335
+ * This source code is licensed under the MIT license found in the
336
+ * LICENSE file in the root directory of this source tree.
337
+ */
338
+ function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q="function"===typeof Object.is?Object.is:p,r=shim.useSyncExternalStore,t=e__default['default'].useRef,u=e__default['default'].useEffect,v=e__default['default'].useMemo,w=e__default['default'].useDebugValue;
339
+ var useSyncExternalStoreWithSelector$1=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f;}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return [function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);
340
+ u(function(){f.hasValue=!0;f.value=d;},[d]);w(d);return d};
341
+
342
+ var withSelector_production_min = {
343
+ useSyncExternalStoreWithSelector: useSyncExternalStoreWithSelector$1
344
+ };
345
+
346
+ /**
347
+ * @license React
348
+ * use-sync-external-store-shim/with-selector.development.js
349
+ *
350
+ * Copyright (c) Facebook, Inc. and its affiliates.
351
+ *
352
+ * This source code is licensed under the MIT license found in the
353
+ * LICENSE file in the root directory of this source tree.
354
+ */
355
+
356
+ var withSelector_development = createCommonjsModule(function (module, exports) {
357
+
358
+ if (process.env.NODE_ENV !== "production") {
359
+ (function() {
360
+
361
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
362
+ if (
363
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
364
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
365
+ 'function'
366
+ ) {
367
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
368
+ }
369
+ var React = e__default['default'];
370
+ var shim$1 = shim;
371
+
372
+ /**
373
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
374
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
375
+ */
376
+ function is(x, y) {
377
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
378
+ ;
379
+ }
380
+
381
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
382
+
383
+ var useSyncExternalStore = shim$1.useSyncExternalStore;
384
+
385
+ // for CommonJS interop.
386
+
387
+ var useRef = React.useRef,
388
+ useEffect = React.useEffect,
389
+ useMemo = React.useMemo,
390
+ useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.
391
+
392
+ function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
393
+ // Use this to track the rendered snapshot.
394
+ var instRef = useRef(null);
395
+ var inst;
396
+
397
+ if (instRef.current === null) {
398
+ inst = {
399
+ hasValue: false,
400
+ value: null
401
+ };
402
+ instRef.current = inst;
403
+ } else {
404
+ inst = instRef.current;
405
+ }
406
+
407
+ var _useMemo = useMemo(function () {
408
+ // Track the memoized state using closure variables that are local to this
409
+ // memoized instance of a getSnapshot function. Intentionally not using a
410
+ // useRef hook, because that state would be shared across all concurrent
411
+ // copies of the hook/component.
412
+ var hasMemo = false;
413
+ var memoizedSnapshot;
414
+ var memoizedSelection;
415
+
416
+ var memoizedSelector = function (nextSnapshot) {
417
+ if (!hasMemo) {
418
+ // The first time the hook is called, there is no memoized result.
419
+ hasMemo = true;
420
+ memoizedSnapshot = nextSnapshot;
421
+
422
+ var _nextSelection = selector(nextSnapshot);
423
+
424
+ if (isEqual !== undefined) {
425
+ // Even if the selector has changed, the currently rendered selection
426
+ // may be equal to the new selection. We should attempt to reuse the
427
+ // current value if possible, to preserve downstream memoizations.
428
+ if (inst.hasValue) {
429
+ var currentSelection = inst.value;
430
+
431
+ if (isEqual(currentSelection, _nextSelection)) {
432
+ memoizedSelection = currentSelection;
433
+ return currentSelection;
434
+ }
435
+ }
436
+ }
437
+
438
+ memoizedSelection = _nextSelection;
439
+ return _nextSelection;
440
+ } // We may be able to reuse the previous invocation's result.
441
+
442
+
443
+ // We may be able to reuse the previous invocation's result.
444
+ var prevSnapshot = memoizedSnapshot;
445
+ var prevSelection = memoizedSelection;
446
+
447
+ if (objectIs(prevSnapshot, nextSnapshot)) {
448
+ // The snapshot is the same as last time. Reuse the previous selection.
449
+ return prevSelection;
450
+ } // The snapshot has changed, so we need to compute a new selection.
451
+
452
+
453
+ // The snapshot has changed, so we need to compute a new selection.
454
+ var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data
455
+ // has changed. If it hasn't, return the previous selection. That signals
456
+ // to React that the selections are conceptually equal, and we can bail
457
+ // out of rendering.
458
+
459
+ // If a custom isEqual function is provided, use that to check if the data
460
+ // has changed. If it hasn't, return the previous selection. That signals
461
+ // to React that the selections are conceptually equal, and we can bail
462
+ // out of rendering.
463
+ if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {
464
+ return prevSelection;
465
+ }
466
+
467
+ memoizedSnapshot = nextSnapshot;
468
+ memoizedSelection = nextSelection;
469
+ return nextSelection;
470
+ }; // Assigning this to a constant so that Flow knows it can't change.
471
+
472
+
473
+ // Assigning this to a constant so that Flow knows it can't change.
474
+ var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
475
+
476
+ var getSnapshotWithSelector = function () {
477
+ return memoizedSelector(getSnapshot());
478
+ };
479
+
480
+ var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {
481
+ return memoizedSelector(maybeGetServerSnapshot());
482
+ };
483
+ return [getSnapshotWithSelector, getServerSnapshotWithSelector];
484
+ }, [getSnapshot, getServerSnapshot, selector, isEqual]),
485
+ getSelection = _useMemo[0],
486
+ getServerSelection = _useMemo[1];
487
+
488
+ var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
489
+ useEffect(function () {
490
+ inst.hasValue = true;
491
+ inst.value = value;
492
+ }, [value]);
493
+ useDebugValue(value);
494
+ return value;
495
+ }
496
+
497
+ exports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;
498
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
499
+ if (
500
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
501
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
502
+ 'function'
503
+ ) {
504
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
505
+ }
506
+
507
+ })();
508
+ }
509
+ });
510
+
511
+ var withSelector = createCommonjsModule(function (module) {
512
+
513
+ if (process.env.NODE_ENV === 'production') {
514
+ module.exports = withSelector_production_min;
515
+ } else {
516
+ module.exports = withSelector_development;
517
+ }
518
+ });
519
+
520
+ /*! *****************************************************************************
521
+ Copyright (c) GlobalSport SAS.
522
+
523
+ Permission to use, copy, modify, and/or distribute this software for any
524
+ purpose with or without fee is hereby granted.
525
+
526
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
527
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
528
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
529
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
530
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
531
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
532
+ PERFORMANCE OF THIS SOFTWARE.
533
+ ***************************************************************************** */
534
+ /**
535
+ * The State decorator can manage only one asynchronous action of same name at a time.
536
+ * This enum is enumertaing all the policies in such case.
537
+ */
538
+ exports.ConflictPolicy = void 0;
539
+ (function (ConflictPolicy) {
540
+ /**
541
+ * Reject the promise.
542
+ */
543
+ ConflictPolicy["REJECT"] = "reject";
544
+ /**
545
+ * Return a resolved promise with no result.
546
+ */
547
+ ConflictPolicy["IGNORE"] = "ignore";
548
+ /**
549
+ * Execute only the last call that conflicts after the one ongoing.
550
+ */
551
+ ConflictPolicy["KEEP_LAST"] = "keepLast";
552
+ /**
553
+ * Execute all calls one after another.
554
+ */
555
+ ConflictPolicy["KEEP_ALL"] = "keepAll";
556
+ /**
557
+ * Execute all calls one after another.
558
+ * @see getPromiseId
559
+ */
560
+ ConflictPolicy["PARALLEL"] = "parallel";
561
+ /**
562
+ * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!
563
+ */
564
+ ConflictPolicy["REUSE"] = "reuse";
565
+ })(exports.ConflictPolicy || (exports.ConflictPolicy = {}));
566
+
567
+ var useSyncExternalStoreWithSelector = withSelector.useSyncExternalStoreWithSelector;
568
+ // =============================
569
+ //
570
+ // STORE
571
+ //
572
+ // =============================
573
+ /**
574
+ * Create a new store.
575
+ * @param config Store configuration
576
+ * @returns a store.
577
+ */
578
+ function createStore(config) {
579
+ var stateRef = impl.createRef();
580
+ var derivedStateRef = impl.createRef();
581
+ var propsRef = impl.createRef();
582
+ var actionsRef = impl.createRef();
583
+ var timeoutRef = impl.createRef();
584
+ var loadingParallelMapRef = impl.createRef();
585
+ var loadingMapRef = impl.createRef();
586
+ var loadingRef = impl.createRef();
587
+ var errorMapRef = impl.createRef();
588
+ var promisesRef = impl.createRef();
589
+ var conflictActionsRef = impl.createRef();
590
+ var initializedRef = impl.createRef(false);
591
+ var snapshotRef = impl.createRef();
592
+ var middlewaresRef = impl.createRef([]);
593
+ var getInitialState = config.getInitialState, actionsImpl = config.actions, _a = config.middlewares, middlewares = _a === void 0 ? [] : _a, options = __rest(config, ["getInitialState", "actions", "middlewares"]);
594
+ var stateListeners = {};
595
+ var stateListenerCount = 0;
596
+ function addStateListener(listener) {
597
+ var id = "".concat(stateListenerCount++);
598
+ stateListeners[id] = listener;
599
+ return function () {
600
+ delete stateListeners[id];
601
+ };
602
+ }
603
+ function notifyStateListeners() {
604
+ updateSnapshot();
605
+ Object.keys(stateListeners).forEach(function (listenerId) {
606
+ stateListeners[listenerId]();
607
+ });
608
+ }
609
+ function setProps(p) {
610
+ var oldProps = propsRef.current;
611
+ propsRef.current = p;
612
+ if (!initializedRef.current) {
613
+ init(p);
614
+ }
615
+ else {
616
+ impl.onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, getInitialState, setState, false, false);
617
+ }
618
+ }
619
+ /** Middleware only: sets the internal state, recompute derived state and notify listeners */
620
+ function setInternalState(s) {
621
+ stateRef.current = s;
622
+ impl.computeDerivedValues(stateRef, propsRef, derivedStateRef, options);
623
+ notifyStateListeners();
624
+ }
625
+ function setInternalLoadingMap(map) {
626
+ loadingParallelMapRef.current = map;
627
+ loadingMapRef.current = getLoadingMap();
628
+ loadingRef.current = isAnyLoading();
629
+ }
630
+ function init(p) {
631
+ var _a;
632
+ if (!initializedRef.current) {
633
+ propsRef.current = p;
634
+ initializedRef.current = true;
635
+ stateRef.current = typeof getInitialState === 'function' ? getInitialState(p) : getInitialState;
636
+ var initialActionSet_1 = new Set(options === null || options === void 0 ? void 0 : options.initialActionsMarkedLoading);
637
+ var loadingMap = Object.keys(actionsImpl).reduce(function (acc, name) {
638
+ var _a;
639
+ acc[name] = initialActionSet_1.has(name) ? (_a = {}, _a[impl.DEFAULT_PROMISE_ID] = true, _a) : {};
640
+ return acc;
641
+ }, {});
642
+ setInternalLoadingMap(loadingMap);
643
+ errorMapRef.current = Object.keys(actionsImpl).reduce(function (acc, name) {
644
+ acc[name] = {};
645
+ return acc;
646
+ }, {});
647
+ timeoutRef.current = {};
648
+ promisesRef.current = {};
649
+ conflictActionsRef.current = {};
650
+ derivedStateRef.current = {
651
+ state: null,
652
+ deps: {},
653
+ };
654
+ // init middlewares
655
+ middlewaresRef.current = [];
656
+ var ctx_1 = {
657
+ options: options,
658
+ get state() {
659
+ return stateRef.current;
660
+ },
661
+ actions: actionsImpl,
662
+ setState: setInternalState,
663
+ };
664
+ var mapper = function (m) {
665
+ var _a;
666
+ var middleware = m();
667
+ middlewaresRef.current.push(middleware);
668
+ (_a = middleware.init) === null || _a === void 0 ? void 0 : _a.call(middleware, ctx_1);
669
+ };
670
+ (_a = impl.globalConfig.defaultMiddlewares) === null || _a === void 0 ? void 0 : _a.forEach(mapper);
671
+ middlewares === null || middlewares === void 0 ? void 0 : middlewares.forEach(mapper);
672
+ // end init
673
+ impl.computeDerivedValues(stateRef, propsRef, derivedStateRef, options);
674
+ // manage PropsChange with onMount
675
+ impl.onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, getInitialState, setState, true, false);
676
+ if (options === null || options === void 0 ? void 0 : options.onMount) {
677
+ options.onMount(impl.buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));
678
+ }
679
+ notifyStateListeners();
680
+ }
681
+ }
682
+ function clearError(actionName, promiseId) {
683
+ if (promiseId === void 0) { promiseId = impl.DEFAULT_PROMISE_ID; }
684
+ var map = errorMapRef.current[actionName];
685
+ if (map === null || map === void 0 ? void 0 : map[promiseId]) {
686
+ delete map[promiseId];
687
+ }
688
+ notifyStateListeners();
689
+ }
690
+ function invokeOnMountDeferred() {
691
+ // manage PropsChange with onMount
692
+ impl.onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, getInitialState, setState, true, true);
693
+ if (options === null || options === void 0 ? void 0 : options.onMountDeferred) {
694
+ options.onMountDeferred(impl.buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));
695
+ }
696
+ }
697
+ function abortActionsOnDestroy() {
698
+ var abortedActions = Object.keys(actionsImpl).reduce(function (acc, actionName) {
699
+ var action = actionsImpl[actionName];
700
+ if (impl.isAsyncAction(action) && action.abortable) {
701
+ var map_1 = loadingParallelMapRef.current[actionName];
702
+ var aborted = Object.keys(map_1).reduce(function (acc, promiseId) {
703
+ if (map_1[promiseId]) {
704
+ // ongoing action
705
+ abortAction(actionName, promiseId);
706
+ acc.push(promiseId);
707
+ }
708
+ return acc;
709
+ }, []);
710
+ if (aborted.length > 0) {
711
+ acc[actionName] = aborted;
712
+ }
713
+ }
714
+ return acc;
715
+ }, {});
716
+ return abortedActions;
717
+ }
718
+ function destroy() {
719
+ var _a;
720
+ if (initializedRef.current) {
721
+ var abortedActions = abortActionsOnDestroy();
722
+ (_a = options === null || options === void 0 ? void 0 : options.onUnmount) === null || _a === void 0 ? void 0 : _a.call(options, impl.buildOnUnMountInvocationContext(stateRef, derivedStateRef, propsRef, abortedActions));
723
+ propsRef.current = null;
724
+ stateRef.current = null;
725
+ loadingParallelMapRef.current = null;
726
+ loadingMapRef.current = null;
727
+ loadingRef.current = null;
728
+ errorMapRef.current = null;
729
+ promisesRef.current = null;
730
+ conflictActionsRef.current = null;
731
+ derivedStateRef.current = null;
732
+ snapshotRef.current = null;
733
+ Object.keys(timeoutRef.current).forEach(function (name) {
734
+ clearTimeout(timeoutRef.current[name]);
735
+ });
736
+ timeoutRef.current = null;
737
+ stateListeners = {};
738
+ initializedRef.current = false;
739
+ middlewaresRef.current.forEach(function (m) {
740
+ var _a;
741
+ (_a = m.destroy) === null || _a === void 0 ? void 0 : _a.call(m);
742
+ });
743
+ middlewaresRef.current = [];
744
+ }
745
+ }
746
+ function setState(newStateIn, newLoadingMapIn, actionName, actionType, isAsync, actionCtx, propsChanged, init) {
747
+ if (propsChanged === void 0) { propsChanged = false; }
748
+ if (init === void 0) { init = false; }
749
+ var hasChanged = false;
750
+ if (!initializedRef.current) {
751
+ return;
752
+ }
753
+ var newLoadingMap = newLoadingMapIn;
754
+ var oldLoading = isAsync
755
+ ? impl.isLoadingImpl(newLoadingMap || loadingParallelMapRef.current, [actionName, actionCtx === null || actionCtx === void 0 ? void 0 : actionCtx.promiseId])
756
+ : false;
757
+ var _a = impl.runMiddlewares(middlewaresRef.current, stateRef.current, newStateIn, oldLoading, actionName, actionType, isAsync, actionCtx), newState = _a.newState, newLoading = _a.newLoading;
758
+ if (newState != null) {
759
+ hasChanged = true;
760
+ stateRef.current = newState;
761
+ }
762
+ if (oldLoading !== newLoading) {
763
+ newLoadingMap = impl.buildLoadingMap(newLoadingMap, actionName, (actionCtx === null || actionCtx === void 0 ? void 0 : actionCtx.promiseId) || impl.DEFAULT_PROMISE_ID, newLoading);
764
+ if (Object.keys(newLoadingMap).length === 0) {
765
+ newLoadingMap = undefined;
766
+ }
767
+ }
768
+ if (newLoadingMap != null) {
769
+ hasChanged = true;
770
+ setInternalLoadingMap(newLoadingMap);
771
+ }
772
+ if (hasChanged) {
773
+ impl.computeDerivedValues(stateRef, propsRef, derivedStateRef, options);
774
+ if (!init) {
775
+ stateRef.current = newState || stateRef.current;
776
+ notifyStateListeners();
777
+ }
778
+ }
779
+ else if (propsChanged) {
780
+ var derivedChanged = impl.computeDerivedValues(stateRef, propsRef, derivedStateRef, options);
781
+ if (derivedChanged && !init) {
782
+ notifyStateListeners();
783
+ }
784
+ }
785
+ }
786
+ var keys = Object.keys(actionsImpl);
787
+ actionsRef.current = keys.reduce(function (acc, actionName) {
788
+ var action = actionsImpl[actionName];
789
+ if (impl.isSimpleSyncAction(action)) {
790
+ acc[actionName] = impl.decorateSimpleSyncAction(actionName, action, stateRef, derivedStateRef, propsRef, initializedRef, setState);
791
+ }
792
+ else if (impl.isAsyncAction(action)) {
793
+ acc[actionName] = impl.decorateAsyncAction({
794
+ actionName: actionName,
795
+ stateRef: stateRef,
796
+ derivedStateRef: derivedStateRef,
797
+ propsRef: propsRef,
798
+ loadingParallelMapRef: loadingParallelMapRef,
799
+ errorMapRef: errorMapRef,
800
+ actionsRef: actionsRef,
801
+ promisesRef: promisesRef,
802
+ conflictActionsRef: conflictActionsRef,
803
+ initializedRef: initializedRef,
804
+ options: options,
805
+ setState: setState,
806
+ clearError: clearError,
807
+ action: impl.computeAsyncActionInput(action),
808
+ });
809
+ }
810
+ else if (impl.isSyncAction(action)) {
811
+ acc[actionName] = impl.decorateSyncAction(actionName, action, stateRef, derivedStateRef, propsRef, actionsRef, initializedRef, timeoutRef, options, setState, clearError);
812
+ }
813
+ return acc;
814
+ }, {});
815
+ function isLoading() {
816
+ var props = [];
817
+ for (var _i = 0; _i < arguments.length; _i++) {
818
+ props[_i] = arguments[_i];
819
+ }
820
+ return impl.isLoadingImpl.apply(void 0, __spreadArray([loadingParallelMapRef.current], props, false));
821
+ }
822
+ function abortAction(actionName, promiseId) {
823
+ var _a, _b;
824
+ if (promiseId === void 0) { promiseId = impl.DEFAULT_PROMISE_ID; }
825
+ var abortController = (_b = (_a = promisesRef.current[actionName]) === null || _a === void 0 ? void 0 : _a[promiseId]) === null || _b === void 0 ? void 0 : _b.abortController;
826
+ var res = false;
827
+ if (abortController) {
828
+ abortController.abort();
829
+ res = true;
830
+ }
831
+ return res;
832
+ }
833
+ function isAnyLoading() {
834
+ if (initializedRef.current) {
835
+ var loadingMap_1 = loadingParallelMapRef.current;
836
+ return (Object.keys(loadingMap_1).find(function (actionName) {
837
+ var promises = loadingMap_1[actionName];
838
+ return Object.keys(promises).find(function (pId) { return !!promises[pId]; });
839
+ }) != null);
840
+ }
841
+ return null;
842
+ }
843
+ function getLoadingMap() {
844
+ if (initializedRef.current) {
845
+ var map_2 = loadingParallelMapRef.current;
846
+ var keys_1 = Object.keys(map_2);
847
+ return keys_1.reduce(function (acc, actionName) {
848
+ var subMap = map_2[actionName];
849
+ acc[actionName] = Object.keys(subMap).find(function (pId) { return !!subMap[pId]; }) != null;
850
+ return acc;
851
+ }, {});
852
+ }
853
+ return null;
854
+ }
855
+ function getErrorMap() {
856
+ if (initializedRef.current) {
857
+ return impl.buildErrorMap(errorMapRef.current);
858
+ }
859
+ return null;
860
+ }
861
+ function getConfig() {
862
+ return __assign({}, config);
863
+ }
864
+ function updateSnapshot() {
865
+ snapshotRef.current = __assign(__assign(__assign(__assign({}, actionsRef.current), stateRef.current), derivedStateRef.current.state), { isLoading: isLoading, abortAction: abortAction, loading: loadingRef.current, loadingMap: loadingMapRef.current, loadingParallelMap: loadingParallelMapRef.current, errorMap: getErrorMap(), errorParallelMap: errorMapRef.current });
866
+ }
867
+ function getSnapshot() {
868
+ return snapshotRef.current;
869
+ }
870
+ return {
871
+ getConfig: getConfig,
872
+ setProps: setProps,
873
+ addStateListener: addStateListener,
874
+ init: init,
875
+ destroy: destroy,
876
+ isLoading: isLoading,
877
+ abortAction: abortAction,
878
+ clearError: clearError,
879
+ getSnapshot: getSnapshot,
880
+ invokeOnMountDeferred: invokeOnMountDeferred,
881
+ get actions() {
882
+ return actionsRef.current;
883
+ },
884
+ get state() {
885
+ if (initializedRef.current) {
886
+ return __assign(__assign({}, stateRef.current), derivedStateRef.current.state);
887
+ }
888
+ return null;
889
+ },
890
+ get loading() {
891
+ return loadingRef.current;
892
+ },
893
+ get loadingMap() {
894
+ return loadingMapRef.current;
895
+ },
896
+ get errorMap() {
897
+ return getErrorMap();
898
+ },
899
+ get loadingParallelMap() {
900
+ if (initializedRef.current) {
901
+ return loadingParallelMapRef.current;
902
+ }
903
+ return null;
904
+ },
905
+ get errorParallelMap() {
906
+ if (initializedRef.current) {
907
+ return errorMapRef.current;
908
+ }
909
+ return null;
910
+ },
911
+ };
912
+ }
913
+ function useStoreSlice(store, funcOrArr) {
914
+ var slicerFunc = e.useMemo(function () { return (funcOrArr instanceof Function ? funcOrArr : function (ctx) { return pick(ctx, funcOrArr); }); }, [funcOrArr]);
915
+ return useSyncExternalStoreWithSelector(store.addStateListener, store.getSnapshot, store.getSnapshot, slicerFunc, impl.globalConfig.comparator);
916
+ }
917
+ function useStoreContextSlice(storeContext, funcOrArr) {
918
+ var store = e.useContext(storeContext);
919
+ return useStoreSlice(store, funcOrArr);
920
+ }
921
+ /**
922
+ * Binds the store to this component.
923
+ * Store will NOT be destroyed when component is unmouted.
924
+ * Props passed to actions will come from this components.
925
+ * If store is configured to react of props changes, it will used passed props.
926
+ * The component will be refreshed for every change in the store.
927
+ *
928
+ * @param store The store to listen to.
929
+ * @param props The parent component props
930
+ * @param refreshOnUpdate Whether refresh the component if store state changes.
931
+ * @returns The store.
932
+ */
933
+ function useStore(store, props, refreshOnUpdate) {
934
+ if (props === void 0) { props = null; }
935
+ if (refreshOnUpdate === void 0) { refreshOnUpdate = true; }
936
+ var _a = e.useReducer(function (s) { return (s > 100 ? 0 : s + 1); }, 0), forceRefresh = _a[1];
937
+ var storeRef = e.useRef(store);
938
+ store.setProps(props);
939
+ e.useLayoutEffect(function () {
940
+ // In development mode, React is calling in order:
941
+ // - render
942
+ // - useLayoutEffect
943
+ // - useEffect
944
+ // - useLayoutEffect => delete callback
945
+ // - useEffect => delete callback
946
+ // - useLayoutEffect
947
+ // - useEffect
948
+ //
949
+ // Here we enforce a initialization of the store after a destroy in the useEffect delete callback
950
+ store.init(props);
951
+ }, []);
952
+ e.useLayoutEffect(function () {
953
+ if (refreshOnUpdate) {
954
+ return storeRef.current.addStateListener(function () {
955
+ forceRefresh();
956
+ });
957
+ }
958
+ return undefined;
959
+ }, [refreshOnUpdate]);
960
+ return store;
961
+ }
962
+ /**
963
+ * Creates and manages a local store.
964
+ * The component will be refreshed for every change in the store.
965
+ * Store will NOT be destroyed when component is unmouted.
966
+ *
967
+ * @param getInitialState Function to compute initial state from props.
968
+ * @param actionImpl Actions implementation.
969
+ * @param props Owner component props to update state or react on prop changes
970
+ * @param options The store options.
971
+ * @param refreshOnUpdate Whether refresh the component if store state changes.
972
+ * @returns The state, actions and isLoading function.
973
+ */
974
+ function useLocalStore(config, props, refreshOnUpdate) {
975
+ if (refreshOnUpdate === void 0) { refreshOnUpdate = true; }
976
+ var storeRef = e.useRef();
977
+ if (storeRef.current == null) {
978
+ storeRef.current = createStore(config);
979
+ }
980
+ e.useEffect(function () {
981
+ storeRef.current.invokeOnMountDeferred();
982
+ return function () {
983
+ var _a;
984
+ (_a = storeRef.current) === null || _a === void 0 ? void 0 : _a.destroy();
985
+ };
986
+ }, []);
987
+ return useStore(storeRef.current, props, refreshOnUpdate);
988
+ }
989
+ // ------------- UTILS
990
+ /**
991
+ * Creates a new object by picking properties to the object passed a first parameter
992
+ * @param obj Object to pick properties from
993
+ * @param props Property names
994
+ * @returns a new object containing only picked properties
995
+ */
996
+ function pick(obj, props) {
997
+ return props.reduce(function (acc, p) {
998
+ if (obj.hasOwnProperty(p)) {
999
+ acc[p] = obj[p];
1000
+ }
1001
+ return acc;
1002
+ }, {});
1003
+ }
1004
+ /**
1005
+ * Returns a function that creates a new object by picking properties to the object passed as first parameter.
1006
+ * To be used in conjunction of <code>useStoreSlice</code> like in example:
1007
+ * const s = useStoreSlice(myStore, slice('list', 'addItem'));
1008
+ * @param props Property names
1009
+ * @returns a function to pick property from an passed object.
1010
+ */
1011
+ function slice() {
1012
+ var props = [];
1013
+ for (var _i = 0; _i < arguments.length; _i++) {
1014
+ props[_i] = arguments[_i];
1015
+ }
1016
+ return function (store) { return pick(store, props); };
1017
+ }
1018
+
1019
+ Object.defineProperty(exports, 'EffectError', {
1020
+ enumerable: true,
1021
+ get: function () {
1022
+ return impl.EffectError;
1023
+ }
1024
+ });
1025
+ Object.defineProperty(exports, 'ParallelActionError', {
1026
+ enumerable: true,
1027
+ get: function () {
1028
+ return impl.ParallelActionError;
1029
+ }
1030
+ });
1031
+ Object.defineProperty(exports, 'setGlobalConfig', {
1032
+ enumerable: true,
1033
+ get: function () {
1034
+ return impl.setGlobalConfig;
1035
+ }
1036
+ });
1037
+ exports.createStore = createStore;
1038
+ exports.default = useLocalStore;
1039
+ exports.pick = pick;
1040
+ exports.slice = slice;
1041
+ exports.useLocalStore = useLocalStore;
1042
+ exports.useStore = useStore;
1043
+ exports.useStoreContextSlice = useStoreContextSlice;
1044
+ exports.useStoreSlice = useStoreSlice;
2
1045
  //# sourceMappingURL=index.js.map