state-decorator 7.0.0-beta.9-dev → 7.0.0-rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +55 -24
  2. package/development.d.ts +10 -0
  3. package/development.js +2 -0
  4. package/development.js.map +1 -0
  5. package/graph.d.ts +8 -0
  6. package/helpers.js +1 -174
  7. package/helpers.js.map +1 -1
  8. package/impl.d.ts +20 -32
  9. package/impl.js +1 -996
  10. package/impl.js.map +1 -1
  11. package/index.d.ts +10 -11
  12. package/index.js +1 -1044
  13. package/index.js.map +1 -1
  14. package/middlewares.d.ts +0 -23
  15. package/middlewares.js +1 -526
  16. package/middlewares.js.map +1 -1
  17. package/package.json +2 -2
  18. package/shallow.d.ts +0 -14
  19. package/test.d.ts +7 -21
  20. package/test.js +1 -358
  21. package/test.js.map +1 -1
  22. package/types.d.ts +73 -72
  23. package/v5.d.ts +5 -18
  24. package/v5.js +1 -322
  25. package/v5.js.map +1 -1
  26. package/v5_test.d.ts +4 -17
  27. package/v5_test.js +1 -416
  28. package/v5_test.js.map +1 -1
  29. package/v5_types.d.ts +15 -29
  30. package/v6.d.ts +7 -3
  31. package/v6.js +1 -120
  32. package/v6.js.map +1 -1
  33. package/es/helpers.d.ts +0 -66
  34. package/es/helpers.js +0 -163
  35. package/es/helpers.js.map +0 -1
  36. package/es/impl.d.ts +0 -209
  37. package/es/impl.js +0 -964
  38. package/es/impl.js.map +0 -1
  39. package/es/index.d.ts +0 -164
  40. package/es/index.js +0 -1014
  41. package/es/index.js.map +0 -1
  42. package/es/middlewares.d.ts +0 -26
  43. package/es/middlewares.js +0 -520
  44. package/es/middlewares.js.map +0 -1
  45. package/es/shallow.d.ts +0 -15
  46. package/es/test.d.ts +0 -136
  47. package/es/test.js +0 -350
  48. package/es/test.js.map +0 -1
  49. package/es/types.d.ts +0 -381
  50. package/es/v5.d.ts +0 -58
  51. package/es/v5.js +0 -302
  52. package/es/v5.js.map +0 -1
  53. package/es/v5_test.d.ts +0 -70
  54. package/es/v5_test.js +0 -393
  55. package/es/v5_test.js.map +0 -1
  56. package/es/v5_types.d.ts +0 -227
  57. package/es/v6.d.ts +0 -17
  58. package/es/v6.js +0 -97
  59. package/es/v6.js.map +0 -1
package/es/impl.js DELETED
@@ -1,964 +0,0 @@
1
- /*! *****************************************************************************
2
- Copyright (c) Microsoft Corporation.
3
-
4
- Permission to use, copy, modify, and/or distribute this software for any
5
- purpose with or without fee is hereby granted.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
- PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */
15
- /* global Reflect, Promise */
16
-
17
- var extendStatics = function(d, b) {
18
- extendStatics = Object.setPrototypeOf ||
19
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
21
- return extendStatics(d, b);
22
- };
23
-
24
- function __extends(d, b) {
25
- if (typeof b !== "function" && b !== null)
26
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
27
- extendStatics(d, b);
28
- function __() { this.constructor = d; }
29
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30
- }
31
-
32
- var __assign = function() {
33
- __assign = Object.assign || function __assign(t) {
34
- for (var s, i = 1, n = arguments.length; i < n; i++) {
35
- s = arguments[i];
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
37
- }
38
- return t;
39
- };
40
- return __assign.apply(this, arguments);
41
- };
42
-
43
- function __awaiter(thisArg, _arguments, P, generator) {
44
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
- return new (P || (P = Promise))(function (resolve, reject) {
46
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
47
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
48
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
49
- step((generator = generator.apply(thisArg, _arguments || [])).next());
50
- });
51
- }
52
-
53
- function __generator(thisArg, body) {
54
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
55
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
56
- function verb(n) { return function (v) { return step([n, v]); }; }
57
- function step(op) {
58
- if (f) throw new TypeError("Generator is already executing.");
59
- while (_) try {
60
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
61
- if (y = 0, t) op = [op[0] & 2, t.value];
62
- switch (op[0]) {
63
- case 0: case 1: t = op; break;
64
- case 4: _.label++; return { value: op[1], done: false };
65
- case 5: _.label++; y = op[1]; op = [0]; continue;
66
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
67
- default:
68
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
69
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
70
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
71
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
72
- if (t[2]) _.ops.pop();
73
- _.trys.pop(); continue;
74
- }
75
- op = body.call(thisArg, _);
76
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
77
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
78
- }
79
- }
80
-
81
- function __spreadArray(to, from, pack) {
82
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
83
- if (ar || !(i in from)) {
84
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
85
- ar[i] = from[i];
86
- }
87
- }
88
- return to.concat(ar || Array.prototype.slice.call(from));
89
- }
90
-
91
- /*! *****************************************************************************
92
- Copyright (c) GlobalSport SAS.
93
-
94
- Permission to use, copy, modify, and/or distribute this software for any
95
- purpose with or without fee is hereby granted.
96
-
97
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
98
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
99
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
100
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
101
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
102
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
103
- PERFORMANCE OF THIS SOFTWARE.
104
- ***************************************************************************** */
105
- // @ts-nocheck
106
- // SOURCE https://github.com/pmndrs/zustand/blob/master/src/shallow.ts
107
- function shallow(objA, objB) {
108
- if (Object.is(objA, objB)) {
109
- return true;
110
- }
111
- if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
112
- return false;
113
- }
114
- if (objA instanceof Set || objB instanceof Set) {
115
- // if they are equal, first condition is true
116
- return false;
117
- }
118
- var keysA = Object.keys(objA);
119
- var keysB = Object.keys(objB);
120
- if (keysA.length !== keysB.length) {
121
- return false;
122
- }
123
- for (var i = 0; i < keysA.length; i++) {
124
- if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||
125
- !Object.is(objA[keysA[i]], objB[keysA[i]])) {
126
- return false;
127
- }
128
- }
129
- return true;
130
- }
131
-
132
- /*! *****************************************************************************
133
- Copyright (c) GlobalSport SAS.
134
-
135
- Permission to use, copy, modify, and/or distribute this software for any
136
- purpose with or without fee is hereby granted.
137
-
138
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
139
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
140
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
141
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
142
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
143
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
144
- PERFORMANCE OF THIS SOFTWARE.
145
- ***************************************************************************** */
146
- /**
147
- * The State decorator can manage only one asynchronous action of same name at a time.
148
- * This enum is enumertaing all the policies in such case.
149
- */
150
- var ConflictPolicy;
151
- (function (ConflictPolicy) {
152
- /**
153
- * Reject the promise.
154
- */
155
- ConflictPolicy["REJECT"] = "reject";
156
- /**
157
- * Return a resolved promise with no result.
158
- */
159
- ConflictPolicy["IGNORE"] = "ignore";
160
- /**
161
- * Execute only the last call that conflicts after the one ongoing.
162
- */
163
- ConflictPolicy["KEEP_LAST"] = "keepLast";
164
- /**
165
- * Execute all calls one after another.
166
- */
167
- ConflictPolicy["KEEP_ALL"] = "keepAll";
168
- /**
169
- * Execute all calls one after another.
170
- * @see getPromiseId
171
- */
172
- ConflictPolicy["PARALLEL"] = "parallel";
173
- /**
174
- * Reuse the ongoing promise if any and if possible (same arguments). Only for GET requests!
175
- */
176
- ConflictPolicy["REUSE"] = "reuse";
177
- })(ConflictPolicy || (ConflictPolicy = {}));
178
-
179
- /*! *****************************************************************************
180
- Copyright (c) GlobalSport SAS.
181
-
182
- Permission to use, copy, modify, and/or distribute this software for any
183
- purpose with or without fee is hereby granted.
184
-
185
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
186
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
187
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
188
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
189
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
190
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
191
- PERFORMANCE OF THIS SOFTWARE.
192
- ***************************************************************************** */
193
- var EffectError = /** @class */ (function (_super) {
194
- __extends(EffectError, _super);
195
- function EffectError(source, initialError) {
196
- var _this = _super.call(this, source.message) || this;
197
- _this.source = source;
198
- _this.initialError = initialError;
199
- Object.setPrototypeOf(_this, EffectError.prototype);
200
- return _this;
201
- }
202
- return EffectError;
203
- }(Error));
204
- /** @internal */
205
- var globalConfig = {
206
- clone: defaultCloneFunc,
207
- comparator: shallow,
208
- asyncErrorHandler: function () { },
209
- retryOnErrorFunction: function (error) { return error instanceof TypeError; },
210
- notifySuccess: undefined,
211
- notifyError: undefined,
212
- notifyWarning: undefined,
213
- getErrorMessage: undefined,
214
- defaultMiddlewares: [],
215
- };
216
- function setGlobalConfig(overrideConfig) {
217
- var keys = Object.keys(overrideConfig);
218
- keys.forEach(function (k) {
219
- if (overrideConfig[k] != null) {
220
- globalConfig[k] = overrideConfig[k];
221
- }
222
- });
223
- }
224
- function defaultCloneFunc(src) {
225
- return JSON.parse(JSON.stringify(src));
226
- }
227
- function clone(obj) {
228
- try {
229
- return globalConfig.clone(obj);
230
- }
231
- catch (e) {
232
- var msg = 'StateDecorator: Cannot clone object. Set setCloneFunction on global global with another implementation like lodash/cloneDeep.';
233
- if (process.env.NODE_ENV === 'development') {
234
- console.error(msg);
235
- console.error(e.toString());
236
- }
237
- throw new Error(msg);
238
- }
239
- }
240
- // ----------------------------
241
- //
242
- // TYPE GUARDS
243
- //
244
- // -----------------------------
245
- /**
246
- * Type guard function to test if an action is a asynchronous action.
247
- */
248
- function isAsyncAction(action) {
249
- return (!(action instanceof Function) && (action.hasOwnProperty('getPromise') || action.hasOwnProperty('getGetPromise')));
250
- }
251
- /**
252
- * Type guard function to test if an action is a synchronous action.
253
- */
254
- function isSimpleSyncAction(action) {
255
- return typeof action === 'function';
256
- }
257
- /**
258
- * Type guard function to test if an action is a synchronous action.
259
- */
260
- function isSyncAction(action) {
261
- return (typeof action !== 'function' && !action.hasOwnProperty('getPromise') && !action.hasOwnProperty('getGetPromise'));
262
- }
263
- function isAsyncGetPromiseAction(action) {
264
- return typeof action !== 'function' && action.hasOwnProperty('getPromise') && !action.hasOwnProperty('getGetPromise');
265
- }
266
- function isAsyncGetPromiseGetAction(action) {
267
- return typeof action !== 'function' && !action.hasOwnProperty('getPromise') && action.hasOwnProperty('getGetPromise');
268
- }
269
- /** @internal */
270
- function computeAsyncActionInput(action) {
271
- if (isAsyncGetPromiseGetAction(action)) {
272
- return __assign(__assign({}, action), { getPromise: action.getGetPromise, retryCount: 3, conflictPolicy: ConflictPolicy.REUSE });
273
- }
274
- return action;
275
- }
276
- /** @internal */
277
- function buildLoadingMap(source, actionName, promiseId, loading) {
278
- var _a, _b, _c, _d;
279
- if (loading) {
280
- return __assign(__assign({}, source), (_a = {}, _a[actionName] = __assign(__assign({}, (source[actionName] || {})), (_b = {}, _b[promiseId] = loading, _b)), _a));
281
- }
282
- var res = __assign(__assign({}, source), (_c = {}, _c[actionName] = __assign(__assign({}, source[actionName]), (_d = {}, _d[promiseId] = false, _d)), _c));
283
- return res;
284
- }
285
- /** @internal */
286
- function updateErrorMap(source, actionName, promiseId, error) {
287
- var _a, _b, _c, _d;
288
- if (error) {
289
- return __assign(__assign({}, source), (_a = {}, _a[actionName] = __assign(__assign({}, (source[actionName] || {})), (_b = {}, _b[promiseId] = error, _b)), _a));
290
- }
291
- var res = __assign(__assign({}, source), (_c = {}, _c[actionName] = __assign(__assign({}, source[actionName]), (_d = {}, _d[promiseId] = undefined, _d)), _c));
292
- return res;
293
- }
294
- var ParallelActionError = /** @class */ (function (_super) {
295
- __extends(ParallelActionError, _super);
296
- function ParallelActionError(promiseIds) {
297
- var _this = _super.call(this, 'Error') || this;
298
- _this.promiseIds = promiseIds;
299
- Object.setPrototypeOf(_this, ParallelActionError.prototype);
300
- return _this;
301
- }
302
- return ParallelActionError;
303
- }(Error));
304
- function buildErrorMap(map) {
305
- var keys = Object.keys(map);
306
- return keys.reduce(function (acc, actionName) {
307
- var subMap = map[actionName];
308
- // DEFAULT_PROMISE_ID is set internally
309
- // if defines it means that action is NOT run in parallel
310
- if (subMap[DEFAULT_PROMISE_ID] == null) ;
311
- else if (subMap[DEFAULT_PROMISE_ID]) {
312
- acc[actionName] = subMap[DEFAULT_PROMISE_ID];
313
- }
314
- else {
315
- var res = Object.keys(subMap).reduce(function (acc, promiseId) {
316
- if (subMap[promiseId] != null) {
317
- acc.hasErr = true;
318
- acc.map[promiseId] = subMap[promiseId];
319
- }
320
- return acc;
321
- }, { hasErr: false, map: {} });
322
- if (res.hasErr) {
323
- acc[actionName] = new ParallelActionError(res.map);
324
- }
325
- }
326
- return acc;
327
- }, {});
328
- }
329
- /** @internal */
330
- function retryPromiseDecorator(promiseProvider, maxCalls, delay, isRetryError) {
331
- if (maxCalls === void 0) { maxCalls = 1; }
332
- if (delay === void 0) { delay = 1000; }
333
- if (isRetryError === void 0) { isRetryError = function () { return true; }; }
334
- if (maxCalls === 1) {
335
- return promiseProvider;
336
- }
337
- return function (ctx) {
338
- function call(callCount, p) {
339
- return __awaiter(this, void 0, void 0, function () {
340
- return __generator(this, function (_a) {
341
- if (p === null) {
342
- return [2 /*return*/, null];
343
- }
344
- return [2 /*return*/, p.catch(function (e) {
345
- if (isRetryError(e)) {
346
- if (callCount === maxCalls) {
347
- return Promise.reject(e);
348
- }
349
- return new Promise(function (resolve, reject) {
350
- setTimeout(function () {
351
- var p = promiseProvider(ctx);
352
- call(callCount + 1, p)
353
- .then(resolve)
354
- .catch(reject);
355
- }, delay * callCount);
356
- });
357
- }
358
- return Promise.reject(e);
359
- })];
360
- });
361
- });
362
- }
363
- var initialPromise = promiseProvider(ctx);
364
- if (initialPromise === null) {
365
- return null;
366
- }
367
- return call(1, initialPromise);
368
- };
369
- }
370
- /** @internal */
371
- function createRef(init) {
372
- if (init === void 0) { init = null; }
373
- return {
374
- current: init,
375
- };
376
- }
377
- // =============================
378
- //
379
- // ACTION DECORATORS
380
- //
381
- // =============================
382
- /** @internal */
383
- function buildInvocationContextBase(stateRef, derivedStateRef, propsRef) {
384
- var _a, _b;
385
- return {
386
- state: stateRef.current,
387
- s: stateRef.current,
388
- ds: (_a = derivedStateRef === null || derivedStateRef === void 0 ? void 0 : derivedStateRef.current) === null || _a === void 0 ? void 0 : _a.state,
389
- derived: (_b = derivedStateRef === null || derivedStateRef === void 0 ? void 0 : derivedStateRef.current) === null || _b === void 0 ? void 0 : _b.state,
390
- props: propsRef.current,
391
- p: propsRef.current,
392
- };
393
- }
394
- /** @internal */
395
- function buildOnMountInvocationContext(stateRef, derivedStateRef, propsRef, actionsRef) {
396
- return addContextActions(buildInvocationContextBase(stateRef, derivedStateRef, propsRef), actionsRef);
397
- }
398
- /** @internal */
399
- function buildOnUnMountInvocationContext(stateRef, derivedStateRef, propsRef, abortedActions) {
400
- return __assign(__assign({}, buildInvocationContextBase(stateRef, derivedStateRef, propsRef)), { abortedActions: abortedActions });
401
- }
402
- /** @internal */
403
- function buildOnPropChangeEffects(stateRef, derivedStateRef, propsRef, indices, index, isInit, getInitialState) {
404
- var res = buildInvocationContextBase(stateRef, derivedStateRef, propsRef);
405
- res.indices = indices;
406
- res.index = index;
407
- res.isInit = isInit;
408
- res.getInitialState =
409
- typeof getInitialState === 'function' ? getInitialState : function () { return getInitialState; };
410
- return res;
411
- }
412
- /** @internal */
413
- function buildInvocationContext(stateRef, derivedStateRef, propsRef, args, promiseId) {
414
- var res = buildInvocationContextBase(stateRef, derivedStateRef, propsRef);
415
- res.args = args;
416
- if (promiseId) {
417
- res.promiseId = promiseId;
418
- }
419
- return res;
420
- }
421
- /** @internal */
422
- function buildEffectsInvocationContext(stateRef, derivedStateRef, propsRef, args, result, promiseId) {
423
- var res = buildInvocationContext(stateRef, derivedStateRef, propsRef, args, promiseId);
424
- res.result = result;
425
- res.res = result;
426
- return res;
427
- }
428
- /** @internal */
429
- function buildErrorEffectsInvocationContext(stateRef, derivedStateRef, propsRef, args, error, promiseId) {
430
- var res = buildInvocationContext(stateRef, derivedStateRef, propsRef, args, promiseId);
431
- res.error = error;
432
- res.err = error;
433
- return res;
434
- }
435
- /** @internal */
436
- function buildPromiseActionContext(stateRef, derivedStateRef, propsRef, args, actionsRef, abortSignal, promiseId) {
437
- var res = addContextActions(buildInvocationContext(stateRef, derivedStateRef, propsRef, args, promiseId), actionsRef);
438
- res.abortSignal = abortSignal;
439
- return res;
440
- }
441
- /** @internal */
442
- function addStateToContext(ctx, stateRef) {
443
- var newCtx = ctx;
444
- newCtx.state = stateRef.current;
445
- newCtx.s = stateRef.current;
446
- return newCtx;
447
- }
448
- /** @internal */
449
- function addContextActions(ctx, actionsRef) {
450
- var newCtx = ctx;
451
- newCtx.actions = actionsRef.current;
452
- newCtx.a = actionsRef.current;
453
- return newCtx;
454
- }
455
- /** @internal */
456
- function addSideEffectsContext(ctx, stateRef, derivedStateRef, actionsRef, notifyWarning, clearError) {
457
- var _a;
458
- var res = addContextActions(ctx, actionsRef);
459
- addStateToContext(ctx, stateRef);
460
- var ds = (_a = derivedStateRef === null || derivedStateRef === void 0 ? void 0 : derivedStateRef.current) === null || _a === void 0 ? void 0 : _a.state;
461
- res.derived = ds;
462
- res.ds = ds;
463
- res.notifyWarning = notifyWarning;
464
- res.clearError = clearError;
465
- return res;
466
- }
467
- function notInitWarning(actionName) {
468
- if (process.env.NODE_ENV === 'development') {
469
- console.warn("[state-decorator] ".concat(actionName, " action was called while store is not initialized or destroyed, this is probably a leak"));
470
- }
471
- }
472
- function mergeState(stateRef, newState) {
473
- return newState == null ? null : __assign(__assign({}, stateRef.current), newState);
474
- }
475
- /** @internal */
476
- function decorateSimpleSyncAction(actionName, action, stateRef, derivedStateRef, propsRef, initializedRef, setState) {
477
- return function () {
478
- var args = [];
479
- for (var _i = 0; _i < arguments.length; _i++) {
480
- args[_i] = arguments[_i];
481
- }
482
- // store was destroyed
483
- if (!initializedRef.current) {
484
- notInitWarning(actionName);
485
- return;
486
- }
487
- var ctx = buildInvocationContext(stateRef, derivedStateRef, propsRef, args);
488
- var newState = mergeState(stateRef, action(ctx));
489
- setState(newState, null, actionName, 'effects', false, ctx, false);
490
- };
491
- }
492
- /** @internal */
493
- function executeSyncActionImpl(actionName, action, stateRef, derivedStateRef, propsRef, actionsRef, timeoutMap, options, setState, clearError, args) {
494
- var _a;
495
- var ctx = buildEffectsInvocationContext(stateRef, derivedStateRef, propsRef, args, undefined);
496
- var actionDropped = false;
497
- if (action.effects != null) {
498
- var newState = mergeState(stateRef, action.effects(ctx));
499
- if (newState === null) {
500
- actionDropped = true;
501
- }
502
- else {
503
- setState(newState, undefined, actionName, 'effects', false, ctx, false);
504
- }
505
- }
506
- if (!actionDropped) {
507
- if (action.debounceSideEffectsTimeout > 0) {
508
- var timeout = timeoutMap.current[actionName];
509
- if (timeout) {
510
- clearTimeout(timeout);
511
- }
512
- timeoutMap.current[actionName] = setTimeout(function () {
513
- var _a;
514
- (_a = action.sideEffects) === null || _a === void 0 ? void 0 : _a.call(action, addSideEffectsContext(ctx, stateRef, derivedStateRef, actionsRef, options.notifyWarning, clearError));
515
- delete timeoutMap.current[actionName];
516
- }, action.debounceSideEffectsTimeout);
517
- }
518
- else {
519
- (_a = action.sideEffects) === null || _a === void 0 ? void 0 : _a.call(action, addSideEffectsContext(ctx, stateRef, derivedStateRef, actionsRef, options.notifyWarning, clearError));
520
- }
521
- }
522
- }
523
- /** @internal */
524
- function decorateSyncAction(actionName, action, stateRef, derivedStateRef, propsRef, actionsRef, initializedRef, timeoutMap, options, setState, clearError) {
525
- return function () {
526
- var args = [];
527
- for (var _i = 0; _i < arguments.length; _i++) {
528
- args[_i] = arguments[_i];
529
- }
530
- // store was destroyed
531
- if (!initializedRef.current) {
532
- notInitWarning(actionName);
533
- return;
534
- }
535
- if (action.debounceTimeout) {
536
- var timeout = timeoutMap.current[actionName];
537
- if (timeout) {
538
- clearTimeout(timeout);
539
- }
540
- timeoutMap.current[actionName] = setTimeout(function () {
541
- delete timeoutMap.current[actionName];
542
- executeSyncActionImpl(actionName, action, stateRef, derivedStateRef, propsRef, actionsRef, timeoutMap, options, setState, clearError, args);
543
- }, action.debounceTimeout);
544
- }
545
- else {
546
- executeSyncActionImpl(actionName, action, stateRef, derivedStateRef, propsRef, actionsRef, timeoutMap, options, setState, clearError, args);
547
- }
548
- };
549
- }
550
- function processPromiseSuccess(context, promiseId, promiseResult, args) {
551
- var action = context.action, stateRef = context.stateRef, derivedStateRef = context.derivedStateRef, propsRef = context.propsRef, promisesRef = context.promisesRef, actionsRef = context.actionsRef, loadingMapRef = context.loadingParallelMapRef, conflictActionsRef = context.conflictActionsRef, actionName = context.actionName, options = context.options, setState = context.setState, clearError = context.clearError;
552
- // store was destroyed
553
- if (!context.initializedRef.current) {
554
- return void 0;
555
- }
556
- var newState = null;
557
- var ctx = buildEffectsInvocationContext(stateRef, derivedStateRef, propsRef, args, promiseResult, promiseId);
558
- if (action.effects) {
559
- try {
560
- newState = mergeState(stateRef, action.effects(ctx));
561
- }
562
- catch (e) {
563
- return Promise.reject(new EffectError(e));
564
- }
565
- }
566
- setState(newState, buildLoadingMap(loadingMapRef.current, actionName, promiseId, false), actionName, 'effects', true, ctx, false);
567
- var notifySuccess = options.notifySuccess || globalConfig.notifySuccess;
568
- if (notifySuccess) {
569
- var msg = void 0;
570
- if (action.getSuccessMessage) {
571
- msg = action.getSuccessMessage(ctx);
572
- }
573
- if (msg) {
574
- notifySuccess(msg);
575
- }
576
- }
577
- delete promisesRef.current[actionName][promiseId];
578
- if (action.sideEffects) {
579
- action.sideEffects(addSideEffectsContext(ctx, stateRef, derivedStateRef, actionsRef, globalConfig.notifyWarning, clearError));
580
- }
581
- processNextConflictAction(actionName, actionsRef.current, conflictActionsRef.current);
582
- return promiseResult;
583
- }
584
- function processPromiseFailed(context, promiseId, err, args) {
585
- var action = context.action, stateRef = context.stateRef, derivedStateRef = context.derivedStateRef, propsRef = context.propsRef, actionsRef = context.actionsRef, loadingMapRef = context.loadingParallelMapRef, errorMapRef = context.errorMapRef, promisesRef = context.promisesRef, conflictActionsRef = context.conflictActionsRef, actionName = context.actionName, options = context.options, clearError = context.clearError, setState = context.setState;
586
- // store was killed;
587
- if (!context.initializedRef.current) {
588
- return void 0;
589
- }
590
- var newState = null;
591
- var error = err;
592
- var ctx = buildErrorEffectsInvocationContext(stateRef, derivedStateRef, propsRef, args, error, promiseId);
593
- if (action.errorEffects) {
594
- try {
595
- newState = mergeState(stateRef, action.errorEffects(ctx));
596
- }
597
- catch (e) {
598
- error = new EffectError(e, err);
599
- }
600
- }
601
- // do not trigger a setState by itself because loading state will trigger a set anyway...
602
- errorMapRef.current = updateErrorMap(errorMapRef.current, actionName, promiseId, error);
603
- setState(newState, buildLoadingMap(loadingMapRef.current, actionName, promiseId, false), actionName, 'errorEffects', true, ctx, false);
604
- var errorHandled = false;
605
- if (newState != null || action.errorSideEffects || action.isErrorManaged || options.isErrorManaged) {
606
- errorHandled = true;
607
- }
608
- var notifyError = options.notifyError || globalConfig.notifyError;
609
- if (notifyError) {
610
- var msg = void 0;
611
- if (action.getErrorMessage) {
612
- msg = action.getErrorMessage(ctx);
613
- }
614
- // do not trigger a default error message if the error is already managed by error effects
615
- if (msg === undefined && !errorHandled && globalConfig.getErrorMessage) {
616
- msg = globalConfig.getErrorMessage(error);
617
- }
618
- if (msg) {
619
- errorHandled = true;
620
- notifyError(msg);
621
- }
622
- }
623
- globalConfig.asyncErrorHandler(error, errorHandled || action.rejectPromiseOnError, stateRef.current, propsRef.current, actionName, args);
624
- delete promisesRef.current[actionName][promiseId];
625
- if (action.errorSideEffects) {
626
- action.errorSideEffects(addSideEffectsContext(ctx, stateRef, derivedStateRef, actionsRef, globalConfig.notifyWarning, clearError));
627
- }
628
- processNextConflictAction(actionName, actionsRef.current, conflictActionsRef.current);
629
- var result = !errorHandled || action.rejectPromiseOnError ? Promise.reject(error) : Promise.resolve();
630
- return result;
631
- }
632
- /** @internal */
633
- function decorateAsyncAction(context) {
634
- var action = context.action, stateRef = context.stateRef, derivedStateRef = context.derivedStateRef, propsRef = context.propsRef, actionsRef = context.actionsRef, promisesRef = context.promisesRef, loadingMapRef = context.loadingParallelMapRef, errorMapRef = context.errorMapRef, initializedRef = context.initializedRef, conflictActionsRef = context.conflictActionsRef, actionName = context.actionName, setState = context.setState;
635
- return function () {
636
- var _a;
637
- var _b, _c;
638
- var args = [];
639
- for (var _i = 0; _i < arguments.length; _i++) {
640
- args[_i] = arguments[_i];
641
- }
642
- if (!initializedRef.current) {
643
- notInitWarning(actionName);
644
- return null;
645
- }
646
- var promises = promisesRef.current;
647
- var _d = action.conflictPolicy, conflictPolicy = _d === void 0 ? ConflictPolicy.KEEP_ALL : _d;
648
- var isParallel = conflictPolicy === ConflictPolicy.PARALLEL;
649
- var promiseId = null;
650
- if (isParallel) {
651
- if (!action.getPromiseId) {
652
- throw new Error('If conflict policy is set to ConflictPolicy.PARALLEL, getPromiseId must be set and return a string.');
653
- }
654
- promiseId = action.getPromiseId.apply(action, args);
655
- }
656
- else {
657
- promiseId = DEFAULT_PROMISE_ID;
658
- }
659
- if (!isParallel && ((_b = promises[actionName]) === null || _b === void 0 ? void 0 : _b[promiseId])) {
660
- return handleConflictingAction(promises, conflictActionsRef.current, actionName, conflictPolicy, args);
661
- }
662
- var newState = null;
663
- var hasChanged = false;
664
- var ctx = buildInvocationContext(stateRef, derivedStateRef, propsRef, args, promiseId);
665
- if (action.preEffects) {
666
- try {
667
- newState = mergeState(stateRef, action.preEffects(ctx));
668
- }
669
- catch (error) {
670
- globalConfig.asyncErrorHandler(new EffectError(error), false, stateRef.current, propsRef.current, actionName, args);
671
- return Promise.reject(new EffectError(error));
672
- }
673
- // apply internal state change for calls to other actions in the getPromise
674
- if (newState) {
675
- hasChanged = true;
676
- stateRef.current = newState;
677
- }
678
- }
679
- var abortable = action.abortable, retryCount = action.retryCount, retryDelaySeed = action.retryDelaySeed, isTriggerRetryError = action.isTriggerRetryError;
680
- var abortController = abortable && window.AbortController ? new AbortController() : null;
681
- var promiseProvider = retryPromiseDecorator(action.getPromise, retryCount ? 1 + retryCount : 1, retryDelaySeed, isTriggerRetryError || globalConfig.retryOnErrorFunction);
682
- var p = (_c = promiseProvider(buildPromiseActionContext(stateRef, derivedStateRef, propsRef, args, actionsRef, abortController === null || abortController === void 0 ? void 0 : abortController.signal))) === null || _c === void 0 ? void 0 : _c.then(function (promiseResult) { return processPromiseSuccess(context, promiseId, promiseResult, args); }).catch(function (error) { return processPromiseFailed(context, promiseId, error, args); });
683
- if (p != null) {
684
- promises[actionName] = __assign(__assign({}, (promises[actionName] || {})), (_a = {}, _a[promiseId || DEFAULT_PROMISE_ID] = {
685
- abortController: abortController,
686
- promise: p,
687
- refArgs: conflictPolicy === ConflictPolicy.REUSE && args.length > 0 ? __spreadArray([], args, true) : [],
688
- }, _a));
689
- }
690
- errorMapRef.current = updateErrorMap(errorMapRef.current, actionName, promiseId, null);
691
- setState(p == null && !hasChanged ? undefined : stateRef.current, p == null ? undefined : buildLoadingMap(loadingMapRef.current, actionName, promiseId, true), actionName, 'preEffects', true, ctx, false);
692
- return p;
693
- };
694
- }
695
- /** @internal */
696
- function isLoadingImpl(loadingMap) {
697
- var props = [];
698
- for (var _i = 1; _i < arguments.length; _i++) {
699
- props[_i - 1] = arguments[_i];
700
- }
701
- return props.some(function (propIn) {
702
- var _a;
703
- var actionName = null;
704
- var promiseId = DEFAULT_PROMISE_ID;
705
- if (Array.isArray(propIn)) {
706
- actionName = propIn[0], _a = propIn[1], promiseId = _a === void 0 ? DEFAULT_PROMISE_ID : _a;
707
- }
708
- else {
709
- actionName = propIn;
710
- }
711
- var res = loadingMap[actionName];
712
- if (res == null) {
713
- return false;
714
- }
715
- if (res[promiseId] != null) {
716
- return res[promiseId];
717
- }
718
- return false;
719
- });
720
- }
721
- // ------------------------------
722
- //
723
- // Conflict management
724
- //
725
- // ------------------------------
726
- var DEFAULT_PROMISE_ID = '__def__';
727
- /** @internal */
728
- function areSameArgs(args1, args2) {
729
- if (args1.length !== args2.length) {
730
- return false;
731
- }
732
- return args1.findIndex(function (value, index) { return args2[index] !== value; }) === -1;
733
- }
734
- /**
735
- * Handles a conflicting action depending on the action conflict policy.
736
- */
737
- /** @internal */
738
- function handleConflictingAction(promises, conflictActions, actionName, conflictPolicy, args) {
739
- var policy = conflictPolicy;
740
- if (policy === ConflictPolicy.REUSE) {
741
- // use default because action cannot be parallel
742
- if (areSameArgs(promises[actionName][DEFAULT_PROMISE_ID].refArgs, args)) {
743
- return promises[actionName][DEFAULT_PROMISE_ID].promise;
744
- } // else
745
- policy = ConflictPolicy.KEEP_ALL;
746
- }
747
- return new Promise(function (resolve, reject) {
748
- var futureAction = {
749
- resolve: resolve,
750
- reject: reject,
751
- args: clone(args),
752
- timestamp: Date.now(),
753
- };
754
- switch (policy) {
755
- case ConflictPolicy.IGNORE:
756
- resolve(void 0);
757
- break;
758
- case ConflictPolicy.REJECT:
759
- reject(new Error("An asynchronous action ".concat(actionName, " is already ongoing.")));
760
- break;
761
- case ConflictPolicy.KEEP_LAST: {
762
- conflictActions[actionName] = [futureAction];
763
- break;
764
- }
765
- case ConflictPolicy.KEEP_ALL: {
766
- var stack = conflictActions[actionName];
767
- if (!stack) {
768
- conflictActions[actionName] = stack = [];
769
- }
770
- stack.push(futureAction);
771
- break;
772
- }
773
- case ConflictPolicy.PARALLEL:
774
- case ConflictPolicy.REUSE:
775
- // no-op
776
- break;
777
- }
778
- });
779
- }
780
- /**
781
- * Processes next conflicting action (see ConflictPolicy) in the queue.
782
- */
783
- function processNextConflictAction(actionName, actions, conflictActions) {
784
- var futureActions = conflictActions[actionName];
785
- if (futureActions && futureActions.length > 0) {
786
- var futureAction_1 = conflictActions[actionName].shift();
787
- if (futureAction_1) {
788
- var p = actions[actionName].apply(actions, futureAction_1.args);
789
- if (p == null) {
790
- processNextConflictAction(actionName, actions, conflictActions);
791
- }
792
- else {
793
- p.then(function (res) {
794
- if (res === null) {
795
- // promise was aborted
796
- processNextConflictAction(actionName, actions, conflictActions);
797
- }
798
- futureAction_1.resolve(res);
799
- }).catch(function (e) { return futureAction_1.reject(e); });
800
- } // else aborted
801
- }
802
- }
803
- }
804
- /** @internal */
805
- function computeDerivedValues(s, p, derivedStateRef, options) {
806
- if ((options === null || options === void 0 ? void 0 : options.derivedState) == null) {
807
- return false;
808
- }
809
- var hasChanged = false;
810
- var compare = globalConfig.comparator;
811
- var depsMap = derivedStateRef.current.deps;
812
- var ctx = buildInvocationContextBase(s, null, p);
813
- var keys = Object.keys(options.derivedState);
814
- derivedStateRef.current.state = keys.reduce(function (acc, propName) {
815
- var compute = false;
816
- var previousDeps = depsMap[propName];
817
- var deps = options.derivedState[propName].getDeps(ctx);
818
- if (previousDeps == null) {
819
- compute = true;
820
- }
821
- else {
822
- compute =
823
- deps.find(function (dep, index) { return (previousDeps.length < index ? true : !compare(previousDeps[index], dep)); }) != null;
824
- }
825
- hasChanged = hasChanged || compute;
826
- // update cache of previous deps
827
- depsMap[propName] = deps;
828
- if (compute) {
829
- acc[propName] = options.derivedState[propName].get(ctx);
830
- }
831
- else {
832
- acc[propName] = derivedStateRef.current.state[propName];
833
- }
834
- return acc;
835
- }, {});
836
- return hasChanged;
837
- }
838
- // --------------------------------------
839
- //
840
- // Props change
841
- //
842
- // --------------------------------------
843
- /** @internal */
844
- function onPropChange(stateRef, derivedStateRef, propsRef, oldProps, actionsRef, options, getInitialState, setState, isInit, isDeferred) {
845
- var hasDerivedState = (options === null || options === void 0 ? void 0 : options.derivedState) != null;
846
- if (options.onPropsChange == null) {
847
- if ((options === null || options === void 0 ? void 0 : options.derivedState) != null) {
848
- // derived values must be updated from props
849
- setState(undefined, undefined, 'onPropsChange', 'effects', false, null, true);
850
- }
851
- return;
852
- }
853
- var onPropsChanges;
854
- if (Array.isArray(options.onPropsChange)) {
855
- onPropsChanges = options.onPropsChange;
856
- }
857
- else {
858
- onPropsChanges = [options.onPropsChange];
859
- }
860
- var stateChanged = false;
861
- var newStateRef = createRef(stateRef.current);
862
- var sideEffects = [];
863
- var compare = globalConfig.comparator;
864
- onPropsChanges.forEach(function (propsChange, index) {
865
- var _a;
866
- var getDeps = propsChange.getDeps;
867
- if (getDeps) {
868
- var propChanged_1 = false;
869
- var indices_1 = [];
870
- if (isInit) {
871
- if ((!isDeferred && propsChange.onMount) || (isDeferred && propsChange.onMountDeferred)) {
872
- propChanged_1 = true;
873
- }
874
- else {
875
- // skip this onPropsChange
876
- return;
877
- }
878
- }
879
- else {
880
- var oldValues = getDeps(oldProps);
881
- var newValues_1 = getDeps(propsRef.current);
882
- if (oldValues.length !== newValues_1.length) {
883
- console.warn('options.onPropsChange.getDeps returned array must be stable (same length)');
884
- propChanged_1 = true;
885
- }
886
- else {
887
- oldValues.forEach(function (v, i) {
888
- if (!compare(v, newValues_1[i])) {
889
- propChanged_1 = true;
890
- indices_1.push(i);
891
- }
892
- });
893
- }
894
- }
895
- if (propChanged_1) {
896
- var ctx = buildOnPropChangeEffects(newStateRef, derivedStateRef, propsRef, indices_1, index, isInit, getInitialState);
897
- var newState = mergeState(stateRef, (_a = propsChange.effects) === null || _a === void 0 ? void 0 : _a.call(propsChange, ctx));
898
- if (newState != null) {
899
- stateChanged = true;
900
- newStateRef.current = newState;
901
- setState(newStateRef.current, undefined, 'onPropsChange', 'effects', false, ctx, true, isInit);
902
- }
903
- if (propsChange.sideEffects) {
904
- sideEffects.push({ index: index, indices: indices_1, ctx: ctx });
905
- }
906
- }
907
- }
908
- });
909
- if (!stateChanged && hasDerivedState) {
910
- // derived values must be updated from props
911
- setState(undefined, undefined, 'onPropsChange', 'effects', false, null, true);
912
- }
913
- if (sideEffects.length > 0) {
914
- sideEffects.forEach(function (sideEffectInfo) {
915
- var onPropChange = onPropsChanges[sideEffectInfo.index];
916
- onPropChange.sideEffects(__assign(__assign({}, addStateToContext(addContextActions(sideEffectInfo.ctx, actionsRef), newStateRef)), { indices: sideEffectInfo.indices }));
917
- });
918
- }
919
- }
920
- // ------------------
921
- //
922
- // Middlewares
923
- //
924
- // ------------------
925
- /** @internal */
926
- function runMiddlewares(middlewares, oldState, newState, loading, actionName, actionType, isAsync, actionCtx) {
927
- // onPropChange to compute derived state but not state change
928
- if (actionName === 'onPropsChange' && newState === undefined) {
929
- return {
930
- newState: null,
931
- newLoading: false,
932
- };
933
- }
934
- if (middlewares && middlewares.length > 0) {
935
- var res = middlewares.reduce(function (acc, middleware) {
936
- var res = middleware.effects({
937
- isAsync: isAsync,
938
- name: actionName,
939
- type: actionType,
940
- context: actionCtx,
941
- }, acc.oldState, acc.newState, loading);
942
- return {
943
- newState: (res === null || res === void 0 ? void 0 : res.state) || acc.newState,
944
- oldState: (res === null || res === void 0 ? void 0 : res.state) ? acc.newState : acc.oldState,
945
- loading: (res === null || res === void 0 ? void 0 : res.loading) == null ? acc.loading : res.loading,
946
- };
947
- }, {
948
- oldState: oldState,
949
- newState: newState,
950
- loading: loading,
951
- });
952
- return {
953
- newLoading: res.loading,
954
- newState: res.newState,
955
- };
956
- }
957
- return {
958
- newState: newState,
959
- newLoading: loading,
960
- };
961
- }
962
-
963
- export { DEFAULT_PROMISE_ID, EffectError, ParallelActionError, addContextActions, addStateToContext, areSameArgs, buildErrorMap, buildInvocationContextBase, buildLoadingMap, buildOnMountInvocationContext, buildOnPropChangeEffects, buildOnUnMountInvocationContext, computeAsyncActionInput, computeDerivedValues, createRef, decorateAsyncAction, decorateSimpleSyncAction, decorateSyncAction, globalConfig, isAsyncAction, isAsyncGetPromiseAction, isAsyncGetPromiseGetAction, isLoadingImpl, isSimpleSyncAction, isSyncAction, onPropChange, retryPromiseDecorator, runMiddlewares, setGlobalConfig, updateErrorMap };
964
- //# sourceMappingURL=impl.js.map