state-decorator 6.7.1 → 6.9.0
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/README.md +93 -9
- package/impl.d.ts +7 -1
- package/impl.es.js +1 -1
- package/impl.es.js.map +1 -1
- package/impl.js +1 -1
- package/impl.js.map +1 -1
- package/index.d.ts +16 -4
- package/index.es.js +1 -1
- package/index.es.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/middlewares.es.js +1 -1
- package/middlewares.es.js.map +1 -1
- package/middlewares.js +1 -1
- package/middlewares.js.map +1 -1
- package/package.json +1 -1
- package/test.d.ts +2 -1
- package/test.es.js +1 -1
- package/test.es.js.map +1 -1
- package/test.js +1 -1
- package/test.js.map +1 -1
- package/types.d.ts +15 -0
- package/v5.es.js +1 -1
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/types.ts","../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/nonIterableRest.js","../node_modules/@babel/runtime/helpers/slicedToArray.js","../node_modules/@babel/runtime/helpers/defineProperty.js","../src/index.ts"],"sourcesContent":["/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nexport type PromiseResult<Type> = Type extends Promise<infer X> ? X : null;\n\nexport type NotifyFunc = (msg: string) => void;\n\nexport type PromiseIdMap = { [promiseId: string]: boolean };\n\nexport type LoadingMap<A> = { [pId in keyof A]?: boolean };\nexport type LoadingParallelMap<A> = { [P in keyof A]?: PromiseIdMap };\nexport type InternalLoadingMap<A> = LoadingParallelMap<A>;\n\nexport type LoadingProps<A> = {\n loading: boolean;\n loadingMap: LoadingMap<A>;\n loadingParallelMap: LoadingParallelMap<A>;\n};\n\n// https://github.com/Microsoft/TypeScript/issues/15300\nexport interface DecoratedActions {\n [name: string]: (...args: any[]) => Promise<any> | void;\n}\n\n/**\n * The State decorator can manage only one asynchronous action of same name at a time.\n * This enum is enumertaing all the policies in such case.\n */\nexport enum ConflictPolicy {\n /**\n * Reject the promise.\n */\n REJECT = 'reject',\n\n /**\n * Return a resolved promise with no result.\n */\n IGNORE = 'ignore',\n\n /**\n * Execute only the last call that conflicts after the one ongoing.\n */\n KEEP_LAST = 'keepLast',\n\n /**\n * Execute all calls one after another.\n */\n KEEP_ALL = 'keepAll',\n\n /**\n * Execute all calls one after another.\n * @see getPromiseId\n */\n PARALLEL = 'parallel',\n\n /**\n * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!\n */\n REUSE = 'reuse',\n}\n\nexport type PromiseProvider<S, DS, F extends (...args: any[]) => any, A, P> = (\n ctx: GetPromiseInvocationContext<S, DS, F, P, A>\n) => ReturnType<F> | null;\n\n/**\n * Simple form of a synchronous action.\n */\nexport type SimpleSyncAction<S, F extends (...args: any[]) => any, P, DS, FxRes = S> = (\n ctx: InvocationContext<S, DS, F, P>\n) => FxRes | null;\n\nexport type SyncAction<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * Function that update the state when the action is called.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Debounces the action if this parameter is defined.\n */\n debounceTimeout?: number;\n\n /**\n * Debounces the action side effects if this parameter is defined.\n */\n debounceSideEffectsTimeout?: number;\n\n /**\n * Function that calls side effects, ie. effects that are not changing the state directly.\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n};\n\n/**\n * Try to abort an action, if the action is <code>abortable</code>.\n * @param actionName The action name\n * @param promiseId If the action conflict type is <code>ConflictType.PARALLEL</code>, the identifier of the promise.\n * @returns <code>true</code> if the action is abortable and an action is ongoing, <code>false</code> otherwise.\n */\nexport type AbortActionCallback<A> = (actionName: keyof A, promiseId?: string) => boolean;\n\nexport type GetErrorMessage<S, DS, F extends (...args: any[]) => any, P> = (\n ctx: ErrorMessageInvocationContext<S, DS, F, P>\n) => string;\n\nexport type ContextState<S> = {\n state: S;\n s: S;\n};\n\nexport type ContextDerivedStateState<DS> = {\n derived: DS;\n ds: DS;\n};\n\nexport type ContextBase<S, P> = ContextState<S> & {\n props: P;\n p: P;\n};\n\nexport type ContextWithDerived<S, DS, P> = ContextBase<S, P> & ContextDerivedStateState<DS>;\n\nexport type InvocationContextActions<A> = {\n actions: A;\n a: A;\n};\n\nexport type WarningNotifyFunc = {\n notifyWarning?: NotifyFunc;\n};\n\nexport type InvocationContext<S, DS, F extends (...args: any[]) => any, P> = ContextWithDerived<S, DS, P> & {\n args: Parameters<F>;\n promiseId: string;\n};\n\nexport type EffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<S, DS, F, P> & {\n result: PromiseResult<ReturnType<F>>;\n res: PromiseResult<ReturnType<F>>;\n};\n\nexport type GetPromiseInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = InvocationContextActions<A> &\n InvocationContext<S, DS, F, P> & {\n abortSignal: AbortSignal;\n };\n\nexport type ErrorEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<\n S,\n DS,\n F,\n P\n> & {\n error: Error;\n err: Error;\n};\n\nexport type SuccessMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\nexport type ErrorMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = ErrorEffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\n\nexport type SideEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n> &\n InvocationContextActions<A> &\n WarningNotifyFunc;\n\nexport type ErrorSideEffectsInvocationContext<\n S,\n DS,\n F extends (...args: any[]) => any,\n P,\n A\n> = ErrorEffectsInvocationContext<S, DS, F, P> & InvocationContextActions<A> & WarningNotifyFunc;\n\nexport type OnMountInvocationContext<S, A, P> = ContextBase<S, P> & InvocationContextActions<A>;\n\nexport type EffectsType = 'preEffects' | 'effects' | 'errorEffects' | 'optimisticEffects' | null;\n\nexport type MiddlewareActionContext<S, A, P> = {\n name: keyof A;\n type: EffectsType;\n isAsync: boolean;\n context: InvocationContext<S, any, any, P>;\n};\n\nexport type MiddlewareStoreContext<S, A extends DecoratedActions, P> = {\n actions: StoreActions<S, A, P, any, any>;\n state: S;\n setState: (s: S) => void;\n options: StoreOptions<S, A, P, any>;\n};\n\nexport type MiddlewareFactory<S, A extends DecoratedActions, P> = () => Middleware<S, A, P>;\n\n/**\n * A state change middleware.\n * Allow to listen and change a state change on the fly.\n */\nexport type Middleware<S, A extends DecoratedActions, P> = {\n /**\n * Initializes the middleware. Called when the store is initializing.\n */\n init: (storeContext: MiddlewareStoreContext<S, A, P>) => void;\n\n /**\n * Invoked on a state change has occurred and returns a new state or <code>null</code> if unchanged.\n */\n effects: (\n actionContext: MiddlewareActionContext<S, A, P>,\n oldState: S,\n newState: S,\n loading: boolean\n ) => null | {\n state: S;\n loading: boolean;\n };\n\n /**\n * Destroys the middleware. Called when the store is being destroyed.\n */\n destroy: () => void;\n};\n\nexport type AsyncActionBase<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * This action can be aborted. An abortSignal will be injected to the <code>promise</code> / <code>promiseGet</code>.\n */\n abortable?: boolean;\n\n /**\n * A function that provides the success message to pass to the notifySuccess function passed as property to the StateDecorator.\n */\n getSuccessMessage?: (ctx: SuccessMessageInvocationContext<S, DS, F, P>) => string;\n\n /**\n * A function that provides the error message to pass to the notifyError function passed as property to the StateDecorator.\n */\n getErrorMessage?: GetErrorMessage<S, DS, F, P>;\n\n /**\n * If set, called with the result of the promise to update the current state.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * If set, called with the error of the promise to update the current state.\n */\n errorEffects?: (ctx: ErrorEffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Whether reject the promise instead of handling it.\n */\n rejectPromiseOnError?: boolean;\n\n /**\n * Handle side effects when the request succeeded.\n * @param result The result of the request\n * @param newData The data after the reducer is applied\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi success (use successMessage / getSuccessMessage otherwise).\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Handle side effects when the request failed.\n * @param error The error of the request\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi failure (use errorMessage / getErrorMessage otherwise).\n */\n errorSideEffects?: (ctx: ErrorSideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n preEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n optimisticEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Policy to apply when a call to an asynchronous action is done but a previous call is still not resolved.\n */\n conflictPolicy?: ConflictPolicy;\n\n /**\n * Get an identifier for an action call. Used only when conflictPolicy is ConflictPolicy.PARALLEL.\n * This information will be available in loadingMap. loadingMap[actionName] will be an array of promise identifiers.\n */\n getPromiseId?: (...args: Parameters<F>) => string;\n\n /**\n * Number of retries in case of error (failed to fetch).\n * Do not use this if you are creating objects...\n * Default value is 0 (no retry).\n */\n retryCount?: number;\n\n /**\n * Seed of delay between each retry in milliseconds.\n * The applied delay is retryDelaySeed * retry count.\n * Default value is 1000 (1 second).\n */\n retryDelaySeed?: number;\n\n /**\n * Function to test if the error will trigger an action retry or will fail directly.\n */\n isTriggerRetryError?: (e: Error) => boolean;\n};\n\nexport type AsyncActionPromise<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise\n */\n getPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncActionPromiseGet<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise that is a GET request.\n * A shortcut to set:\n * - retryCount: 3\n * - conflictPolicy: ConflictPolicy.REUSE\n */\n getGetPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncActionPromise<S, F, A, P, DS, FxRes>\n | AsyncActionPromiseGet<S, F, A, P, DS, FxRes>;\n\nexport type StoreAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncAction<S, F, A, P, DS, FxRes>\n | SimpleSyncAction<S, F, P, DS, FxRes>\n | SyncAction<S, F, A, P, DS, FxRes>;\n\n/**\n * S: The type of the state\n * A: The type of the actions to pass to the children (used to check keys only).\n */\nexport type StoreActions<S, A extends DecoratedActions, P = {}, DS = {}, FxRes = S> = {\n [Prop in keyof A]: StoreAction<S, A[Prop], A, P, DS, FxRes>;\n};\n\nexport type OnPropsChangeEffectsContext<S, DS, P> = ContextWithDerived<S, DS, P> & {\n indices: number[];\n index: number;\n isInit: boolean;\n};\n\nexport type OnPropsChangeSideEffectsContext<S, P, A, DS = {}> = OnPropsChangeEffectsContext<S, DS, P> & {\n actions: A;\n a: A;\n};\n\ntype DerivedStateOption<S, P, DS> = {\n [k in keyof DS]: {\n getDeps: (ctx: ContextBase<S, P>) => any[];\n get: (ctx: ContextBase<S, P>) => DS[k];\n };\n};\n\nexport type OnPropsChangeOptions<S, DS, A, P> = {\n onMount?: boolean;\n getDeps: (p: P) => any[];\n effects?: (ctx: OnPropsChangeEffectsContext<S, DS, P>) => S;\n sideEffects?: (ctx: OnPropsChangeSideEffectsContext<S, P, A>) => void;\n};\n\nexport type StoreOptions<S, A, P = {}, DS = {}> = {\n /**\n * The state decorator name. Use in debug traces to identify the useStateDecorator instance.\n */\n name?: string;\n\n /**\n * List of action names that are marked as loading at initial time.\n * If you must start your initial actions in a useSideEffect, a render is done before\n * first actions can be trigerred, some actions can be marked as loading at initial time.\n */\n initialActionsMarkedLoading?: (keyof A)[];\n\n /**\n * One or several configurations of inbound properties change managements.\n */\n onPropsChange?: OnPropsChangeOptions<S, DS, A, P> | OnPropsChangeOptions<S, DS, A, P>[];\n\n /**\n * The callback function called if an asynchronous function succeeded and a success messsage is defined.\n */\n notifySuccess?: NotifyFunc;\n\n /**\n * The callback function called if an asynchronous function fails and an error messsage is defined.\n */\n notifyError?: NotifyFunc;\n\n /**\n * The callback function injected in onDone and onFail of asynchronous functions to notify a semi success / failed request.\n */\n notifyWarning?: NotifyFunc;\n\n /**\n * Initial actions.\n */\n onMount?: (ctx: OnMountInvocationContext<S, A, P>) => void;\n\n /**\n * Callback on store destruction.\n */\n onUnmount?: (ctx: OnMountInvocationContext<S, A, P>) => Promise<any> | void;\n\n /**\n * Compute derived state\n */\n derivedState?: DerivedStateOption<S, P, DS>;\n};\n","function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport { useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';\nimport {\n computeAsyncActionInput,\n createRef,\n isSyncAction,\n isAsyncAction,\n isSimpleSyncAction,\n TimeoutMap,\n PromiseMap,\n DEFAULT_PROMISE_ID,\n globalConfig,\n setGlobalConfig,\n GlobalConfig,\n ConflictActionsMap,\n buildOnMountInvocationContext,\n decorateSimpleSyncAction,\n decorateSyncAction,\n decorateAsyncAction,\n computeDerivedValues,\n DerivedState,\n onPropChange,\n runMiddlewares,\n buildLoadingMap,\n isLoadingImpl,\n} from './impl';\n\nimport {\n DecoratedActions,\n StoreActions,\n AsyncAction,\n SyncAction,\n SimpleSyncAction,\n InternalLoadingMap,\n LoadingMap,\n LoadingParallelMap,\n StoreOptions,\n AsyncActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n ContextState,\n ConflictPolicy,\n Middleware,\n AbortActionCallback,\n MiddlewareFactory,\n MiddlewareStoreContext,\n LoadingProps,\n} from './types';\n\nexport {\n DecoratedActions,\n StoreActions,\n LoadingMap,\n StoreOptions,\n LoadingParallelMap,\n AsyncActionPromise as AsynchActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n SyncAction,\n AsyncAction,\n SimpleSyncAction,\n ContextState,\n ConflictPolicy,\n GlobalConfig,\n Middleware,\n setGlobalConfig,\n LoadingProps,\n AbortActionCallback,\n};\n\nexport type IsLoadingFunc<A> = (...props: (keyof A | [keyof A, string])[]) => boolean;\ntype StateListenerUnregister = () => void;\n\nexport type StoreApi<S, A extends DecoratedActions, P, DS = {}> = {\n /**\n * The current store state (with derived state if any).\n */\n readonly state: S & DS;\n /**\n * The store decorator (ie. ready to use) actions.\n */\n readonly actions: A;\n /**\n * A boolean that indicates that at least one asynchronous action is loading.\n */\n readonly loading: boolean;\n /**\n * A map of loading actions map (computed on property access)\n */\n readonly loadingMap: LoadingMap<A>;\n /**\n * A map of parallel loading actions map (computed on property access)\n */\n readonly loadingParallelMap: LoadingParallelMap<A>;\n /**\n * Initializes the store with the specified props\n */\n init: (p: P) => void;\n /**\n * Update the store with the specified props\n */\n setProps: (p: P) => void;\n /**\n * Destroy the store\n */\n destroy: () => void;\n /**\n * Abort an asynchronous action marked as abortable.\n */\n abortAction: (actionName: keyof A, promiseId?: string) => boolean;\n /**\n * Add a store state change listener\n */\n addStateListener: (listener: StateListener<S, DS, A>) => StateListenerUnregister;\n /**\n * A function that takes a list of action names or a tuple of [action name, promiseId] and returns <code>true</code> if any action is loading.\n */\n isLoading: IsLoadingFunc<A>;\n\n getConfig: () => {\n getInitialState: (p: P) => S;\n options: StoreOptions<S, A, P, DS>;\n actions: StoreActions<S, A, P, DS>;\n };\n};\n\nexport type StateListenerContext<S, DS, A extends DecoratedActions> = S &\n DS &\n A &\n Pick<StoreApi<S, A, any, DS>, 'loading' | 'loadingMap' | 'isLoading' | 'abortAction'>;\n\nexport type StateListener<S, DS, A extends DecoratedActions> = (ctx: StateListenerContext<S, DS, A>) => void;\n\n// =============================\n//\n// STORE\n//\n// =============================\n\n/**\n * Create a new store.\n * @param getInitialState The state initialization function (using props)\n * @param actionsImpl The actions implementation (pure functions only).\n * @param options Options to configure the store\n * @returns a store.\n */\nexport function createStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionsImpl: StoreActions<S, A, P, DS>,\n options: StoreOptions<S, A, P, DS> = {},\n storeMiddlewares: MiddlewareFactory<S, A, P>[] = null\n): StoreApi<S, A, P, DS> {\n const stateRef = createRef<S>();\n const derivedStateRef = createRef<DerivedState<DS>>();\n const propsRef = createRef<P>();\n const actionsRef = createRef<A>();\n const timeoutRef = createRef<TimeoutMap<A>>();\n const loadingMapRef = createRef<InternalLoadingMap<A>>();\n const promisesRef = createRef<PromiseMap<A>>();\n const conflictActionsRef = createRef<ConflictActionsMap<A>>();\n const initializedRef = createRef(false);\n\n const middlewaresRef = createRef<Middleware<S, A, P>[]>([]);\n\n let stateListeners: Record<string, StateListener<S, DS, A>> = {};\n let stateListenerCount = 0;\n\n function addStateListener(listener: StateListener<S, DS, A>): () => void {\n const id = `${stateListenerCount++}`;\n stateListeners[id] = listener;\n return () => {\n delete stateListeners[id];\n };\n }\n\n function notifyStateListeners(newState: S, derivedState: DS) {\n const s = {\n ...newState,\n ...derivedState,\n };\n\n const ctx: StateListenerContext<S, DS, A> = {\n ...s,\n ...actionsRef.current,\n isLoading,\n abortAction,\n loading: isAnyLoading(),\n loadingMap: getLoadingMap(),\n };\n\n Object.keys(stateListeners).forEach((listenerId) => {\n stateListeners[listenerId](ctx);\n });\n }\n\n function setProps(p: P) {\n const oldProps = propsRef.current;\n\n propsRef.current = p;\n\n if (!initializedRef.current) {\n init(p);\n } else {\n onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, setState, false);\n }\n }\n\n /** Middleware only: sets the internal state, recompute derived state and notify listeners */\n function setInternalState(s: S) {\n stateRef.current = s;\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n\n function init(p: P) {\n if (!initializedRef.current) {\n propsRef.current = p;\n initializedRef.current = true;\n stateRef.current = getInitialState(p);\n\n const initialActionSet = new Set(options?.initialActionsMarkedLoading);\n\n loadingMapRef.current = (Object.keys(actionsImpl) as (keyof A)[]).reduce<InternalLoadingMap<A>>((acc, name) => {\n acc[name] = initialActionSet.has(name) ? { [DEFAULT_PROMISE_ID]: true } : {};\n return acc;\n }, {});\n\n timeoutRef.current = {};\n promisesRef.current = {};\n conflictActionsRef.current = {};\n derivedStateRef.current = {\n state: null,\n deps: {},\n };\n\n // init middlewares\n middlewaresRef.current = [];\n const ctx: MiddlewareStoreContext<S, A, P> = {\n options,\n get state() {\n return stateRef.current;\n },\n actions: actionsImpl,\n setState: setInternalState,\n };\n const mapper = (m: MiddlewareFactory<S, A, P>) => {\n const middleware = m();\n middlewaresRef.current.push(middleware);\n middleware.init?.(ctx);\n };\n globalConfig.defaultMiddlewares?.forEach(mapper);\n storeMiddlewares?.forEach(mapper);\n // end init\n\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n\n // manage PropsChange with onMount\n onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, setState, true);\n\n if (options?.onMount) {\n options.onMount(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n }\n\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n }\n\n function destroy() {\n if (initializedRef.current) {\n options?.onUnmount?.(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n\n propsRef.current = null;\n stateRef.current = null;\n loadingMapRef.current = null;\n promisesRef.current = null;\n conflictActionsRef.current = null;\n derivedStateRef.current = null;\n\n Object.keys(timeoutRef.current).forEach((name) => {\n clearTimeout(timeoutRef.current[name]);\n });\n\n timeoutRef.current = null;\n stateListeners = {};\n initializedRef.current = false;\n\n middlewaresRef.current.forEach((m) => {\n m.destroy?.();\n });\n\n middlewaresRef.current = [];\n }\n }\n\n function setState(\n newStateIn: S,\n newLoadingMapIn: InternalLoadingMap<A>,\n actionName: keyof A,\n actionType: 'preEffects' | 'effects' | 'errorEffects' | null,\n isAsync: boolean,\n actionCtx: any,\n propsChanged: boolean = false,\n init = false\n ) {\n let hasChanged = false;\n\n if (!initializedRef.current) {\n return;\n }\n\n let newLoadingMap = newLoadingMapIn;\n\n const oldLoading = isAsync\n ? isLoadingImpl(newLoadingMap || loadingMapRef.current, [actionName, actionCtx?.promiseId])\n : false;\n\n const { newState, newLoading } = runMiddlewares(\n middlewaresRef.current,\n stateRef.current,\n newStateIn,\n oldLoading,\n actionName,\n actionType,\n isAsync,\n actionCtx\n );\n\n if (newState != null) {\n hasChanged = true;\n stateRef.current = newState;\n }\n\n if (oldLoading !== newLoading) {\n newLoadingMap = buildLoadingMap(\n newLoadingMap,\n actionName,\n actionCtx?.promiseId || DEFAULT_PROMISE_ID,\n newLoading\n );\n if (Object.keys(newLoadingMap).length === 0) {\n newLoadingMap = undefined;\n }\n }\n\n if (newLoadingMap != null) {\n hasChanged = true;\n loadingMapRef.current = newLoadingMap;\n }\n\n if (hasChanged) {\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (!init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n } else if (propsChanged) {\n const derivedChanged = computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (derivedChanged && !init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n }\n }\n\n const keys = Object.keys(actionsImpl) as (keyof A)[];\n actionsRef.current = keys.reduce<A>((acc, actionName) => {\n const action = actionsImpl[actionName];\n if (isSimpleSyncAction(action)) {\n acc[actionName] = decorateSimpleSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n initializedRef,\n setState\n ) as any;\n } else if (isAsyncAction(action)) {\n acc[actionName] = decorateAsyncAction({\n actionName,\n stateRef,\n derivedStateRef,\n propsRef,\n loadingMapRef,\n actionsRef,\n promisesRef,\n conflictActionsRef,\n initializedRef,\n options,\n setState,\n action: computeAsyncActionInput(action),\n }) as any;\n } else if (isSyncAction(action)) {\n acc[actionName] = decorateSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n actionsRef,\n initializedRef,\n timeoutRef,\n options,\n setState\n ) as any;\n }\n\n return acc;\n }, {} as A);\n\n function isLoading<K extends keyof A>(...props: (K | [K, string])[]) {\n return isLoadingImpl(loadingMapRef.current, ...props);\n }\n\n function abortAction(actionName: keyof A, promiseId: string = DEFAULT_PROMISE_ID) {\n const abortController = promisesRef.current[actionName]?.[promiseId]?.abortController;\n\n let res = false;\n if (abortController) {\n abortController.abort();\n res = true;\n }\n\n return res;\n }\n\n function isAnyLoading() {\n if (initializedRef.current) {\n const loadingMap = loadingMapRef.current;\n return (\n Object.keys(loadingMap).find((actionName) => {\n const promises = loadingMap[actionName];\n return Object.keys(promises).find((pId) => !!promises[pId]);\n }) != null\n );\n }\n return null;\n }\n\n function getLoadingMap() {\n if (initializedRef.current) {\n const map = loadingMapRef.current;\n const keys = Object.keys(map) as (keyof A)[];\n return keys.reduce<LoadingMap<A>>((acc, actionName) => {\n acc[actionName] = Object.keys(map[actionName]).find((pId) => !!map[actionName][pId]) != null;\n return acc;\n }, {});\n }\n return null;\n }\n\n function getConfig() {\n return {\n getInitialState,\n options,\n actions: actionsImpl,\n };\n }\n\n return {\n getConfig,\n setProps,\n addStateListener,\n init,\n destroy,\n isLoading,\n abortAction,\n get actions() {\n return actionsRef.current;\n },\n get state() {\n if (initializedRef.current) {\n return {\n ...stateRef.current,\n ...derivedStateRef.current.state,\n };\n }\n return null;\n },\n get loading() {\n return isAnyLoading();\n },\n get loadingMap() {\n return getLoadingMap();\n },\n get loadingParallelMap() {\n if (initializedRef.current) {\n return loadingMapRef.current;\n }\n return null;\n },\n };\n}\n\n// =====================================\n//\n// REACT HOOKS\n//\n// =====================================\n\ntype useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE> = (\n store: StoreApi<S, A, P, DS>,\n slicer: (ctx: StateListenerContext<S, DS, A>) => SLICE\n) => SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @param comparator An optional function to compare if slice property has changed (shallow test by default)\n * @returns The state slice.\n */\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n store: StoreApi<S, A, P, DS>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, K extends keyof StateListenerContext<S, DS, A>>(\n store: StoreApi<S, A, P, DS>,\n properties: K[]\n): Pick<StateListenerContext<S, DS, A>, K>;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS>(store: StoreApi<S, A, P, DS>, funcOrArr: any) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const slicerFunc = useMemo(\n () => (funcOrArr instanceof Function ? funcOrArr : (ctx: StateListenerContext<S, DS, A>) => pick(ctx, funcOrArr)),\n [funcOrArr]\n );\n\n const sliceRef = useRef<any>(null);\n if (sliceRef.current === null) {\n const s = store.state;\n sliceRef.current = slicerFunc({\n ...s,\n ...store.actions,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n });\n }\n\n useLayoutEffect(() => {\n const unregister = store.addStateListener((ctx) => {\n let hasChanged = false;\n\n const slice = slicerFunc(ctx);\n const prevSlice = sliceRef.current;\n const compare = globalConfig.comparator;\n\n hasChanged = prevSlice == null || !compare(slice, prevSlice);\n\n sliceRef.current = slice;\n\n if (hasChanged) {\n forceRefresh();\n }\n });\n\n return unregister;\n }, []);\n\n return sliceRef.current;\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n * This component will be refreshed for every change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @returns The state, actions and isLoading function.\n */\nexport function useStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const storeRef = useRef(store);\n\n store.setProps(props);\n\n useLayoutEffect(\n () =>\n storeRef.current.addStateListener(() => {\n forceRefresh();\n }),\n []\n );\n\n useEffect(() => () => store.destroy(), []);\n\n return {\n state: store.state,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n loadingParallelMap: store.loadingParallelMap,\n };\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n *\n * This component will NOT be refreshed for any change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n */\nexport function useBindStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n // access to store in debugger\n useRef(store);\n\n store.setProps(props);\n useEffect(() => {\n return () => store.destroy();\n }, []);\n return store;\n}\n\n/**\n * Creates and manages a local store.\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns The state, actions and isLoading function.\n */\nexport function useLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n return useStore(storeRef.current, props);\n}\n\nexport default useLocalStore;\n\n// ------------- UTILS\n\n/**\n * Creates a new object by picking properties to the object passed a first parameter\n * @param obj Object to pick properties from\n * @param props Property names\n * @returns a new object containing only picked properties\n */\nexport function pick<T, K extends keyof T>(obj: T, props: K[]): Pick<T, K> {\n return props.reduce((acc, p) => {\n if (obj.hasOwnProperty(p)) {\n acc[p] = obj[p];\n }\n return acc;\n }, {} as any);\n}\n\n/**\n * Returns a function that creates a new object by picking properties to the object passed as first parameter.\n * To be used in conjunction of <code>useStoreSlice</code> like in example:\n * const s = useStoreSlice(myStore, slice('list', 'addItem'));\n * @param props Property names\n * @returns a function to pick property from an passed object.\n */\nexport function slice<T, K extends keyof T>(...props: K[]): (obj: T) => Pick<T, K> {\n return (store: T) => pick(store, props);\n}\n"],"names":["ConflictPolicy","module","arr","Array","isArray","exports","i","Symbol","iterator","Object","_arr","_n","_d","_e","undefined","_s","_i","next","done","push","value","length","err","len","arr2","o","minLen","arrayLikeToArray","n","prototype","toString","call","slice","constructor","name","from","test","TypeError","arrayWithHoles","iterableToArrayLimit","unsupportedIterableToArray","nonIterableRest","obj","key","defineProperty","enumerable","configurable","writable","createStore","getInitialState","actionsImpl","options","storeMiddlewares","stateRef","createRef","derivedStateRef","propsRef","actionsRef","timeoutRef","loadingMapRef","promisesRef","conflictActionsRef","initializedRef","middlewaresRef","stateListeners","stateListenerCount","addStateListener","listener","id","notifyStateListeners","newState","derivedState","s","ctx","current","isLoading","abortAction","loading","isAnyLoading","loadingMap","getLoadingMap","keys","forEach","listenerId","setProps","p","oldProps","onPropChange","setState","init","setInternalState","computeDerivedValues","state","initialActionSet","Set","initialActionsMarkedLoading","reduce","acc","has","DEFAULT_PROMISE_ID","deps","actions","mapper","m","middleware","globalConfig","defaultMiddlewares","onMount","buildOnMountInvocationContext","destroy","onUnmount","clearTimeout","newStateIn","newLoadingMapIn","actionName","actionType","isAsync","actionCtx","propsChanged","hasChanged","newLoadingMap","oldLoading","isLoadingImpl","promiseId","runMiddlewares","newLoading","buildLoadingMap","derivedChanged","props","abortController","_promisesRef$current$","_promisesRef$current$2","res","abort","find","promises","pId","map","getConfig","action","isSimpleSyncAction","decorateSimpleSyncAction","isAsyncAction","decorateAsyncAction","computeAsyncActionInput","isSyncAction","decorateSyncAction","useStore","store","useReducer","forceRefresh","storeRef","useRef","useLayoutEffect","useEffect","loadingParallelMap","useLocalStore","actionImpl","middlewares","pick","hasOwnProperty","funcOrArr","slicerFunc","useMemo","Function","sliceRef","prevSlice","compare","comparator"],"mappings":"wRAmCYA,mBC/BZC,UAJA,SAAyBC,GACvB,GAAIC,MAAMC,QAAQF,GAAM,OAAOA,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kBAAOF,aAAqBG,SAAWH,EAAY,SAACxF,UAAwCsF,EAAKtF,EAAKwF,MACtG,CAACA,IAGGI,EAAWb,SAAY,SACJ,OAArBa,EAAS3F,QAAkB,KACvBF,EAAI4E,EAAMxD,MAChByE,EAAS3F,QAAUwF,WACd1F,GACA4E,EAAM/C,aACTA,QAAS+C,EAAM/C,QACfxB,QAASuE,EAAMvE,QACfF,UAAWyE,EAAMzE,UACjBC,YAAawE,EAAMxE,YACnBG,WAAYqE,EAAMrE,qBAItB0E,mBAAgB,kBACKL,EAAMlF,kBAAiB,SAACO,OACrC8C,EAEEvF,EAAQkI,EAAWzF,GACnB6F,EAAYD,EAAS3F,QACrB6F,EAAU9D,eAAa+D,WAE7BjD,EAA0B,MAAb+C,IAAsBC,EAAQvI,EAAOsI,GAElDD,EAAS3F,QAAU1C,EAEfuF,GACF+B,SAKH,IAEIe,EAAS3F"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/types.ts","../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/nonIterableRest.js","../node_modules/@babel/runtime/helpers/slicedToArray.js","../node_modules/@babel/runtime/helpers/defineProperty.js","../src/index.ts"],"sourcesContent":["/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nexport type PromiseResult<Type> = Type extends Promise<infer X> ? X : null;\n\nexport type NotifyFunc = (msg: string) => void;\n\nexport type PromiseIdMap = { [promiseId: string]: boolean };\n\nexport type LoadingMap<A> = { [pId in keyof A]?: boolean };\nexport type LoadingParallelMap<A> = { [P in keyof A]?: PromiseIdMap };\nexport type InternalLoadingMap<A> = LoadingParallelMap<A>;\n\nexport type LoadingProps<A> = {\n loading: boolean;\n loadingMap: LoadingMap<A>;\n loadingParallelMap: LoadingParallelMap<A>;\n};\n\nexport type PromiseIdErrorMap = { [promiseId: string]: Error };\nexport type ErrorMap<A> = { [pId in keyof A]?: Error };\nexport type ErrorParallelMap<A> = { [P in keyof A]?: PromiseIdErrorMap };\n\n// https://github.com/Microsoft/TypeScript/issues/15300\nexport interface DecoratedActions {\n [name: string]: (...args: any[]) => Promise<any> | void;\n}\n\n/**\n * The State decorator can manage only one asynchronous action of same name at a time.\n * This enum is enumertaing all the policies in such case.\n */\nexport enum ConflictPolicy {\n /**\n * Reject the promise.\n */\n REJECT = 'reject',\n\n /**\n * Return a resolved promise with no result.\n */\n IGNORE = 'ignore',\n\n /**\n * Execute only the last call that conflicts after the one ongoing.\n */\n KEEP_LAST = 'keepLast',\n\n /**\n * Execute all calls one after another.\n */\n KEEP_ALL = 'keepAll',\n\n /**\n * Execute all calls one after another.\n * @see getPromiseId\n */\n PARALLEL = 'parallel',\n\n /**\n * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!\n */\n REUSE = 'reuse',\n}\n\nexport type PromiseProvider<S, DS, F extends (...args: any[]) => any, A, P> = (\n ctx: GetPromiseInvocationContext<S, DS, F, P, A>\n) => ReturnType<F> | null;\n\n/**\n * Simple form of a synchronous action.\n */\nexport type SimpleSyncAction<S, F extends (...args: any[]) => any, P, DS, FxRes = S> = (\n ctx: InvocationContext<S, DS, F, P>\n) => FxRes | null;\n\nexport type SyncAction<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * Function that update the state when the action is called.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Debounces the action if this parameter is defined.\n */\n debounceTimeout?: number;\n\n /**\n * Debounces the action side effects if this parameter is defined.\n */\n debounceSideEffectsTimeout?: number;\n\n /**\n * Function that calls side effects, ie. effects that are not changing the state directly.\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n};\n\n/**\n * Try to abort an action, if the action is <code>abortable</code>.\n * @param actionName The action name\n * @param promiseId If the action conflict type is <code>ConflictType.PARALLEL</code>, the identifier of the promise.\n * @returns <code>true</code> if the action is abortable and an action is ongoing, <code>false</code> otherwise.\n */\nexport type AbortActionCallback<A> = (actionName: keyof A, promiseId?: string) => boolean;\n\nexport type GetErrorMessage<S, DS, F extends (...args: any[]) => any, P> = (\n ctx: ErrorMessageInvocationContext<S, DS, F, P>\n) => string;\n\nexport type ContextState<S> = {\n state: S;\n s: S;\n};\n\nexport type ContextDerivedStateState<DS> = {\n derived: DS;\n ds: DS;\n};\n\nexport type ContextBase<S, P> = ContextState<S> & {\n props: P;\n p: P;\n};\n\nexport type ContextWithDerived<S, DS, P> = ContextBase<S, P> & ContextDerivedStateState<DS>;\n\nexport type InvocationContextActions<A> = {\n actions: A;\n a: A;\n};\n\nexport type WarningNotifyFunc = {\n notifyWarning?: NotifyFunc;\n};\n\nexport type InvocationContext<S, DS, F extends (...args: any[]) => any, P> = ContextWithDerived<S, DS, P> & {\n args: Parameters<F>;\n promiseId: string;\n};\n\nexport type EffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<S, DS, F, P> & {\n result: PromiseResult<ReturnType<F>>;\n res: PromiseResult<ReturnType<F>>;\n};\n\nexport type GetPromiseInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = InvocationContextActions<A> &\n InvocationContext<S, DS, F, P> & {\n abortSignal: AbortSignal;\n };\n\nexport type ErrorEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P> = InvocationContext<\n S,\n DS,\n F,\n P\n> & {\n error: Error;\n err: Error;\n};\n\nexport type SuccessMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\nexport type ErrorMessageInvocationContext<S, DS, F extends (...args: any[]) => any, P> = ErrorEffectsInvocationContext<\n S,\n DS,\n F,\n P\n>;\n\nexport type SideEffectsInvocationContext<S, DS, F extends (...args: any[]) => any, P, A> = EffectsInvocationContext<\n S,\n DS,\n F,\n P\n> &\n InvocationContextActions<A> &\n WarningNotifyFunc;\n\nexport type ErrorSideEffectsInvocationContext<\n S,\n DS,\n F extends (...args: any[]) => any,\n P,\n A\n> = ErrorEffectsInvocationContext<S, DS, F, P> & InvocationContextActions<A> & WarningNotifyFunc;\n\nexport type OnMountInvocationContext<S, A, P> = ContextBase<S, P> & InvocationContextActions<A>;\n\nexport type EffectsType = 'preEffects' | 'effects' | 'errorEffects' | 'optimisticEffects' | null;\n\nexport type MiddlewareActionContext<S, A, P> = {\n name: keyof A;\n type: EffectsType;\n isAsync: boolean;\n context: InvocationContext<S, any, any, P>;\n};\n\nexport type MiddlewareStoreContext<S, A extends DecoratedActions, P> = {\n actions: StoreActions<S, A, P, any, any>;\n state: S;\n setState: (s: S) => void;\n options: StoreOptions<S, A, P, any>;\n};\n\nexport type MiddlewareFactory<S, A extends DecoratedActions, P> = () => Middleware<S, A, P>;\n\n/**\n * A state change middleware.\n * Allow to listen and change a state change on the fly.\n */\nexport type Middleware<S, A extends DecoratedActions, P> = {\n /**\n * Initializes the middleware. Called when the store is initializing.\n */\n init: (storeContext: MiddlewareStoreContext<S, A, P>) => void;\n\n /**\n * Invoked on a state change has occurred and returns a new state or <code>null</code> if unchanged.\n */\n effects: (\n actionContext: MiddlewareActionContext<S, A, P>,\n oldState: S,\n newState: S,\n loading: boolean\n ) => null | {\n state: S;\n loading: boolean;\n };\n\n /**\n * Destroys the middleware. Called when the store is being destroyed.\n */\n destroy: () => void;\n};\n\nexport type AsyncActionBase<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = {\n /**\n * This action can be aborted. An abortSignal will be injected to the <code>promise</code> / <code>promiseGet</code>.\n */\n abortable?: boolean;\n\n /**\n * A function that provides the success message to pass to the notifySuccess function passed as property to the StateDecorator.\n */\n getSuccessMessage?: (ctx: SuccessMessageInvocationContext<S, DS, F, P>) => string;\n\n /**\n * A function that provides the error message to pass to the notifyError function passed as property to the StateDecorator.\n */\n getErrorMessage?: GetErrorMessage<S, DS, F, P>;\n\n /**\n * If set, called with the result of the promise to update the current state.\n */\n effects?: (ctx: EffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * If set, called with the error of the promise to update the current state.\n */\n errorEffects?: (ctx: ErrorEffectsInvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Whether reject the promise instead of handling it.\n */\n rejectPromiseOnError?: boolean;\n\n /**\n * When the error will not be managed by an errorEffect, errorSideEffect, getErrorMessage,\n * the state decorator will not display an error message and will not return a failed promise\n * (unless <code>rejectPromiseOnError</code>) is set.\n */\n isErrorManaged?: boolean;\n\n /**\n * Handle side effects when the request succeeded.\n * @param result The result of the request\n * @param newData The data after the reducer is applied\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi success (use successMessage / getSuccessMessage otherwise).\n */\n sideEffects?: (ctx: SideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Handle side effects when the request failed.\n * @param error The error of the request\n * @param args The argument during the call of the request function\n * @param props The props passed to the state decorator\n * @param actions The actions available\n * @param notifyWarning If specified, a notify function to indicate that the action is a semi failure (use errorMessage / getErrorMessage otherwise).\n */\n errorSideEffects?: (ctx: ErrorSideEffectsInvocationContext<S, DS, F, P, A>) => void;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n preEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Retrieve the state to set as current data before the promise is resolved.\n * If the there's no reducer, this data will be used after the promise is done.\n */\n optimisticEffects?: (ctx: InvocationContext<S, DS, F, P>) => FxRes | null;\n\n /**\n * Policy to apply when a call to an asynchronous action is done but a previous call is still not resolved.\n */\n conflictPolicy?: ConflictPolicy;\n\n /**\n * Get an identifier for an action call. Used only when conflictPolicy is ConflictPolicy.PARALLEL.\n * This information will be available in loadingMap. loadingMap[actionName] will be an array of promise identifiers.\n */\n getPromiseId?: (...args: Parameters<F>) => string;\n\n /**\n * Number of retries in case of error (failed to fetch).\n * Do not use this if you are creating objects...\n * Default value is 0 (no retry).\n */\n retryCount?: number;\n\n /**\n * Seed of delay between each retry in milliseconds.\n * The applied delay is retryDelaySeed * retry count.\n * Default value is 1000 (1 second).\n */\n retryDelaySeed?: number;\n\n /**\n * Function to test if the error will trigger an action retry or will fail directly.\n */\n isTriggerRetryError?: (e: Error) => boolean;\n};\n\nexport type AsyncActionPromise<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise\n */\n getPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncActionPromiseGet<S, F extends (...args: any[]) => any, A, P, DS, FxRes = S> = AsyncActionBase<\n S,\n F,\n A,\n P,\n DS,\n FxRes\n> & {\n /**\n * The request, returns a promise that is a GET request.\n * A shortcut to set:\n * - retryCount: 3\n * - conflictPolicy: ConflictPolicy.REUSE\n */\n getGetPromise: PromiseProvider<S, DS, F, A, P>;\n};\n\nexport type AsyncAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncActionPromise<S, F, A, P, DS, FxRes>\n | AsyncActionPromiseGet<S, F, A, P, DS, FxRes>;\n\nexport type StoreAction<S, F extends (...args: any[]) => any, A, P, DS = {}, FxRes = S> =\n | AsyncAction<S, F, A, P, DS, FxRes>\n | SimpleSyncAction<S, F, P, DS, FxRes>\n | SyncAction<S, F, A, P, DS, FxRes>;\n\n/**\n * S: The type of the state\n * A: The type of the actions to pass to the children (used to check keys only).\n */\nexport type StoreActions<S, A extends DecoratedActions, P = {}, DS = {}, FxRes = S> = {\n [Prop in keyof A]: StoreAction<S, A[Prop], A, P, DS, FxRes>;\n};\n\nexport type OnPropsChangeEffectsContext<S, DS, P> = ContextWithDerived<S, DS, P> & {\n indices: number[];\n index: number;\n isInit: boolean;\n};\n\nexport type OnPropsChangeSideEffectsContext<S, P, A, DS = {}> = OnPropsChangeEffectsContext<S, DS, P> & {\n actions: A;\n a: A;\n};\n\ntype DerivedStateOption<S, P, DS> = {\n [k in keyof DS]: {\n getDeps: (ctx: ContextBase<S, P>) => any[];\n get: (ctx: ContextBase<S, P>) => DS[k];\n };\n};\n\nexport type OnPropsChangeOptions<S, DS, A, P> = {\n onMount?: boolean;\n getDeps: (p: P) => any[];\n effects?: (ctx: OnPropsChangeEffectsContext<S, DS, P>) => S;\n sideEffects?: (ctx: OnPropsChangeSideEffectsContext<S, P, A>) => void;\n};\n\nexport type StoreOptions<S, A, P = {}, DS = {}> = {\n /**\n * The state decorator name. Use in debug traces to identify the useStateDecorator instance.\n */\n name?: string;\n\n /**\n * List of action names that are marked as loading at initial time.\n * If you must start your initial actions in a useSideEffect, a render is done before\n * first actions can be trigerred, some actions can be marked as loading at initial time.\n */\n initialActionsMarkedLoading?: (keyof A)[];\n\n /**\n * One or several configurations of inbound properties change managements.\n */\n onPropsChange?: OnPropsChangeOptions<S, DS, A, P> | OnPropsChangeOptions<S, DS, A, P>[];\n\n /**\n * The callback function called if an asynchronous function succeeded and a success messsage is defined.\n */\n notifySuccess?: NotifyFunc;\n\n /**\n * The callback function called if an asynchronous function fails and an error messsage is defined.\n */\n notifyError?: NotifyFunc;\n\n /**\n * The callback function injected in onDone and onFail of asynchronous functions to notify a semi success / failed request.\n */\n notifyWarning?: NotifyFunc;\n\n /**\n * Initial actions.\n */\n onMount?: (ctx: OnMountInvocationContext<S, A, P>) => void;\n\n /**\n * Callback on store destruction.\n */\n onUnmount?: (ctx: OnMountInvocationContext<S, A, P>) => Promise<any> | void;\n\n /**\n * Compute derived state\n */\n derivedState?: DerivedStateOption<S, P, DS>;\n};\n","function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","var arrayWithHoles = require(\"./arrayWithHoles.js\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\n\nvar nonIterableRest = require(\"./nonIterableRest.js\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","/*\n * Copyright 2019 Globalsport SAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport { useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';\nimport {\n computeAsyncActionInput,\n createRef,\n isSyncAction,\n isAsyncAction,\n isSimpleSyncAction,\n TimeoutMap,\n PromiseMap,\n DEFAULT_PROMISE_ID,\n globalConfig,\n setGlobalConfig,\n GlobalConfig,\n ConflictActionsMap,\n buildOnMountInvocationContext,\n decorateSimpleSyncAction,\n decorateSyncAction,\n decorateAsyncAction,\n computeDerivedValues,\n DerivedState,\n onPropChange,\n runMiddlewares,\n buildLoadingMap,\n isLoadingImpl,\n ParallelActionError,\n buildErrorMap,\n} from './impl';\n\nimport {\n DecoratedActions,\n StoreActions,\n AsyncAction,\n SyncAction,\n SimpleSyncAction,\n InternalLoadingMap,\n LoadingMap,\n ErrorMap,\n LoadingParallelMap,\n ErrorParallelMap,\n StoreOptions,\n AsyncActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n ContextState,\n ConflictPolicy,\n Middleware,\n AbortActionCallback,\n MiddlewareFactory,\n MiddlewareStoreContext,\n LoadingProps,\n} from './types';\n\nexport {\n DecoratedActions,\n StoreActions,\n LoadingMap,\n ErrorMap,\n LoadingParallelMap,\n ErrorParallelMap,\n ParallelActionError,\n StoreOptions,\n AsyncActionPromise as AsynchActionPromise,\n InvocationContext,\n GetPromiseInvocationContext,\n EffectsInvocationContext,\n InvocationContextActions,\n WarningNotifyFunc,\n ErrorEffectsInvocationContext,\n OnMountInvocationContext,\n ContextBase,\n OnPropsChangeEffectsContext,\n SyncAction,\n AsyncAction,\n SimpleSyncAction,\n ContextState,\n ConflictPolicy,\n GlobalConfig,\n Middleware,\n setGlobalConfig,\n LoadingProps,\n AbortActionCallback,\n};\n\nexport type IsLoadingFunc<A> = (...props: (keyof A | [keyof A, string])[]) => boolean;\ntype StateListenerUnregister = () => void;\n\nexport type StoreApi<S, A extends DecoratedActions, P, DS = {}> = {\n /**\n * The current store state (with derived state if any).\n */\n readonly state: S & DS;\n /**\n * The store decorator (ie. ready to use) actions.\n */\n readonly actions: A;\n /**\n * A boolean that indicates that at least one asynchronous action is loading.\n */\n readonly loading: boolean;\n /**\n * A map of loading actions map (computed on property access)\n */\n readonly loadingMap: LoadingMap<A>;\n /**\n * A map of loading actions map (computed on property access)\n */\n readonly errorMap: ErrorMap<A>;\n /**\n * A map of parallel loading actions map (computed on property access)\n */\n readonly loadingParallelMap: LoadingParallelMap<A>;\n /**\n * A map of parallel actions error map (computed on property access)\n */\n readonly errorParallelMap: ErrorParallelMap<A>;\n /**\n * Initializes the store with the specified props\n */\n init: (p: P) => void;\n /**\n * Update the store with the specified props\n */\n setProps: (p: P) => void;\n /**\n * Destroy the store\n */\n destroy: () => void;\n /**\n * Abort an asynchronous action marked as abortable.\n */\n abortAction: (actionName: keyof A, promiseId?: string) => boolean;\n /**\n * Add a store state change listener\n */\n addStateListener: (listener: StateListener<S, DS, A>) => StateListenerUnregister;\n /**\n * A function that takes a list of action names or a tuple of [action name, promiseId] and returns <code>true</code> if any action is loading.\n */\n isLoading: IsLoadingFunc<A>;\n\n getConfig: () => {\n getInitialState: (p: P) => S;\n options: StoreOptions<S, A, P, DS>;\n actions: StoreActions<S, A, P, DS>;\n };\n};\n\nexport type StateListenerContext<S, DS, A extends DecoratedActions> = S &\n DS &\n A &\n Pick<StoreApi<S, A, any, DS>, 'loading' | 'loadingMap' | 'errorMap' | 'isLoading' | 'abortAction'>;\n\nexport type StateListener<S, DS, A extends DecoratedActions> = (ctx: StateListenerContext<S, DS, A>) => void;\n\n// =============================\n//\n// STORE\n//\n// =============================\n\n/**\n * Create a new store.\n * @param getInitialState The state initialization function (using props)\n * @param actionsImpl The actions implementation (pure functions only).\n * @param options Options to configure the store\n * @returns a store.\n */\nexport function createStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionsImpl: StoreActions<S, A, P, DS>,\n options: StoreOptions<S, A, P, DS> = {},\n storeMiddlewares: MiddlewareFactory<S, A, P>[] = null\n): StoreApi<S, A, P, DS> {\n const stateRef = createRef<S>();\n const derivedStateRef = createRef<DerivedState<DS>>();\n const propsRef = createRef<P>();\n const actionsRef = createRef<A>();\n const timeoutRef = createRef<TimeoutMap<A>>();\n const loadingMapRef = createRef<InternalLoadingMap<A>>();\n const errorMapRef = createRef<ErrorParallelMap<A>>();\n const promisesRef = createRef<PromiseMap<A>>();\n const conflictActionsRef = createRef<ConflictActionsMap<A>>();\n const initializedRef = createRef(false);\n\n const middlewaresRef = createRef<Middleware<S, A, P>[]>([]);\n\n let stateListeners: Record<string, StateListener<S, DS, A>> = {};\n let stateListenerCount = 0;\n\n function addStateListener(listener: StateListener<S, DS, A>): () => void {\n const id = `${stateListenerCount++}`;\n stateListeners[id] = listener;\n return () => {\n delete stateListeners[id];\n };\n }\n\n function notifyStateListeners(newState: S, derivedState: DS) {\n const s = {\n ...newState,\n ...derivedState,\n };\n\n const ctx: StateListenerContext<S, DS, A> = {\n ...s,\n ...actionsRef.current,\n isLoading,\n abortAction,\n loading: isAnyLoading(),\n loadingMap: getLoadingMap(),\n errorMap: getErrorMap(),\n };\n\n Object.keys(stateListeners).forEach((listenerId) => {\n stateListeners[listenerId](ctx);\n });\n }\n\n function setProps(p: P) {\n const oldProps = propsRef.current;\n\n propsRef.current = p;\n\n if (!initializedRef.current) {\n init(p);\n } else {\n onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, setState, false);\n }\n }\n\n /** Middleware only: sets the internal state, recompute derived state and notify listeners */\n function setInternalState(s: S) {\n stateRef.current = s;\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n\n function init(p: P) {\n if (!initializedRef.current) {\n propsRef.current = p;\n initializedRef.current = true;\n stateRef.current = getInitialState(p);\n\n const initialActionSet = new Set(options?.initialActionsMarkedLoading);\n\n loadingMapRef.current = (Object.keys(actionsImpl) as (keyof A)[]).reduce<InternalLoadingMap<A>>((acc, name) => {\n acc[name] = initialActionSet.has(name) ? { [DEFAULT_PROMISE_ID]: true } : {};\n return acc;\n }, {});\n\n errorMapRef.current = (Object.keys(actionsImpl) as (keyof A)[]).reduce<ErrorParallelMap<A>>((acc, name) => {\n acc[name] = {};\n return acc;\n }, {});\n\n timeoutRef.current = {};\n promisesRef.current = {};\n conflictActionsRef.current = {};\n derivedStateRef.current = {\n state: null,\n deps: {},\n };\n\n // init middlewares\n middlewaresRef.current = [];\n const ctx: MiddlewareStoreContext<S, A, P> = {\n options,\n get state() {\n return stateRef.current;\n },\n actions: actionsImpl,\n setState: setInternalState,\n };\n const mapper = (m: MiddlewareFactory<S, A, P>) => {\n const middleware = m();\n middlewaresRef.current.push(middleware);\n middleware.init?.(ctx);\n };\n globalConfig.defaultMiddlewares?.forEach(mapper);\n storeMiddlewares?.forEach(mapper);\n // end init\n\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n\n // manage PropsChange with onMount\n onPropChange(stateRef, derivedStateRef, propsRef, null, actionsRef, options, setState, true);\n\n if (options?.onMount) {\n options.onMount(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n }\n\n notifyStateListeners(stateRef.current, derivedStateRef.current.state);\n }\n }\n\n function destroy() {\n if (initializedRef.current) {\n options?.onUnmount?.(buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef));\n\n propsRef.current = null;\n stateRef.current = null;\n loadingMapRef.current = null;\n errorMapRef.current = null;\n promisesRef.current = null;\n conflictActionsRef.current = null;\n derivedStateRef.current = null;\n\n Object.keys(timeoutRef.current).forEach((name) => {\n clearTimeout(timeoutRef.current[name]);\n });\n\n timeoutRef.current = null;\n stateListeners = {};\n initializedRef.current = false;\n\n middlewaresRef.current.forEach((m) => {\n m.destroy?.();\n });\n\n middlewaresRef.current = [];\n }\n }\n\n function setState(\n newStateIn: S,\n newLoadingMapIn: InternalLoadingMap<A>,\n actionName: keyof A,\n actionType: 'preEffects' | 'effects' | 'errorEffects' | null,\n isAsync: boolean,\n actionCtx: any,\n propsChanged: boolean = false,\n init = false\n ) {\n let hasChanged = false;\n\n if (!initializedRef.current) {\n return;\n }\n\n let newLoadingMap = newLoadingMapIn;\n\n const oldLoading = isAsync\n ? isLoadingImpl(newLoadingMap || loadingMapRef.current, [actionName, actionCtx?.promiseId])\n : false;\n\n const { newState, newLoading } = runMiddlewares(\n middlewaresRef.current,\n stateRef.current,\n newStateIn,\n oldLoading,\n actionName,\n actionType,\n isAsync,\n actionCtx\n );\n\n if (newState != null) {\n hasChanged = true;\n stateRef.current = newState;\n }\n\n if (oldLoading !== newLoading) {\n newLoadingMap = buildLoadingMap(\n newLoadingMap,\n actionName,\n actionCtx?.promiseId || DEFAULT_PROMISE_ID,\n newLoading\n );\n if (Object.keys(newLoadingMap).length === 0) {\n newLoadingMap = undefined;\n }\n }\n\n if (newLoadingMap != null) {\n hasChanged = true;\n loadingMapRef.current = newLoadingMap;\n }\n\n if (hasChanged) {\n computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (!init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n } else if (propsChanged) {\n const derivedChanged = computeDerivedValues(stateRef, propsRef, derivedStateRef, options);\n if (derivedChanged && !init) {\n notifyStateListeners(newState || stateRef.current, derivedStateRef.current.state);\n }\n }\n }\n\n const keys = Object.keys(actionsImpl) as (keyof A)[];\n actionsRef.current = keys.reduce<A>((acc, actionName) => {\n const action = actionsImpl[actionName];\n if (isSimpleSyncAction(action)) {\n acc[actionName] = decorateSimpleSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n initializedRef,\n setState\n ) as any;\n } else if (isAsyncAction(action)) {\n acc[actionName] = decorateAsyncAction({\n actionName,\n stateRef,\n derivedStateRef,\n propsRef,\n loadingMapRef,\n errorMapRef,\n actionsRef,\n promisesRef,\n conflictActionsRef,\n initializedRef,\n options,\n setState,\n action: computeAsyncActionInput(action),\n }) as any;\n } else if (isSyncAction(action)) {\n acc[actionName] = decorateSyncAction(\n actionName,\n action,\n stateRef,\n derivedStateRef,\n propsRef,\n actionsRef,\n initializedRef,\n timeoutRef,\n options,\n setState\n ) as any;\n }\n\n return acc;\n }, {} as A);\n\n function isLoading<K extends keyof A>(...props: (K | [K, string])[]) {\n return isLoadingImpl(loadingMapRef.current, ...props);\n }\n\n function abortAction(actionName: keyof A, promiseId: string = DEFAULT_PROMISE_ID) {\n const abortController = promisesRef.current[actionName]?.[promiseId]?.abortController;\n\n let res = false;\n if (abortController) {\n abortController.abort();\n res = true;\n }\n\n return res;\n }\n\n function isAnyLoading() {\n if (initializedRef.current) {\n const loadingMap = loadingMapRef.current;\n return (\n Object.keys(loadingMap).find((actionName) => {\n const promises = loadingMap[actionName];\n return Object.keys(promises).find((pId) => !!promises[pId]);\n }) != null\n );\n }\n return null;\n }\n\n function getLoadingMap() {\n if (initializedRef.current) {\n const map = loadingMapRef.current;\n const keys = Object.keys(map) as (keyof A)[];\n return keys.reduce<LoadingMap<A>>((acc, actionName) => {\n const subMap = map[actionName];\n acc[actionName] = Object.keys(subMap).find((pId) => !!subMap[pId]) != null;\n return acc;\n }, {});\n }\n return null;\n }\n\n function getErrorMap() {\n if (initializedRef.current) {\n return buildErrorMap(errorMapRef.current);\n }\n return null;\n }\n\n function getConfig() {\n return {\n getInitialState,\n options,\n actions: actionsImpl,\n };\n }\n\n return {\n getConfig,\n setProps,\n addStateListener,\n init,\n destroy,\n isLoading,\n abortAction,\n get actions() {\n return actionsRef.current;\n },\n get state() {\n if (initializedRef.current) {\n return {\n ...stateRef.current,\n ...derivedStateRef.current.state,\n };\n }\n return null;\n },\n get loading() {\n return isAnyLoading();\n },\n get loadingMap() {\n return getLoadingMap();\n },\n get errorMap() {\n return getErrorMap();\n },\n get loadingParallelMap() {\n if (initializedRef.current) {\n return loadingMapRef.current;\n }\n return null;\n },\n get errorParallelMap() {\n if (initializedRef.current) {\n return errorMapRef.current;\n }\n return null;\n },\n };\n}\n\n// =====================================\n//\n// REACT HOOKS\n//\n// =====================================\n\ntype useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE> = (\n store: StoreApi<S, A, P, DS>,\n slicer: (ctx: StateListenerContext<S, DS, A>) => SLICE\n) => SLICE;\n\n/**\n * A react hook to get a state slice. Will be refresh if, and only if, one property of the slice has changed\n * @param store The store to listen to.\n * @param slicerFunc A function that returns a state slice\n * @param comparator An optional function to compare if slice property has changed (shallow test by default)\n * @returns The state slice.\n */\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, SLICE>(\n store: StoreApi<S, A, P, DS>,\n slicerFunc: (ctx: StateListenerContext<S, DS, A>) => SLICE\n): SLICE;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS, K extends keyof StateListenerContext<S, DS, A>>(\n store: StoreApi<S, A, P, DS>,\n properties: K[]\n): Pick<StateListenerContext<S, DS, A>, K>;\n\nexport function useStoreSlice<S, A extends DecoratedActions, P, DS>(store: StoreApi<S, A, P, DS>, funcOrArr: any) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const slicerFunc = useMemo(\n () => (funcOrArr instanceof Function ? funcOrArr : (ctx: StateListenerContext<S, DS, A>) => pick(ctx, funcOrArr)),\n [funcOrArr]\n );\n\n const sliceRef = useRef<any>(null);\n if (sliceRef.current === null) {\n const s = store.state;\n sliceRef.current = slicerFunc({\n ...s,\n ...store.actions,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n errorMap: store.errorMap,\n });\n }\n\n useLayoutEffect(() => {\n const unregister = store.addStateListener((ctx) => {\n let hasChanged = false;\n\n const slice = slicerFunc(ctx);\n const prevSlice = sliceRef.current;\n const compare = globalConfig.comparator;\n\n hasChanged = prevSlice == null || !compare(slice, prevSlice);\n\n sliceRef.current = slice;\n\n if (hasChanged) {\n forceRefresh();\n }\n });\n\n return unregister;\n }, []);\n\n return sliceRef.current;\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n * This component will be refreshed for every change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n * @returns The state, actions and isLoading function.\n */\nexport function useStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n const [, forceRefresh] = useReducer((s) => (s > 100 ? 0 : s + 1), 0);\n\n const storeRef = useRef(store);\n\n store.setProps(props);\n\n useLayoutEffect(\n () =>\n storeRef.current.addStateListener(() => {\n forceRefresh();\n }),\n []\n );\n\n useEffect(() => () => store.destroy(), []);\n\n return {\n state: store.state,\n actions: store.actions,\n loading: store.loading,\n isLoading: store.isLoading,\n abortAction: store.abortAction,\n loadingMap: store.loadingMap,\n errorMap: store.errorMap,\n loadingParallelMap: store.loadingParallelMap,\n errorParallelMap: store.errorParallelMap,\n };\n}\n\n/**\n * Binds the store to this component.\n * Store will be destroyed when component is unmouted.\n * Props passed to actions will come from this components.\n * If store is configured to react of props changes, it will used passed props.\n * A store must be bound to only one React component.\n *\n * This component will NOT be refreshed for any change in the store.\n *\n * @param store The store to listen to.\n * @param props The parent component props\n */\nexport function useBindStore<S, A extends DecoratedActions, P, DS = {}>(store: StoreApi<S, A, P, DS>, props: P = null) {\n // access to store in debugger\n useRef(store);\n\n store.setProps(props);\n useEffect(() => {\n return () => store.destroy();\n }, []);\n return store;\n}\n\n/**\n * Creates and manages a local store.\n * @param getInitialState Function to compute initial state from props.\n * @param actionImpl Actions implementation.\n * @param props Owner component props to update state or react on prop changes\n * @param options The store options.\n * @returns The state, actions and isLoading function.\n */\nexport function useLocalStore<S, A extends DecoratedActions, P, DS = {}>(\n getInitialState: (p: P) => S,\n actionImpl: StoreActions<S, A, P, DS>,\n props?: P,\n options?: StoreOptions<S, A, P, DS>,\n middlewares?: MiddlewareFactory<S, A, P>[]\n) {\n const storeRef = useRef<StoreApi<S, A, P, DS>>();\n if (storeRef.current == null) {\n storeRef.current = createStore(getInitialState, actionImpl, options, middlewares);\n }\n\n return useStore(storeRef.current, props);\n}\n\nexport default useLocalStore;\n\n// ------------- UTILS\n\n/**\n * Creates a new object by picking properties to the object passed a first parameter\n * @param obj Object to pick properties from\n * @param props Property names\n * @returns a new object containing only picked properties\n */\nexport function pick<T, K extends keyof T>(obj: T, props: K[]): Pick<T, K> {\n return props.reduce((acc, p) => {\n if (obj.hasOwnProperty(p)) {\n acc[p] = obj[p];\n }\n return acc;\n }, {} as any);\n}\n\n/**\n * Returns a function that creates a new object by picking properties to the object passed as first parameter.\n * To be used in conjunction of <code>useStoreSlice</code> like in example:\n * const s = useStoreSlice(myStore, slice('list', 'addItem'));\n * @param props Property names\n * @returns a function to pick property from an passed object.\n */\nexport function slice<T, K extends keyof T>(...props: K[]): (obj: T) => Pick<T, K> {\n return (store: T) => pick(store, props);\n}\n"],"names":["ConflictPolicy","module","arr","Array","isArray","exports","i","Symbol","iterator","Object","_arr","_n","_d","_e","undefined","_s","_i","next","done","push","value","length","err","len","arr2","o","minLen","arrayLikeToArray","n","prototype","toString","call","slice","constructor","name","from","test","TypeError","arrayWithHoles","iterableToArrayLimit","unsupportedIterableToArray","nonIterableRest","obj","key","defineProperty","enumerable","configurable","writable","createStore","getInitialState","actionsImpl","options","storeMiddlewares","stateRef","createRef","derivedStateRef","propsRef","actionsRef","timeoutRef","loadingMapRef","errorMapRef","promisesRef","conflictActionsRef","initializedRef","middlewaresRef","stateListeners","stateListenerCount","addStateListener","listener","id","notifyStateListeners","newState","derivedState","s","ctx","current","isLoading","abortAction","loading","isAnyLoading","loadingMap","getLoadingMap","errorMap","getErrorMap","keys","forEach","listenerId","setProps","p","oldProps","onPropChange","setState","init","setInternalState","computeDerivedValues","state","initialActionSet","Set","initialActionsMarkedLoading","reduce","acc","has","DEFAULT_PROMISE_ID","deps","actions","mapper","m","middleware","globalConfig","defaultMiddlewares","onMount","buildOnMountInvocationContext","destroy","onUnmount","clearTimeout","newStateIn","newLoadingMapIn","actionName","actionType","isAsync","actionCtx","propsChanged","hasChanged","newLoadingMap","oldLoading","isLoadingImpl","promiseId","runMiddlewares","newLoading","buildLoadingMap","derivedChanged","props","abortController","_promisesRef$current$","_promisesRef$current$2","res","abort","find","promises","pId","map","subMap","buildErrorMap","getConfig","action","isSimpleSyncAction","decorateSimpleSyncAction","isAsyncAction","decorateAsyncAction","computeAsyncActionInput","isSyncAction","decorateSyncAction","useStore","store","useReducer","forceRefresh","storeRef","useRef","useLayoutEffect","useEffect","loadingParallelMap","errorParallelMap","useLocalStore","actionImpl","middlewares","pick","hasOwnProperty","funcOrArr","slicerFunc","useMemo","Function","sliceRef","prevSlice","compare","comparator"],"mappings":"wRAuCYA,mBCnCZC,UAJA,SAAyBC,GACvB,GAAIC,MAAMC,QAAQF,GAAM,OAAOA,GAIjCD,EAAOI,QAAiB,QAAIJ,EAAOI,QAASJ,sBAA4B,sBCsBxEA,UA3BA,SAA+BC,EAAKI,GAClC,GAAsB,oBAAXC,QAA4BA,OAAOC,YAAYC,OAAOP,GAAjE,CACA,IAAIQ,EAAO,GACPC,GAAK,EACLC,GAAK,EACLC,OAAKC,EAET,IACE,IAAK,IAAiCC,EAA7BC,EAAKd,EAAIK,OAAOC,cAAmBG,GAAMI,EAAKC,EAAGC,QAAQC,QAChER,EAAKS,KAAK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AI,GAAzDkF,YAEHa,EAAaC,WACjB,kBAAOF,aAAqBG,SAAWH,EAAY,SAAC7F,UAAwC2F,EAAK3F,EAAK6F,MACtG,CAACA,IAGGI,EAAWd,SAAY,SACJ,OAArBc,EAAShG,QAAkB,KACvBF,EAAIgF,EAAM1D,MAChB4E,EAAShG,QAAU6F,WACd/F,GACAgF,EAAMjD,aACTA,QAASiD,EAAMjD,QACf1B,QAAS2E,EAAM3E,QACfF,UAAW6E,EAAM7E,UACjBC,YAAa4E,EAAM5E,YACnBG,WAAYyE,EAAMzE,WAClBE,SAAUuE,EAAMvE,mBAIpB4E,mBAAgB,kBACKL,EAAMtF,kBAAiB,SAACO,OACrCgD,EAEE1F,EAAQwI,EAAW9F,GACnBkG,EAAYD,EAAShG,QACrBkG,EAAUjE,eAAakE,WAE7BpD,EAA0B,MAAbkD,IAAsBC,EAAQ7I,EAAO4I,GAElDD,EAAShG,QAAU3C,EAEf0F,GACFiC,SAKH,IAEIgB,EAAShG"}
|
package/middlewares.es.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function e(t){var e={exports:{}};return t(e,e.exports),e.exports}var r=t(e((function(t){t.exports=function(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t},t.exports.default=t.exports,t.exports.__esModule=!0}))),n=t(e((function(t){function e(r){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?(t.exports=e=function(t){return typeof t},t.exports.default=t.exports,t.exports.__esModule=!0):(t.exports=e=function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.default=t.exports,t.exports.__esModule=!0),e(r)}t.exports=e,t.exports.default=t.exports,t.exports.__esModule=!0}))),o=Array.isArray,i=Object.keys,a=Object.prototype.hasOwnProperty,c=function t(e,r){if(e===r)return!0;if(e&&r&&"object"==typeof e&&"object"==typeof r){var n,c,u,s=o(e),l=o(r);if(s&&l){if((c=e.length)!=r.length)return!1;for(n=c;0!=n--;)if(!t(e[n],r[n]))return!1;return!0}if(s!=l)return!1;var f=e instanceof Date,p=r instanceof Date;if(f!=p)return!1;if(f&&p)return e.getTime()==r.getTime();var d=e instanceof RegExp,h=r instanceof RegExp;if(d!=h)return!1;if(d&&h)return e.toString()==r.toString();var y=i(e);if((c=y.length)!==i(r).length)return!1;for(n=c;0!=n--;)if(!a.call(r,y[n]))return!1;for(n=c;0!=n--;)if(!t(e[u=y[n]],r[u]))return!1;return!0}return e!=e&&r!=r},u=e((function(t){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n},t.exports.default=t.exports,t.exports.__esModule=!0})),s=e((function(t){t.exports=function(t){if(Array.isArray(t))return u(t)},t.exports.default=t.exports,t.exports.__esModule=!0})),l=e((function(t){t.exports=function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)},t.exports.default=t.exports,t.exports.__esModule=!0})),f=e((function(t){t.exports=function(t,e){if(t){if("string"==typeof t)return u(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?u(t,e):void 0}},t.exports.default=t.exports,t.exports.__esModule=!0})),p=e((function(t){t.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},t.exports.default=t.exports,t.exports.__esModule=!0}));e((function(t){t.exports=function(t){return s(t)||l(t)||f(t)||p()},t.exports.default=t.exports,t.exports.__esModule=!0}));var d,h=e((function(t){t.exports=function(t){if(Array.isArray(t))return t},t.exports.default=t.exports,t.exports.__esModule=!0})),y=e((function(t){t.exports=function(t,e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var r=[],n=!0,o=!1,i=void 0;try{for(var a,c=t[Symbol.iterator]();!(n=(a=c.next()).done)&&(r.push(a.value),!e||r.length!==e);n=!0);}catch(t){o=!0,i=t}finally{try{n||null==c.return||c.return()}finally{if(o)throw i}}return r}},t.exports.default=t.exports,t.exports.__esModule=!0})),v=e((function(t){t.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},t.exports.default=t.exports,t.exports.__esModule=!0}));e((function(t){t.exports=function(t,e){return h(t)||y(t,e)||f(t,e)||v()},t.exports.default=t.exports,t.exports.__esModule=!0})),e((function(t){function e(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}t.exports=function(t){return function(){var r=this,n=arguments;return new Promise((function(o,i){var a=t.apply(r,n);function c(t){e(a,o,i,c,u,"next",t)}function u(t){e(a,o,i,c,u,"throw",t)}c(void 0)}))}},t.exports.default=t.exports,t.exports.__esModule=!0})),e((function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function u(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{u({},"")}catch(t){u=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var o=e&&e.prototype instanceof v?e:v,i=Object.create(o.prototype),a=new N(n||[]);return i._invoke=function(t,e,r){var n=f;return function(o,i){if(n===d)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw i;return P()}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=S(a,r);if(c){if(c===y)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===f)throw n=h,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=d;var u=l(t,e,r);if("normal"===u.type){if(n=r.done?h:p,u.arg===y)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n=h,r.method="throw",r.arg=u.arg)}}}(t,r,a),i}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var f="suspendedStart",p="suspendedYield",d="executing",h="completed",y={};function v(){}function g(){}function m(){}var x={};x[i]=function(){return this};var E=Object.getPrototypeOf,b=E&&E(E(A([])));b&&b!==r&&n.call(b,i)&&(x=b);var w=m.prototype=v.prototype=Object.create(x);function O(t){["next","throw","return"].forEach((function(e){u(t,e,(function(t){return this._invoke(e,t)}))}))}function _(t,e){function r(o,i,a,c){var u=l(t[o],t,i);if("throw"!==u.type){var s=u.arg,f=s.value;return f&&"object"==typeof f&&n.call(f,"__await")?e.resolve(f.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(f).then((function(t){s.value=t,a(s)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var o;this._invoke=function(t,n){function i(){return new e((function(e,o){r(t,n,e,o)}))}return o=o?o.then(i,i):i()}}function S(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,S(t,r),"throw"===r.method))return y;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return y}var o=l(n,t.iterator,r.arg);if("throw"===o.type)return r.method="throw",r.arg=o.arg,r.delegate=null,y;var i=o.arg;return i?i.done?(r[t.resultName]=i.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,y):i:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}function j(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function L(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(j,this),this.reset(!0)}function A(t){if(t){var r=t[i];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,a=function r(){for(;++o<t.length;)if(n.call(t,o))return r.value=t[o],r.done=!1,r;return r.value=e,r.done=!0,r};return a.next=a}}return{next:P}}function P(){return{value:e,done:!0}}return g.prototype=w.constructor=m,m.constructor=g,g.displayName=u(m,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,m):(t.__proto__=m,u(t,c,"GeneratorFunction")),t.prototype=Object.create(w),t},t.awrap=function(t){return{__await:t}},O(_.prototype),_.prototype[a]=function(){return this},t.AsyncIterator=_,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new _(s(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},O(w),u(w,c,"Generator"),w[i]=function(){return this},w.toString=function(){return"[object Generator]"},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=A,N.prototype={constructor:N,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(L),!t)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=e)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var r=this;function o(n,o){return c.type="throw",c.arg=t,r.next=n,o&&(r.method="next",r.arg=e),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),s=n.call(a,"finallyLoc");if(u&&s){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,y):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),y},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),L(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;L(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:A(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),y}},t}(t.exports);try{regeneratorRuntime=e}catch(t){Function("r","regeneratorRuntime = r")(e)}})),function(t){t.REJECT="reject",t.IGNORE="ignore",t.KEEP_LAST="keepLast",t.KEEP_ALL="keepAll",t.PARALLEL="parallel",t.REUSE="reuse"}(d||(d={}));var g={clone:function(t){return JSON.parse(JSON.stringify(t))},comparator:function(t,e){if(Object.is(t,e))return!0;if("object"!==n(t)||null===t||"object"!==n(e)||null===e)return!1;if(t instanceof Set||e instanceof Set)return!1;var r=Object.keys(t),o=Object.keys(e);if(r.length!==o.length)return!1;for(var i=0;i<r.length;i++)if(!Object.prototype.hasOwnProperty.call(e,r[i])||!Object.is(t[r[i]],e[r[i]]))return!1;return!0},asyncErrorHandler:function(){},retryOnErrorFunction:function(t){return t instanceof TypeError},notifySuccess:void 0,notifyError:void 0,notifyWarning:void 0,getErrorMessage:void 0,defaultMiddlewares:[]};function m(t){return"function"==typeof t}function x(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function E(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?x(Object(n),!0).forEach((function(e){r(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):x(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function b(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:console.log,e=function(){var e=t,r="";return{init:function(t){if("development"===process.env.NODE_ENV||"test"===process.env.NODE_ENV){var n,o;r=null!==(n=t.options)&&void 0!==n&&n.name?"[".concat(null===(o=t.options)||void 0===o?void 0:o.name,"]"):"";var i=t.state;e(r,"initialState",i)}},destroy:null,effects:function(t,n,o,i){return"development"!==process.env.NODE_ENV&&"test"!==process.env.NODE_ENV||e(r,t.name,t.type,null===o?"no effect":o,t.isAsync?"preEffects"!==t.type||i?"loading: ".concat(i):"Promise cancelled":""),null}}};return e}function w(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:console;return function(){var e="",r=t;if("development"===process.env.NODE_ENV||"test"===process.env.NODE_ENV){var o=function(t,e){var r;if(e!==t){var o=n(null!=t?t:e);if("number"===o||"string"===o||"boolean"===o)r="".concat(t," => ").concat(""===e?'""':e);else if(t&&t.length||e&&e.length)if(null==t)r="was ".concat(t,", now contains ").concat(e.length," element(s)");else if(null==e)r="contained ".concat(t.length," element(s), now is ").concat(e);else if(0===t.length)r="was empty, now contains ".concat(e.length," elements");else if(0===e.length)r="contained ".concat(t.length," elements, now is empty");else{var i=e.filter((function(e){return!t.find((function(t){return c(e,t)}))})),a=t.filter((function(t){return!e.find((function(e){return c(t,e)}))}));i.length>10&&(i="".concat(i.length," element(s) added")),a.length>10&&(a="".concat(a.length," element(s) removed")),r={added:i,removed:a}}else r=e}return r},i=function(t){return"string"==typeof t?'"'.concat(t,'"'):t};return{init:function(n){var o,a;e=null!==(o=n.options)&&void 0!==o&&o.name?"[".concat(null===(a=n.options)||void 0===a?void 0:a.name,"]"):"";var c=n.state;t.group(e,"initialState"),Object.keys(c).forEach((function(t){r.log(t,":",i(c[t]))})),t.groupEnd()},destroy:null,effects:function(t,n,a,c){var u,s=null===(u=t.context)||void 0===u?void 0:u.args,l=[e,t.name.toString()];if(t.isAsync&&("preEffects"===t.type?l.push(c?"START":"CANCELLED"):"effects"===t.type?l.push("DONE"):l.push("FAILED")),null!=a||s&&0!==Object.keys(s).length?r.group.apply(r,l):r.log.apply(r,l),s&&Object.keys(s).length>0&&(r.group("Arguments"),s.forEach((function(t){r.log(t,":",i(t))})),r.groupEnd()),null!=a){if(r.groupCollapsed("Before"),null==n)r.log("was null");else Object.keys(n).forEach((function(t){r.log(t,":",i(n[t]))}));if(r.groupEnd(),r.groupCollapsed("After"),null==a)r.log("was null");else Object.keys(a).forEach((function(t){r.log(t,":",i(a[t]))}));if(r.groupEnd(),null!=a){r.group("Diff");var f=function(t,e){var r={};"development"===process.env.NODE_ENV&&(t&&Object.keys(t).forEach((function(n){if(e.hasOwnProperty(n)){var i=t[n],a=e[n],c=o(i,a);c&&(r[n]=c)}else r[n]="was deleted"})),Object.keys(e).forEach((function(n){if(null==t||!t.hasOwnProperty(n)){var i=e[n];r[n]=o(void 0,i)}})));return r}(n,a);Object.keys(f).forEach((function(t){return r.log(t,":",f[t])})),r.groupEnd()}}return r.groupEnd(),null}}}return{init:function(){},destroy:null,effects:function(){return null}}}}function O(t){return function(){var e=null,r={history:null,optimisticActions:{},shouldRecordHistory:!1},n=function(e){return(t||g.clone)(e)},o=function(t,e){return"".concat(t,"_").concat(e)};function i(t,e,o){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=r.shouldRecordHistory,c=r.history;if(a){null===c&&(r.history=[]);var u=n(o);delete u.state,delete u.s,delete u.abortSignal,u.error=o.err,u.err=o.err;var s={effectType:e,actionName:t,promiseId:o.promiseId,ctx:u,beforeEffectState:i?n(i):null};r.history.push(s)}}function a(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=r.optimisticActions,a=r.history,c=o(t,e);delete i[c];var u=Object.keys(i);if(0===u.length)r.history=null,r.shouldRecordHistory=!1;else{var s=void 0===n?a.findIndex((function(t){return o(t.actionName,t.promiseId)===c})):n;if(0===s){var l=a.slice(1).findIndex((function(t){return null!=t.beforeEffectState}))+1;a.splice(0,l)}else void 0===n&&(a[s].beforeEffectState=null)}}return{init:function(t){e=t},destroy:function(){e=null,r.history=null,r.optimisticActions={},r.shouldRecordHistory=!1},effects:function(t,n,c,u){var s=t.name,l=t.type,f=t.context,p=t.isAsync;if((null!=c&&m(e.actions[s])||"onPropsChange"===s||null!=e.actions[s][l])&&i(s,l,f,null),p){var d=e.actions[s];if(u&&null!=d.optimisticEffects&&"preEffects"===l){r.shouldRecordHistory=!0,r.optimisticActions[o(s,f.promiseId)]=!0;var h=c||n;return i(s,"optimisticEffects",f,h),{loading:!1,state:d.optimisticEffects(E(E({},f),{},{state:h,s:h}))}}if(null!=d.optimisticEffects&&"effects"===l)return a(s,f.promiseId),{loading:u,state:c};if(null!=d.optimisticEffects&&"errorEffects"===l)return{state:function(t,n){for(var o=r.history,i=o.findIndex((function(e){return"optimisticEffects"===e.effectType&&e.actionName===t&&e.promiseId===n})),c=o[i].beforeEffectState,u=i+1;u<o.length;u++){var s=o[u];s.beforeEffectState&&(s.beforeEffectState=c);var l=E(E({},s.ctx),{},{state:c,s:c});c="onPropsChange"===s.actionName?(Array.isArray(e.options.onPropsChange)?e.options.onPropsChange:[e.options.onPropsChange])[l.index].effects(l):m(e.actions[s.actionName])?e.actions[s.actionName](l):e.actions[s.actionName][s.effectType](l)}return a(t,n,i),c}(s,f.promiseId),loading:u}}return null}}}}function _(){return function(){var t,e,r;try{t=window.__REDUX_DEVTOOLS_EXTENSION__||window.top.__REDUX_DEVTOOLS_EXTENSION__}catch(t){}return t?{init:function(n){var o,i;(e=t.connect({name:null!==(o=null===(i=n.options)||void 0===i?void 0:i.name)&&void 0!==o?o:"StateDecorator"})).init(n.state);var a=null,c=n.state;r=e.subscribe((function(t){var e,r,o,i;if("DISPATCH"===t.type&&t.state&&"ROLLBACK"!==(null===(e=t.payload)||void 0===e?void 0:e.type)){var u=JSON.parse(t.state);n.setState(u)}else"COMMIT"===(null===(r=t.payload)||void 0===r?void 0:r.type)?a=n.state:"ROLLBACK"===(null===(o=t.payload)||void 0===o?void 0:o.type)?null!=a&&n.setState(a):"RESET"===(null===(i=t.payload)||void 0===i?void 0:i.type)&&n.setState(c)}))},effects:function(t,r,n){if(null!=n){var o=E({},t.context);delete o.a,delete o.s,delete o.p,delete o.res,delete o.err,delete o.ds,e.send({type:"".concat(t.name," ").concat(t.type),args:o.args,context:o},n)}return null},destroy:function(){r(),e=null}}:{init:function(){},destroy:null,effects:function(){return null}}}}export{_ as devtools,w as logDetailedEffects,b as logEffects,O as optimisticActions};
|
|
1
|
+
function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function e(t){var e={exports:{}};return t(e,e.exports),e.exports}var r=t(e((function(t){t.exports=function(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t},t.exports.default=t.exports,t.exports.__esModule=!0}))),n=e((function(t){function e(r){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?(t.exports=e=function(t){return typeof t},t.exports.default=t.exports,t.exports.__esModule=!0):(t.exports=e=function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.default=t.exports,t.exports.__esModule=!0),e(r)}t.exports=e,t.exports.default=t.exports,t.exports.__esModule=!0})),o=t(n),i=Array.isArray,u=Object.keys,c=Object.prototype.hasOwnProperty,s=function t(e,r){if(e===r)return!0;if(e&&r&&"object"==typeof e&&"object"==typeof r){var n,o,s,a=i(e),l=i(r);if(a&&l){if((o=e.length)!=r.length)return!1;for(n=o;0!=n--;)if(!t(e[n],r[n]))return!1;return!0}if(a!=l)return!1;var f=e instanceof Date,p=r instanceof Date;if(f!=p)return!1;if(f&&p)return e.getTime()==r.getTime();var d=e instanceof RegExp,y=r instanceof RegExp;if(d!=y)return!1;if(d&&y)return e.toString()==r.toString();var h=u(e);if((o=h.length)!==u(r).length)return!1;for(n=o;0!=n--;)if(!c.call(r,h[n]))return!1;for(n=o;0!=n--;)if(!t(e[s=h[n]],r[s]))return!1;return!0}return e!=e&&r!=r},a=e((function(t){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n},t.exports.default=t.exports,t.exports.__esModule=!0})),l=e((function(t){t.exports=function(t){if(Array.isArray(t))return a(t)},t.exports.default=t.exports,t.exports.__esModule=!0})),f=e((function(t){t.exports=function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)},t.exports.default=t.exports,t.exports.__esModule=!0})),p=e((function(t){t.exports=function(t,e){if(t){if("string"==typeof t)return a(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(t,e):void 0}},t.exports.default=t.exports,t.exports.__esModule=!0})),d=e((function(t){t.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},t.exports.default=t.exports,t.exports.__esModule=!0}));e((function(t){t.exports=function(t){return l(t)||f(t)||p(t)||d()},t.exports.default=t.exports,t.exports.__esModule=!0}));var y=e((function(t){t.exports=function(t){if(Array.isArray(t))return t},t.exports.default=t.exports,t.exports.__esModule=!0})),h=e((function(t){t.exports=function(t,e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var r=[],n=!0,o=!1,i=void 0;try{for(var u,c=t[Symbol.iterator]();!(n=(u=c.next()).done)&&(r.push(u.value),!e||r.length!==e);n=!0);}catch(t){o=!0,i=t}finally{try{n||null==c.return||c.return()}finally{if(o)throw i}}return r}},t.exports.default=t.exports,t.exports.__esModule=!0})),v=e((function(t){t.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},t.exports.default=t.exports,t.exports.__esModule=!0}));e((function(t){t.exports=function(t,e){return y(t)||h(t,e)||p(t,e)||v()},t.exports.default=t.exports,t.exports.__esModule=!0})),e((function(t){function e(t,e,r,n,o,i,u){try{var c=t[i](u),s=c.value}catch(t){return void r(t)}c.done?e(s):Promise.resolve(s).then(n,o)}t.exports=function(t){return function(){var r=this,n=arguments;return new Promise((function(o,i){var u=t.apply(r,n);function c(t){e(u,o,i,c,s,"next",t)}function s(t){e(u,o,i,c,s,"throw",t)}c(void 0)}))}},t.exports.default=t.exports,t.exports.__esModule=!0})),e((function(t){t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},t.exports.default=t.exports,t.exports.__esModule=!0}));var x=e((function(t){t.exports=function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t},t.exports.default=t.exports,t.exports.__esModule=!0})),g=e((function(t){function e(r,n){return t.exports=e=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},t.exports.default=t.exports,t.exports.__esModule=!0,e(r,n)}t.exports=e,t.exports.default=t.exports,t.exports.__esModule=!0}));e((function(t){t.exports=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&g(t,e)},t.exports.default=t.exports,t.exports.__esModule=!0})),e((function(t){var e=n.default;t.exports=function(t,r){return!r||"object"!==e(r)&&"function"!=typeof r?x(t):r},t.exports.default=t.exports,t.exports.__esModule=!0}));var m,b=e((function(t){function e(r){return t.exports=e=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},t.exports.default=t.exports,t.exports.__esModule=!0,e(r)}t.exports=e,t.exports.default=t.exports,t.exports.__esModule=!0})),_=e((function(t){t.exports=function(t){return-1!==Function.toString.call(t).indexOf("[native code]")},t.exports.default=t.exports,t.exports.__esModule=!0})),E=e((function(t){t.exports=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}},t.exports.default=t.exports,t.exports.__esModule=!0})),w=e((function(t){function e(r,n,o){return E()?(t.exports=e=Reflect.construct,t.exports.default=t.exports,t.exports.__esModule=!0):(t.exports=e=function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&g(o,r.prototype),o},t.exports.default=t.exports,t.exports.__esModule=!0),e.apply(null,arguments)}t.exports=e,t.exports.default=t.exports,t.exports.__esModule=!0}));e((function(t){function e(r){var n="function"==typeof Map?new Map:void 0;return t.exports=e=function(t){if(null===t||!_(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(t))return n.get(t);n.set(t,e)}function e(){return w(t,arguments,b(this).constructor)}return e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),g(e,t)},t.exports.default=t.exports,t.exports.__esModule=!0,e(r)}t.exports=e,t.exports.default=t.exports,t.exports.__esModule=!0})),e((function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",u=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function s(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{s({},"")}catch(t){s=function(t,e,r){return t[e]=r}}function a(t,e,r,n){var o=e&&e.prototype instanceof v?e:v,i=Object.create(o.prototype),u=new N(n||[]);return i._invoke=function(t,e,r){var n=f;return function(o,i){if(n===d)throw new Error("Generator is already running");if(n===y){if("throw"===o)throw i;return P()}for(r.method=o,r.arg=i;;){var u=r.delegate;if(u){var c=j(u,r);if(c){if(c===h)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===f)throw n=y,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=d;var s=l(t,e,r);if("normal"===s.type){if(n=r.done?y:p,s.arg===h)continue;return{value:s.arg,done:r.done}}"throw"===s.type&&(n=y,r.method="throw",r.arg=s.arg)}}}(t,r,u),i}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=a;var f="suspendedStart",p="suspendedYield",d="executing",y="completed",h={};function v(){}function x(){}function g(){}var m={};m[i]=function(){return this};var b=Object.getPrototypeOf,_=b&&b(b(M([])));_&&_!==r&&n.call(_,i)&&(m=_);var E=g.prototype=v.prototype=Object.create(m);function w(t){["next","throw","return"].forEach((function(e){s(t,e,(function(t){return this._invoke(e,t)}))}))}function O(t,e){function r(o,i,u,c){var s=l(t[o],t,i);if("throw"!==s.type){var a=s.arg,f=a.value;return f&&"object"==typeof f&&n.call(f,"__await")?e.resolve(f.__await).then((function(t){r("next",t,u,c)}),(function(t){r("throw",t,u,c)})):e.resolve(f).then((function(t){a.value=t,u(a)}),(function(t){return r("throw",t,u,c)}))}c(s.arg)}var o;this._invoke=function(t,n){function i(){return new e((function(e,o){r(t,n,e,o)}))}return o=o?o.then(i,i):i()}}function j(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,j(t,r),"throw"===r.method))return h;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var o=l(n,t.iterator,r.arg);if("throw"===o.type)return r.method="throw",r.arg=o.arg,r.delegate=null,h;var i=o.arg;return i?i.done?(r[t.resultName]=i.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,h):i:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,h)}function S(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function L(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(S,this),this.reset(!0)}function M(t){if(t){var r=t[i];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,u=function r(){for(;++o<t.length;)if(n.call(t,o))return r.value=t[o],r.done=!1,r;return r.value=e,r.done=!0,r};return u.next=u}}return{next:P}}function P(){return{value:e,done:!0}}return x.prototype=E.constructor=g,g.constructor=x,x.displayName=s(g,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===x||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,g):(t.__proto__=g,s(t,c,"GeneratorFunction")),t.prototype=Object.create(E),t},t.awrap=function(t){return{__await:t}},w(O.prototype),O.prototype[u]=function(){return this},t.AsyncIterator=O,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var u=new O(a(e,r,n,o),i);return t.isGeneratorFunction(r)?u:u.next().then((function(t){return t.done?t.value:u.next()}))},w(E),s(E,c,"Generator"),E[i]=function(){return this},E.toString=function(){return"[object Generator]"},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=M,N.prototype={constructor:N,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(L),!t)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=e)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var r=this;function o(n,o){return c.type="throw",c.arg=t,r.next=n,o&&(r.method="next",r.arg=e),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var u=this.tryEntries[i],c=u.completion;if("root"===u.tryLoc)return o("end");if(u.tryLoc<=this.prev){var s=n.call(u,"catchLoc"),a=n.call(u,"finallyLoc");if(s&&a){if(this.prev<u.catchLoc)return o(u.catchLoc,!0);if(this.prev<u.finallyLoc)return o(u.finallyLoc)}else if(s){if(this.prev<u.catchLoc)return o(u.catchLoc,!0)}else{if(!a)throw new Error("try statement without catch or finally");if(this.prev<u.finallyLoc)return o(u.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var u=i?i.completion:{};return u.type=t,u.arg=e,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(u)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),L(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;L(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:M(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),h}},t}(t.exports);try{regeneratorRuntime=e}catch(t){Function("r","regeneratorRuntime = r")(e)}})),function(t){t.REJECT="reject",t.IGNORE="ignore",t.KEEP_LAST="keepLast",t.KEEP_ALL="keepAll",t.PARALLEL="parallel",t.REUSE="reuse"}(m||(m={}));var O={clone:function(t){return JSON.parse(JSON.stringify(t))},comparator:function(t,e){if(Object.is(t,e))return!0;if("object"!==o(t)||null===t||"object"!==o(e)||null===e)return!1;if(t instanceof Set||e instanceof Set)return!1;var r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(var i=0;i<r.length;i++)if(!Object.prototype.hasOwnProperty.call(e,r[i])||!Object.is(t[r[i]],e[r[i]]))return!1;return!0},asyncErrorHandler:function(){},retryOnErrorFunction:function(t){return t instanceof TypeError},notifySuccess:void 0,notifyError:void 0,notifyWarning:void 0,getErrorMessage:void 0,defaultMiddlewares:[]};function j(t){return"function"==typeof t}function S(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function L(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?S(Object(n),!0).forEach((function(e){r(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):S(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function N(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:console.log,e=function(){var e=t,r="";return{init:function(t){if("development"===process.env.NODE_ENV||"test"===process.env.NODE_ENV){var n,o;r=null!==(n=t.options)&&void 0!==n&&n.name?"[".concat(null===(o=t.options)||void 0===o?void 0:o.name,"]"):"";var i=t.state;e(r,"initialState",i)}},destroy:null,effects:function(t,n,o,i){return"development"!==process.env.NODE_ENV&&"test"!==process.env.NODE_ENV||e(r,t.name,t.type,null===o?"no effect":o,t.isAsync?"preEffects"!==t.type||i?"loading: ".concat(i):"Promise cancelled":""),null}}};return e}function M(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:console;return function(){var e="",r=t;if("development"===process.env.NODE_ENV||"test"===process.env.NODE_ENV){var n=function(t,e){var r;if(e!==t){var n=o(null!=t?t:e);if("number"===n||"string"===n||"boolean"===n)r="".concat(t," => ").concat(""===e?'""':e);else if(t&&t.length||e&&e.length)if(null==t)r="was ".concat(t,", now contains ").concat(e.length," element(s)");else if(null==e)r="contained ".concat(t.length," element(s), now is ").concat(e);else if(0===t.length)r="was empty, now contains ".concat(e.length," elements");else if(0===e.length)r="contained ".concat(t.length," elements, now is empty");else{var i=e.filter((function(e){return!t.find((function(t){return s(e,t)}))})),u=t.filter((function(t){return!e.find((function(e){return s(t,e)}))}));i.length>10&&(i="".concat(i.length," element(s) added")),u.length>10&&(u="".concat(u.length," element(s) removed")),r={added:i,removed:u}}else r=e}return r},i=function(t){return"string"==typeof t?'"'.concat(t,'"'):t};return{init:function(n){var o,u;e=null!==(o=n.options)&&void 0!==o&&o.name?"[".concat(null===(u=n.options)||void 0===u?void 0:u.name,"]"):"";var c=n.state;t.group(e,"initialState"),Object.keys(c).forEach((function(t){r.log(t,":",i(c[t]))})),t.groupEnd()},destroy:null,effects:function(t,o,u,c){var s,a=null===(s=t.context)||void 0===s?void 0:s.args,l=[e,t.name.toString()];if(t.isAsync&&("preEffects"===t.type?l.push(c?"START":"CANCELLED"):"effects"===t.type?l.push("DONE"):l.push("FAILED")),null!=u||a&&0!==Object.keys(a).length?r.group.apply(r,l):r.log.apply(r,l),a&&Object.keys(a).length>0&&(r.group("Arguments"),a.forEach((function(t){r.log(t,":",i(t))})),r.groupEnd()),null!=u){if(r.groupCollapsed("Before"),null==o)r.log("was null");else Object.keys(o).forEach((function(t){r.log(t,":",i(o[t]))}));if(r.groupEnd(),r.groupCollapsed("After"),null==u)r.log("was null");else Object.keys(u).forEach((function(t){r.log(t,":",i(u[t]))}));if(r.groupEnd(),null!=u){r.group("Diff");var f=function(t,e){var r={};"development"===process.env.NODE_ENV&&(t&&Object.keys(t).forEach((function(o){if(e.hasOwnProperty(o)){var i=t[o],u=e[o],c=n(i,u);c&&(r[o]=c)}else r[o]="was deleted"})),Object.keys(e).forEach((function(o){if(null==t||!t.hasOwnProperty(o)){var i=e[o];r[o]=n(void 0,i)}})));return r}(o,u);Object.keys(f).forEach((function(t){return r.log(t,":",f[t])})),r.groupEnd()}}return r.groupEnd(),null}}}return{init:function(){},destroy:null,effects:function(){return null}}}}function P(t){return function(){var e=null,r={history:null,optimisticActions:{},shouldRecordHistory:!1},n=function(e){return(t||O.clone)(e)},o=function(t,e){return"".concat(t,"_").concat(e)};function i(t,e,o){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,u=r.shouldRecordHistory,c=r.history;if(u){null===c&&(r.history=[]);var s=n(o);delete s.state,delete s.s,delete s.abortSignal,s.error=o.err,s.err=o.err;var a={effectType:e,actionName:t,promiseId:o.promiseId,ctx:s,beforeEffectState:i?n(i):null};r.history.push(a)}}function u(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=r.optimisticActions,u=r.history,c=o(t,e);delete i[c];var s=Object.keys(i);if(0===s.length)r.history=null,r.shouldRecordHistory=!1;else{var a=void 0===n?u.findIndex((function(t){return o(t.actionName,t.promiseId)===c})):n;if(0===a){var l=u.slice(1).findIndex((function(t){return null!=t.beforeEffectState}))+1;u.splice(0,l)}else void 0===n&&(u[a].beforeEffectState=null)}}return{init:function(t){e=t},destroy:function(){e=null,r.history=null,r.optimisticActions={},r.shouldRecordHistory=!1},effects:function(t,n,c,s){var a=t.name,l=t.type,f=t.context,p=t.isAsync;if((null!=c&&j(e.actions[a])||"onPropsChange"===a||null!=e.actions[a][l])&&i(a,l,f,null),p){var d=e.actions[a];if(s&&null!=d.optimisticEffects&&"preEffects"===l){r.shouldRecordHistory=!0,r.optimisticActions[o(a,f.promiseId)]=!0;var y=c||n;return i(a,"optimisticEffects",f,y),{loading:!1,state:d.optimisticEffects(L(L({},f),{},{state:y,s:y}))}}if(null!=d.optimisticEffects&&"effects"===l)return u(a,f.promiseId),{loading:s,state:c};if(null!=d.optimisticEffects&&"errorEffects"===l)return{state:function(t,n){for(var o=r.history,i=o.findIndex((function(e){return"optimisticEffects"===e.effectType&&e.actionName===t&&e.promiseId===n})),c=o[i].beforeEffectState,s=i+1;s<o.length;s++){var a=o[s];a.beforeEffectState&&(a.beforeEffectState=c);var l=L(L({},a.ctx),{},{state:c,s:c});c="onPropsChange"===a.actionName?(Array.isArray(e.options.onPropsChange)?e.options.onPropsChange:[e.options.onPropsChange])[l.index].effects(l):j(e.actions[a.actionName])?e.actions[a.actionName](l):e.actions[a.actionName][a.effectType](l)}return u(t,n,i),c}(a,f.promiseId),loading:s}}return null}}}}function A(){return function(){var t,e,r;try{t=window.__REDUX_DEVTOOLS_EXTENSION__||window.top.__REDUX_DEVTOOLS_EXTENSION__}catch(t){}return t?{init:function(n){var o,i;(e=t.connect({name:null!==(o=null===(i=n.options)||void 0===i?void 0:i.name)&&void 0!==o?o:"StateDecorator"})).init(n.state);var u=null,c=n.state;r=e.subscribe((function(t){var e,r,o,i;if("DISPATCH"===t.type&&t.state&&"ROLLBACK"!==(null===(e=t.payload)||void 0===e?void 0:e.type)){var s=JSON.parse(t.state);n.setState(s)}else"COMMIT"===(null===(r=t.payload)||void 0===r?void 0:r.type)?u=n.state:"ROLLBACK"===(null===(o=t.payload)||void 0===o?void 0:o.type)?null!=u&&n.setState(u):"RESET"===(null===(i=t.payload)||void 0===i?void 0:i.type)&&n.setState(c)}))},effects:function(t,r,n){if(null!=n){var o=L({},t.context);delete o.a,delete o.s,delete o.p,delete o.res,delete o.err,delete o.ds,e.send({type:"".concat(t.name," ").concat(t.type),args:o.args,context:o},n)}return null},destroy:function(){r(),e=null}}:{init:function(){},destroy:null,effects:function(){return null}}}}export{A as devtools,M as logDetailedEffects,N as logEffects,P as optimisticActions};
|
|
2
2
|
//# sourceMappingURL=middlewares.es.js.map
|