kiss-for-react 1.1.0 → 2.0.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.
Files changed (155) hide show
  1. package/README.md +699 -156
  2. package/lib/cjs/ClassPersistor.js +177 -112
  3. package/lib/cjs/Esserializer/DeserializationOptions.js +4 -4
  4. package/lib/cjs/Esserializer/SerializeOptions.js +4 -4
  5. package/lib/cjs/Esserializer/builtins.js +258 -0
  6. package/lib/cjs/Esserializer/constant.js +39 -131
  7. package/lib/cjs/Esserializer/deserializer.js +226 -313
  8. package/lib/cjs/Esserializer/general.js +91 -39
  9. package/lib/cjs/Esserializer/index.js +47 -43
  10. package/lib/cjs/Esserializer/serializer.js +168 -133
  11. package/lib/cjs/Evt.js +132 -0
  12. package/lib/cjs/Hooks.js +1472 -969
  13. package/lib/cjs/KissAction.js +4635 -1333
  14. package/lib/cjs/LoadPages.js +336 -0
  15. package/lib/cjs/Persistor.js +189 -120
  16. package/lib/cjs/ProcessPersistence.js +579 -262
  17. package/lib/cjs/Store.js +4278 -1534
  18. package/lib/cjs/StoreException.js +162 -75
  19. package/lib/cjs/StoreProvider.js +88 -0
  20. package/lib/cjs/UserException.js +212 -218
  21. package/lib/cjs/Wait.js +309 -309
  22. package/lib/cjs/index.js +69 -42
  23. package/lib/cjs/server.js +54 -0
  24. package/lib/cjs/types/ClassPersistor.d.ts +143 -112
  25. package/lib/cjs/types/ClassPersistor.d.ts.map +1 -1
  26. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +13 -6
  27. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  28. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +11 -5
  29. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  30. package/lib/cjs/types/Esserializer/builtins.d.ts +36 -0
  31. package/lib/cjs/types/Esserializer/builtins.d.ts.map +1 -0
  32. package/lib/cjs/types/Esserializer/constant.d.ts +25 -49
  33. package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -1
  34. package/lib/cjs/types/Esserializer/deserializer.d.ts +27 -17
  35. package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
  36. package/lib/cjs/types/Esserializer/general.d.ts +28 -4
  37. package/lib/cjs/types/Esserializer/general.d.ts.map +1 -1
  38. package/lib/cjs/types/Esserializer/index.d.ts +33 -29
  39. package/lib/cjs/types/Esserializer/index.d.ts.map +1 -1
  40. package/lib/cjs/types/Esserializer/serializer.d.ts +14 -3
  41. package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -1
  42. package/lib/cjs/types/Evt.d.ts +124 -0
  43. package/lib/cjs/types/Evt.d.ts.map +1 -0
  44. package/lib/cjs/types/Hooks.d.ts +1174 -837
  45. package/lib/cjs/types/Hooks.d.ts.map +1 -1
  46. package/lib/cjs/types/KissAction.d.ts +5199 -1398
  47. package/lib/cjs/types/KissAction.d.ts.map +1 -1
  48. package/lib/cjs/types/LoadPages.d.ts +287 -0
  49. package/lib/cjs/types/LoadPages.d.ts.map +1 -0
  50. package/lib/cjs/types/Persistor.d.ts +187 -118
  51. package/lib/cjs/types/Persistor.d.ts.map +1 -1
  52. package/lib/cjs/types/ProcessPersistence.d.ts +197 -99
  53. package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -1
  54. package/lib/cjs/types/Store.d.ts +2253 -1042
  55. package/lib/cjs/types/Store.d.ts.map +1 -1
  56. package/lib/cjs/types/StoreException.d.ts +97 -28
  57. package/lib/cjs/types/StoreException.d.ts.map +1 -1
  58. package/lib/cjs/types/StoreProvider.d.ts +80 -0
  59. package/lib/cjs/types/StoreProvider.d.ts.map +1 -0
  60. package/lib/cjs/types/UserException.d.ts +178 -169
  61. package/lib/cjs/types/UserException.d.ts.map +1 -1
  62. package/lib/cjs/types/index.d.ts +12 -9
  63. package/lib/cjs/types/index.d.ts.map +1 -1
  64. package/lib/cjs/types/server.d.ts +12 -0
  65. package/lib/cjs/types/server.d.ts.map +1 -0
  66. package/lib/cjs/types/utils.d.ts +15 -1
  67. package/lib/cjs/types/utils.d.ts.map +1 -1
  68. package/lib/cjs/utils.js +45 -7
  69. package/lib/esm/ClassPersistor.mjs +177 -0
  70. package/lib/esm/Esserializer/{DeserializationOptions.js → DeserializationOptions.mjs} +3 -3
  71. package/lib/esm/Esserializer/{SerializeOptions.js → SerializeOptions.mjs} +3 -3
  72. package/lib/esm/Esserializer/builtins.mjs +254 -0
  73. package/lib/esm/Esserializer/constant.mjs +28 -0
  74. package/lib/esm/Esserializer/deserializer.mjs +221 -0
  75. package/lib/esm/Esserializer/general.mjs +81 -0
  76. package/lib/esm/Esserializer/index.mjs +43 -0
  77. package/lib/esm/Esserializer/serializer.mjs +164 -0
  78. package/lib/esm/Evt.mjs +151 -0
  79. package/lib/esm/Hooks.mjs +1446 -0
  80. package/lib/esm/KissAction.mjs +4689 -0
  81. package/lib/esm/LoadPages.mjs +340 -0
  82. package/lib/esm/Persistor.mjs +180 -0
  83. package/lib/esm/ProcessPersistence.mjs +581 -0
  84. package/lib/esm/Store.mjs +4400 -0
  85. package/lib/esm/StoreException.mjs +153 -0
  86. package/lib/esm/StoreProvider.mjs +80 -0
  87. package/lib/esm/{UserException.js → UserException.mjs} +240 -246
  88. package/lib/esm/{Wait.js → Wait.mjs} +309 -309
  89. package/lib/esm/index.mjs +12 -9
  90. package/lib/esm/server.mjs +23 -0
  91. package/lib/esm/types/ClassPersistor.d.ts +143 -112
  92. package/lib/esm/types/ClassPersistor.d.ts.map +1 -1
  93. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +13 -6
  94. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  95. package/lib/esm/types/Esserializer/SerializeOptions.d.ts +11 -5
  96. package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  97. package/lib/esm/types/Esserializer/builtins.d.ts +36 -0
  98. package/lib/esm/types/Esserializer/builtins.d.ts.map +1 -0
  99. package/lib/esm/types/Esserializer/constant.d.ts +25 -49
  100. package/lib/esm/types/Esserializer/constant.d.ts.map +1 -1
  101. package/lib/esm/types/Esserializer/deserializer.d.ts +27 -17
  102. package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
  103. package/lib/esm/types/Esserializer/general.d.ts +28 -4
  104. package/lib/esm/types/Esserializer/general.d.ts.map +1 -1
  105. package/lib/esm/types/Esserializer/index.d.ts +33 -29
  106. package/lib/esm/types/Esserializer/index.d.ts.map +1 -1
  107. package/lib/esm/types/Esserializer/serializer.d.ts +14 -3
  108. package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -1
  109. package/lib/esm/types/Evt.d.ts +124 -0
  110. package/lib/esm/types/Evt.d.ts.map +1 -0
  111. package/lib/esm/types/Hooks.d.ts +1174 -837
  112. package/lib/esm/types/Hooks.d.ts.map +1 -1
  113. package/lib/esm/types/KissAction.d.ts +5199 -1398
  114. package/lib/esm/types/KissAction.d.ts.map +1 -1
  115. package/lib/esm/types/LoadPages.d.ts +287 -0
  116. package/lib/esm/types/LoadPages.d.ts.map +1 -0
  117. package/lib/esm/types/Persistor.d.ts +187 -118
  118. package/lib/esm/types/Persistor.d.ts.map +1 -1
  119. package/lib/esm/types/ProcessPersistence.d.ts +197 -99
  120. package/lib/esm/types/ProcessPersistence.d.ts.map +1 -1
  121. package/lib/esm/types/Store.d.ts +2253 -1042
  122. package/lib/esm/types/Store.d.ts.map +1 -1
  123. package/lib/esm/types/StoreException.d.ts +97 -28
  124. package/lib/esm/types/StoreException.d.ts.map +1 -1
  125. package/lib/esm/types/StoreProvider.d.ts +80 -0
  126. package/lib/esm/types/StoreProvider.d.ts.map +1 -0
  127. package/lib/esm/types/UserException.d.ts +178 -169
  128. package/lib/esm/types/UserException.d.ts.map +1 -1
  129. package/lib/esm/types/index.d.ts +12 -9
  130. package/lib/esm/types/index.d.ts.map +1 -1
  131. package/lib/esm/types/server.d.ts +12 -0
  132. package/lib/esm/types/server.d.ts.map +1 -0
  133. package/lib/esm/types/utils.d.ts +15 -1
  134. package/lib/esm/types/utils.d.ts.map +1 -1
  135. package/lib/esm/utils.mjs +38 -0
  136. package/package.json +54 -30
  137. package/lib/cjs/UnmodifiableSetView.js +0 -53
  138. package/lib/cjs/types/UnmodifiableSetView.d.ts +0 -24
  139. package/lib/cjs/types/UnmodifiableSetView.d.ts.map +0 -1
  140. package/lib/esm/ClassPersistor.js +0 -112
  141. package/lib/esm/Esserializer/constant.js +0 -81
  142. package/lib/esm/Esserializer/deserializer.js +0 -307
  143. package/lib/esm/Esserializer/general.js +0 -34
  144. package/lib/esm/Esserializer/index.js +0 -39
  145. package/lib/esm/Esserializer/serializer.js +0 -130
  146. package/lib/esm/Hooks.js +0 -955
  147. package/lib/esm/KissAction.js +0 -1459
  148. package/lib/esm/Persistor.js +0 -113
  149. package/lib/esm/ProcessPersistence.js +0 -262
  150. package/lib/esm/Store.js +0 -1606
  151. package/lib/esm/StoreException.js +0 -69
  152. package/lib/esm/UnmodifiableSetView.js +0 -50
  153. package/lib/esm/types/UnmodifiableSetView.d.ts +0 -24
  154. package/lib/esm/types/UnmodifiableSetView.d.ts.map +0 -1
  155. package/lib/esm/utils.js +0 -3
@@ -0,0 +1,4689 @@
1
+ import { AbortDispatchException, kissAbort, StoreException } from "./StoreException.mjs";
2
+ import { UserException } from "./UserException.mjs";
3
+ import { describeValue, isPlainObject } from "./utils.mjs";
4
+ /**
5
+ * The values of the `poll` property of an action that uses polling.
6
+ * See the documentation of `KissAction.poll` for details.
7
+ */
8
+ export var Poll;
9
+ (function (Poll) {
10
+ /**
11
+ * Start polling.
12
+ * If polling is already active, does nothing.
13
+ * Otherwise, runs the action immediately and starts periodic polling.
14
+ */
15
+ Poll["start"] = "start";
16
+ /** Stop polling (cancels the timer and does not run the action). */
17
+ Poll["stop"] = "stop";
18
+ /**
19
+ * Run the action immediately and restart polling from now.
20
+ * If polling is not active, behaves like `Poll.start`.
21
+ */
22
+ Poll["runNowAndRestart"] = "runNowAndRestart";
23
+ /**
24
+ * Run the action once immediately.
25
+ * Does not start, stop, cancel, or restart polling.
26
+ */
27
+ Poll["once"] = "once";
28
+ })(Poll || (Poll = {}));
29
+ /**
30
+ * Base action. All other actions should extend this one.
31
+ *
32
+ * The lifecycle methods (like `reduce`, `before`, `after` and `wrapError`, and the other
33
+ * methods you override to configure the action) are `protected`, since only Kiss should call
34
+ * them, when the action is dispatched. To run an action, dispatch it. Note your overrides may
35
+ * also be declared `protected`. If they're not, TypeScript makes them public, but the
36
+ * `lifecycle-method-call` rule of the Kiss ESLint plugin still reports calling them.
37
+ */
38
+ export class KissAction {
39
+ get attempts() {
40
+ return this._retry.attempts;
41
+ }
42
+ /**
43
+ * The `before()` method MAY be implemented by the action. If implemented, it runs before the
44
+ * reducer. It may be sync or async. If it's async, the reducer will run after the before
45
+ * resolves.
46
+ *
47
+ * This method is useful for actions that need to perform some checks before executing the
48
+ * reducer. If necessary, it can prevent the reducer from running by throwing an exception.
49
+ *
50
+ * For example, the default `before()` method checks if the `checkInternet` property was set.
51
+ * If it was set, it checks if the device has an internet connection. If the connection is not
52
+ * present, it throws a `UserException` (or an `AbortDispatchException`, with
53
+ * `checkInternet = { abort: true }`), preventing the reducer from running.
54
+ *
55
+ * Note the `after()` method always runs, even if the `before()` method throws an exception.
56
+ */
57
+ before() {
58
+ if (this.checkInternet) {
59
+ const { dialog, abort } = this.checkInternet;
60
+ return this._hasInternet().then((isConnected) => {
61
+ if (!isConnected) {
62
+ if (abort) {
63
+ throw kissAbort('No Internet');
64
+ }
65
+ else if (dialog) {
66
+ throw new UserException("Please, verify your connection.").withTitle("There is no Internet");
67
+ }
68
+ else {
69
+ throw new UserException("No Internet").withDialog(false);
70
+ }
71
+ }
72
+ });
73
+ }
74
+ // Return void (not a Promise) when we don't need to check internet.
75
+ else
76
+ return;
77
+ }
78
+ /**
79
+ * Checks if the device has an internet connection, for `checkInternet` and
80
+ * `unlimitedRetryCheckInternet`.
81
+ *
82
+ * By default, it returns the online signal of the store, `store.isOnline`. In the browser,
83
+ * that's `navigator.onLine` (following the `online`/`offline` events), and elsewhere (Node.js,
84
+ * React Native) it's `true`, unless the store was created with an `onlineSource`. Note
85
+ * `navigator.onLine` only tells you if there's a local connection, not whether the internet
86
+ * is accessible.
87
+ *
88
+ * The recommended way to check the connection in some other way is to give the store an
89
+ * `onlineSource` (see `createStore`), which also feeds `useIsOnline()` and the `onOnline`
90
+ * callback of `useStoreEffect`. For example, in React Native, with the `NetInfo` package
91
+ * (https://www.npmjs.com/package/@react-native-community/netinfo):
92
+ *
93
+ * ```typescript
94
+ * import NetInfo from '@react-native-community/netinfo';
95
+ *
96
+ * const store = createStore<State>({
97
+ * initialState: State.initialState,
98
+ * onlineSource: (setOnline) => NetInfo.addEventListener((s) => setOnline(s.isConnected === true)),
99
+ * });
100
+ * ```
101
+ *
102
+ * You can also override this method, in your base action, to check the connection on demand
103
+ * each time an action needs it (for example, with https://www.npmjs.com/package/is-online, or
104
+ * by pinging your own server). The override then ignores `store.isOnline`:
105
+ *
106
+ * ```typescript
107
+ * protected hasInternet(): Promise<boolean> {
108
+ * return NetInfo.fetch().then(state => state.isConnected === true);
109
+ * }
110
+ * ```
111
+ *
112
+ * Note: This method is not called while the internet connection is being simulated with
113
+ * `internetOnOffSimulation` or `store.forceInternetOnOffSimulation`.
114
+ */
115
+ hasInternet() {
116
+ return Promise.resolve(this.store.isOnline);
117
+ }
118
+ /**
119
+ * If you are running tests, you can override this getter to simulate the internet connection
120
+ * as on or off, for actions that use `checkInternet` or `unlimitedRetryCheckInternet`:
121
+ *
122
+ * - Return `true` if there IS internet.
123
+ * - Return `false` if there is NO internet.
124
+ * - Return `null` to use the real internet connection status (default).
125
+ *
126
+ * If you want to change this for all actions that check the internet, you can do that at
127
+ * the store level:
128
+ *
129
+ * ```ts
130
+ * store.forceInternetOnOffSimulation = () => false;
131
+ * ```
132
+ *
133
+ * Using `store.forceInternetOnOffSimulation` is also useful during tests, for testing what
134
+ * happens when you have no internet connection. And since it's tied to the store, it
135
+ * automatically resets when the store is recreated.
136
+ */
137
+ get internetOnOffSimulation() {
138
+ return this.store.forceInternetOnOffSimulation();
139
+ }
140
+ /**
141
+ * The `after()` method MAY be implemented by the action. If implemented, it runs after the
142
+ * `before()`, after `reduce()`, and after `wrapError()`.
143
+ *
144
+ * The `after()` method is always synchronous, and it will always be called when the action is
145
+ * dispatched, even if errors were thrown by `before` or `reduce`.
146
+ */
147
+ after() {
148
+ }
149
+ /**
150
+ * If any error is thrown by `reduce` or `before`, you have the chance to further process it
151
+ * by using `wrapError`. Usually this is used to wrap the error inside another that better
152
+ * describes the failed action.
153
+ *
154
+ * For example, if some input validation inside your action throws a `ValidationError`,
155
+ * then instead of throwing this error you could do:
156
+ *
157
+ * ```
158
+ * wrapError(error) { return new UserException("Please enter a valid input.", {hardCause: error}) }
159
+ * ```
160
+ *
161
+ * If you want to disable the error you can return `null`. For example, if you want
162
+ * to disable all errors of type `MyException`:
163
+ *
164
+ * ```
165
+ * wrapError(error) { return (error instanceof MyException) ? null : error }
166
+ * ```
167
+ *
168
+ * The return type doesn't allow `undefined`, so that you don't swallow errors by mistake,
169
+ * by forgetting to return them. If `undefined` is returned anyway (for example, from
170
+ * JavaScript), it's treated the same as `null`, and the error is disabled.
171
+ *
172
+ * If you want the action to abort silently, you can return an `AbortDispatchException`. The
173
+ * action doesn't count as failed, and no error is shown or thrown. Note an
174
+ * `AbortDispatchException` thrown by `before` or `reduce` also gets here, so you may turn it
175
+ * into another error. But the ones Kiss itself uses to abort actions (for example, for
176
+ * `ignoreOld` or `sequential`) don't get here.
177
+ *
178
+ * IMPORTANT: If instead of RETURNING an error you throw an error inside the `wrapError` method,
179
+ * Kiss will catch this error and use it instead the original error. In other words,
180
+ * returning an error or throwing an error works the same way. But it's recommended that you
181
+ * return the error instead of throwing it anyway. Note: if your `wrapError` always throws,
182
+ * declare its return type as `never`, since TypeScript would otherwise infer it as `void`:
183
+ *
184
+ * ```
185
+ * wrapError(error: any): never { throw new UserException("Failed.").withHardCause(error) }
186
+ * ```
187
+ *
188
+ * IMPORTANT: Apart from defining `wrapError()` methods per action, you can also handle
189
+ * the errors of all actions with the `errorObserver` store parameter, when you create the
190
+ * Store. It's called after the action's `wrapError`, with the error it returned.
191
+ */
192
+ wrapError(error) {
193
+ return error;
194
+ }
195
+ ;
196
+ _store = null;
197
+ _resolve = null;
198
+ _reject = null;
199
+ _status = new ActionStatus();
200
+ _initialState = null;
201
+ _log = [];
202
+ /**
203
+ * Adds a key/value pair to the action log.
204
+ *
205
+ * ```ts
206
+ * class LoadUser extends Action {
207
+ *
208
+ * async reduce() {
209
+ * let user = await loadUser();
210
+ * this.log('User', user.id); // Here!
211
+ *
212
+ * return (state: State) => state.copy({ user });
213
+ * }
214
+ * }
215
+ * ```
216
+ */
217
+ log(key, value) {
218
+ this._log.push({ key, value });
219
+ }
220
+ /**
221
+ * Gets the action log.
222
+ *
223
+ * ```ts
224
+ * function stateObserver(action: KissAction<State>, prevState: State, newState: State, error: any, dispatchCount: number) {
225
+ * let log = action.getLog(); // Here!
226
+ * saveMetrics(action, log, newState, error);
227
+ * }
228
+ * ```
229
+ */
230
+ getLog() {
231
+ return this._log;
232
+ }
233
+ /**
234
+ * Returns the "status" of the action, used to keep track of the action's lifecycle. If you have
235
+ * a reference to the action you can check its status at any time with `action.status`:
236
+ *
237
+ * ```ts
238
+ * let action = new MyAction();
239
+ * await store.dispatchAndWait(action);
240
+ * if (action.status.isCompletedOk) { ... }
241
+ * ```
242
+ * However, dispatchAndWait also returns the action status after it finishes:
243
+ *
244
+ * ```ts
245
+ * let status = await store.dispatchAndWait(new MyAction());
246
+ * if (status.isCompletedOk) { ... }
247
+ * ```
248
+ */
249
+ get status() {
250
+ return this._status;
251
+ }
252
+ /**
253
+ * Dispatches an action to the Redux store.
254
+ */
255
+ dispatch(action) {
256
+ this._markAsChildren([action]);
257
+ this.store.dispatch(action);
258
+ }
259
+ /**
260
+ * Waits until the store state meets a certain condition, and then dispatches an action.
261
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
262
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
263
+ * the condition, so no other action can change the state in between.
264
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
265
+ * dispatched one after the other, and each condition is checked again right before its
266
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
267
+ *
268
+ * ```ts
269
+ * this.dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
270
+ * ```
271
+ *
272
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
273
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
274
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
275
+ * timeout is logged with `Store.log()`. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
276
+ * (or -1, or `Infinity`), but note that while it waits, the condition runs on every state change.
277
+ * A `logOut()` cancels the `dispatchWhen`s that are still waiting: their action is not
278
+ * dispatched, and their `onTimeout` is not called.
279
+ *
280
+ * ```ts
281
+ * this.dispatchWhen(
282
+ * new BuyStock('IBM'),
283
+ * (state) => state.stocks.getPrice('IBM') >= 100,
284
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
285
+ * );
286
+ * ```
287
+ */
288
+ dispatchWhen(action, condition, options) {
289
+ this._markAsChildren([action]);
290
+ this.store.dispatchWhen(action, condition, options);
291
+ }
292
+ /**
293
+ * Dispatches an action and returns a promise that resolves when the action finishes.
294
+ * While the state change from the action's reducer will have been applied when the promise
295
+ * resolves, other independent processes that the action may have started may still be in
296
+ * progress.
297
+ *
298
+ * Usage: `await this.dispatchAndWait(new MyAction())`.
299
+ */
300
+ dispatchAndWait(action) {
301
+ this._markAsChildren([action]);
302
+ return this.store.dispatchAndWait(action);
303
+ }
304
+ /**
305
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
306
+ * the store state. It returns the same list of actions, so that you can instantiate them
307
+ * inline, but still get a list of them.
308
+ *
309
+ * ```ts
310
+ * let actions = this.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
311
+ * ```
312
+ *
313
+ * See `Store.dispatchAll`.
314
+ */
315
+ dispatchAll(actions) {
316
+ this._markAsChildren(actions);
317
+ return this.store.dispatchAll(actions);
318
+ }
319
+ /**
320
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
321
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
322
+ * ALL actions finish, with the same list of actions.
323
+ *
324
+ * ```ts
325
+ * let actions = await this.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
326
+ * ```
327
+ *
328
+ * Note: While the state change from the action's reducers will have been applied when the
329
+ * Promise resolves, other independent processes that the action may have started may still
330
+ * be in progress.
331
+ *
332
+ * If some actions fail with an error that is not swallowed (see `dispatchAndWait`), all
333
+ * actions are still dispatched and allowed to finish. Only then the Promise rejects, with
334
+ * the error of the first failed action in the list.
335
+ *
336
+ * See `Store.dispatchAndWaitAll`.
337
+ */
338
+ dispatchAndWaitAll(actions) {
339
+ this._markAsChildren(actions);
340
+ return this.store.dispatchAndWaitAll(actions);
341
+ }
342
+ /**
343
+ * Dispatches the given action to the Redux store, to potentially change the state.
344
+ *
345
+ * This is exactly the same as the regular `dispatch`, except for the fact it
346
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
347
+ * if any of its `reduce()` or `before()` methods return a Promise.
348
+ *
349
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
350
+ * action is SYNC, which means the state gets changed right after the dispatch call.
351
+ *
352
+ * This `StoreException` is always thrown. It's not given to `wrapError` or the
353
+ * `errorObserver`, so they can't swallow it or convert it.
354
+ */
355
+ dispatchSync(action) {
356
+ this._markAsChildren([action]);
357
+ return this.store.dispatchSync(action);
358
+ }
359
+ /**
360
+ * Returns the Redux store: `this.store`.
361
+ *
362
+ * To read the current state inside an action, use: `this.store.state` or simply `this.state`.
363
+ * Note this is the CURRENT state, meaning it may change each time you look at it.
364
+ *
365
+ * If you want the snapshot of the state as it was when the action was dispatched, you can
366
+ * use `this.initialState`. You can also make a copy of the current state at any point in time:
367
+ *
368
+ * ```ts
369
+ * let currentState = this.state;
370
+ * ```
371
+ *
372
+ * To dispatch an action inside the current action, you can simply write `this.dispatch()`
373
+ * or `this.dispatchAndWait()`, which is the same as `this.store.dispatch()` etc.
374
+ */
375
+ get store() {
376
+ if (this._store === null)
377
+ throw new StoreException('Store not set in action');
378
+ return this._store;
379
+ }
380
+ /**
381
+ * Returns the CURRENT state: `this.state`.
382
+ * Note this is the CURRENT state, meaning it may change each time you look at it.
383
+ *
384
+ * If you want a snapshot of the state as it was when the action was dispatched, you can
385
+ * use `this.initialState`. You can also make a copy of the current state at any point in time:
386
+ *
387
+ * ```ts
388
+ * let currentState = this.state;
389
+ * ```
390
+ *
391
+ * To dispatch an action inside the current action, you can simply write `this.dispatch()`
392
+ * or `this.dispatchAndWait()`, which is the same as `this.store.dispatch()` etc.
393
+ */
394
+ get state() {
395
+ return this.store.state;
396
+ }
397
+ /**
398
+ * Sets a prop in the store. Same as `this.store.setProp()`. The props hold the long-lived
399
+ * things of the app that are not state: intervals and timeouts, WebSockets, `EventSource`s,
400
+ * `AbortController`s, listeners, RxJS subscriptions. See `Store.setProp` for how they are
401
+ * disposed.
402
+ *
403
+ * ```ts
404
+ * class StartClock extends Action {
405
+ * reduce() {
406
+ * const interval = setInterval(() => this.dispatch(new Tick()), 1000);
407
+ * this.setProp('clock', interval, { dispose: clearInterval });
408
+ * return null;
409
+ * }
410
+ * }
411
+ * ```
412
+ *
413
+ * See also: `prop`, `props`, `disposeProp` and `disposeProps`.
414
+ */
415
+ setProp(key, value, options) {
416
+ this.store.setProp(key, value, options);
417
+ }
418
+ /**
419
+ * Returns the prop with the given key, or `undefined` if there is none. Same as
420
+ * `this.store.prop()`. Give it the type of the value: `this.prop<number>('clock')`.
421
+ */
422
+ prop(key) {
423
+ return this.store.prop(key);
424
+ }
425
+ /**
426
+ * All the props of the store, with their keys and values. Same as `this.store.props`.
427
+ */
428
+ get props() {
429
+ return this.store.props;
430
+ }
431
+ /**
432
+ * Disposes the prop with the given key, and removes it from the props. Same as
433
+ * `this.store.disposeProp()`. See `Store.setProp` for how the value is disposed.
434
+ *
435
+ * ```ts
436
+ * class StopClock extends Action {
437
+ * reduce() {
438
+ * this.disposeProp('clock');
439
+ * return null;
440
+ * }
441
+ * }
442
+ * ```
443
+ */
444
+ disposeProp(key) {
445
+ this.store.disposeProp(key);
446
+ }
447
+ /**
448
+ * Disposes all the props, and removes them, or only the ones the `predicate` selects. Same
449
+ * as `this.store.disposeProps()`.
450
+ */
451
+ disposeProps(predicate) {
452
+ this.store.disposeProps(predicate);
453
+ }
454
+ /**
455
+ * Returns the state as it was when the action was dispatched.
456
+ *
457
+ * It can be the same or different from `this.state`, which is the current state in the store,
458
+ * because other actions may have changed the current state since this action was dispatched.
459
+ *
460
+ * In the case of SYNC actions that do not dispatch other SYNC actions,
461
+ * `this.state` and `this.initialState` will be the same.
462
+ */
463
+ get initialState() {
464
+ return this._initialState;
465
+ }
466
+ /**
467
+ * You can wrap the reducer to allow for some pre- or post-processing.
468
+ * For instance, if you want to prevent an async reducer from modifying the current state,
469
+ * if the current state has already changed since the reducer started:
470
+ *
471
+ * ```ts
472
+ * wrapReduce(reduce: () => ReduxReducer<State>): () => ReduxReducer<State> {
473
+ * return async () => {
474
+ * let oldState = this.state;
475
+ * let result = await reduce();
476
+ * if (oldState !== this.state) return null;
477
+ * return typeof result === 'function' ? result : () => result;
478
+ * };
479
+ * }
480
+ * ```
481
+ *
482
+ * Note: If you return a function that returns a Promise, the action will be ASYNC.
483
+ * If you return a function that returns St, the action will be SYNC only if the
484
+ * before and reduce methods are also SYNC.
485
+ */
486
+ wrapReduce(reduce) {
487
+ return reduce;
488
+ }
489
+ /**
490
+ * If method `abortDispatch()` returns true, the action will not be dispatched: `before`,
491
+ * `reduce` and `after` will not be called. This is an advanced feature only useful under rare
492
+ * circumstances, and you should only use it if you know what you are doing.
493
+ *
494
+ * Inside `abortDispatch()`, you can read `this.state`, `this.store` and `this.initialState`.
495
+ * For example, to only run the action when there are no items loaded:
496
+ *
497
+ * ```ts
498
+ * abortDispatch() { return this.state.items.length > 0; }
499
+ * ```
500
+ *
501
+ * Note: If `abortDispatch()` throws an error, the error is logged and the action is aborted.
502
+ *
503
+ * When the dispatch is aborted, `dispatchAndWait` returns a status with
504
+ * `isDispatchAborted: true`. Note `abortDispatch()` must decide synchronously. To abort the
505
+ * action after some ASYNC check, throw an `AbortDispatchException` from `before` instead.
506
+ */
507
+ abortDispatch() {
508
+ return false;
509
+ }
510
+ /**
511
+ * Method `abortReduce()` is called with the result of the `reduce()` method, right after
512
+ * the `reduce()` runs. However, it's only called if no error was thrown, and if the `reduce()`
513
+ * method result would change the current state (in other words, if `reduce()` returned a
514
+ * non-null state different from the current state).
515
+ *
516
+ * If `abortReduce()` returns true, the result of the `reduce()` method will be discarded,
517
+ * as if the `reduce()` method itself returned null.
518
+ *
519
+ * Note: `abortReduce()` is called BEFORE the `after()` method, and the `after()` method will
520
+ * run normally no matter the result of `abortReduce()`.
521
+ *
522
+ * This is mostly useful for async actions. While the action is waiting (for example, for a
523
+ * server response), other actions may change the state, so the result may be out of date
524
+ * by the time it arrives.
525
+ *
526
+ * For example, suppose a different user logs in while the profile of the previous user is
527
+ * still loading. The loaded profile belongs to the wrong person, so we discard it:
528
+ *
529
+ * ```ts
530
+ * class LoadUserProfile extends Action {
531
+ *
532
+ * async reduce() {
533
+ * const profile = await api.getProfile(this.state.userId);
534
+ * return (state: State) => state.copy({ profile });
535
+ * }
536
+ *
537
+ * // If a different user logged in while we were loading, don't save this profile.
538
+ * abortReduce(newState: State): boolean {
539
+ * return newState.userId !== this.initialState.userId;
540
+ * }
541
+ * }
542
+ * ```
543
+ *
544
+ * Note `this.initialState` is the state when the action was dispatched, while `newState`
545
+ * is the state the reducer wants to apply.
546
+ *
547
+ * Method `abortReduce()` is an advanced feature only useful under rare circumstances,
548
+ * and you should only use it if you know what you are doing.
549
+ */
550
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameter documents the signature to override.
551
+ abortReduce(state) {
552
+ return false;
553
+ }
554
+ /**
555
+ * An optional key that tells apart the actions of the same class, for `isWaiting`, `isFailed`,
556
+ * `exceptionFor` and `clearExceptionFor` (and the hooks `useIsWaiting`, `useIsFailed`,
557
+ * `useExceptionFor` and `useClearExceptionFor`).
558
+ *
559
+ * By default, those functions work per action class: `useIsWaiting(LoadUser)` is `true` while
560
+ * any `LoadUser` runs, and `useIsFailed(LoadUser)` is `true` if any `LoadUser` failed. In a
561
+ * list of users where each row dispatches its own `LoadUser(userId)`, that would show a
562
+ * spinner in every row while any one user loads.
563
+ *
564
+ * Override this getter to return a value that identifies the action instance. Then, pass the
565
+ * same value to the status functions, in `statusKey`:
566
+ *
567
+ * ```ts
568
+ * class LoadUser extends Action {
569
+ * constructor(readonly userId: string) { super(); }
570
+ * get statusKey() { return this.userId; }
571
+ * async reduce() { ... }
572
+ * }
573
+ *
574
+ * // In the row of one user:
575
+ * const isWaiting = useIsWaiting(LoadUser, { statusKey: userId });
576
+ * const isFailed = useIsFailed(LoadUser, { statusKey: userId });
577
+ * const error = useExceptionFor(LoadUser, { statusKey: userId });
578
+ * ```
579
+ *
580
+ * The key can be any value: a string, a number, an array like `[userId, cartId]`, or a plain
581
+ * object. Arrays and plain objects are compared by their content, and everything else with
582
+ * `Object.is`. Without `statusKey` in the options, the status functions consider all actions
583
+ * of the type, as usual, whatever their keys.
584
+ *
585
+ * ### What is kept in memory
586
+ *
587
+ * For `isWaiting`, nothing extra is kept: the store already holds the actions in progress,
588
+ * and reads their `statusKey` when asked.
589
+ *
590
+ * For `isFailed` and `exceptionFor`, the store keeps a record of each failure: the action
591
+ * type, the `statusKey` and the error (not the action itself). Without a `statusKey`, there
592
+ * is at most one record per action class. With a `statusKey`, there is one record per key
593
+ * that failed: for example, one per user whose `LoadUser` failed. A record is removed when an
594
+ * action of the same type and key is dispatched again, by `clearExceptionFor`, or by
595
+ * `clearAllExceptions` (which `clearInternalActionProps`, `logOut` and the shutdown of the
596
+ * store call). So, when a `statusKey` can take many values, remember that the failures that
597
+ * are never retried stay in memory until one of those is called.
598
+ *
599
+ * ### The key must always be the same
600
+ *
601
+ * Derive the key only from the action's own fields, the ones set in its constructor, like
602
+ * `this.userId` above. The getter must return the same value every time it's read, for the
603
+ * whole life of the action. Don't use anything that can change: a field the action itself
604
+ * changes in `before` or `reduce`, something read from the state or from the store props,
605
+ * the current time, or a random value.
606
+ *
607
+ * The reason is that the store reads the key at different moments: when the action is
608
+ * dispatched (to clear its old failure), when it fails (to record the failure), and every
609
+ * time `isWaiting` is asked. If the key changed between those moments, the old failure would
610
+ * never be cleared, or `isWaiting(LoadUser, { statusKey: userId })` would stop matching the
611
+ * action that is running.
612
+ */
613
+ get statusKey() {
614
+ return undefined;
615
+ }
616
+ /**
617
+ * You can use `isWaiting` and pass it an action `type`:
618
+ * - It returns true if an action of the given type (or of a subclass) is currently being processed.
619
+ * - It returns false if no action of the given type is currently being processed.
620
+ * - This is only useful for ASYNC actions. A SYNC action finishes before `dispatch` returns, so
621
+ * outside of it, `isWaiting` is always `false` for it, and components never see it as `true`.
622
+ * - Inside an action, `isWaiting` of the action's own type is always `true` (even when the action
623
+ * is SYNC), since the action itself is being processed.
624
+ *
625
+ * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
626
+ *
627
+ * ```ts
628
+ * this.dispatch(new MyAction());
629
+ * if (this.isWaiting(MyAction)) { ... } // Show a spinner
630
+ * ```
631
+ *
632
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see `statusKey`):
633
+ * `this.isWaiting(LoadUser, { statusKey: userId })`.
634
+ */
635
+ isWaiting(type, options) {
636
+ return this.store.isWaiting(type, options);
637
+ }
638
+ /**
639
+ * Returns true if the given action `type` failed, with any error, not only with a
640
+ * `UserException`. Use `exceptionFor` to get the error, if it was a `UserException`.
641
+ * An error swallowed by `wrapError` or the `errorObserver` (they returned `null`), and
642
+ * an `AbortDispatchException`, don't count as failures.
643
+ * Note: This method uses the EXACT action type. Subtypes are not considered.
644
+ *
645
+ * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see `statusKey`):
646
+ * `this.isFailed(LoadUser, { statusKey: userId })`.
647
+ */
648
+ isFailed(type, options) {
649
+ return this.store.isFailed(type, options);
650
+ }
651
+ /**
652
+ * Returns the `UserException` of the `type` that failed. Returns `null` if it didn't fail,
653
+ * or if it failed with an error that is not a `UserException` (in that case, `isFailed` is
654
+ * still true).
655
+ * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
656
+ *
657
+ * Pass `{ statusKey }` to get the exception of the failure with that `statusKey` (see
658
+ * `statusKey`): `this.exceptionFor(LoadUser, { statusKey: userId })`. Without it, if actions
659
+ * with different keys failed, you get the `UserException` of the most recent failure.
660
+ */
661
+ exceptionFor(type, options) {
662
+ return this.store.exceptionFor(type, options);
663
+ }
664
+ /**
665
+ * Removes the exact given action `type` from the list of action types that failed.
666
+ * Note it clears the EXACT given type. Subtypes are not considered.
667
+ *
668
+ * Even if you never call this method explicitly, just dispatching an action already clears that action type
669
+ * from the list of failing action types. But you can call this method explicitly if you want to clear the
670
+ * action type before it's used again.
671
+ *
672
+ * Usage:
673
+ * ```ts
674
+ * this.clearExceptionFor(MyAction);
675
+ * ```
676
+ *
677
+ * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see `statusKey`):
678
+ * `this.clearExceptionFor(LoadUser, { statusKey: userId })`. Without it, all the failures of
679
+ * the type are cleared, whatever their keys.
680
+ */
681
+ clearExceptionFor(type, options) {
682
+ return this.store.clearExceptionFor(type, options);
683
+ }
684
+ /**
685
+ * Clears the failures of all action types, so that `isFailed` is `false` and `exceptionFor`
686
+ * is `null` for all of them. Same as `store.clearAllExceptions()`.
687
+ *
688
+ * You rarely need this, since `clearInternalActionProps()`, `logOut()` and the shutdown of
689
+ * the store already call it.
690
+ */
691
+ clearAllExceptions() {
692
+ return this.store.clearAllExceptions();
693
+ }
694
+ /**
695
+ * Set `nonReentrant` to `true` to abort the action in case the action is still running
696
+ * from a previous dispatch. For example:
697
+ *
698
+ * ```ts
699
+ * class SaveAction extends KissAction<State> {
700
+ * nonReentrant = true;
701
+ *
702
+ * async reduce() {
703
+ * await fetch('https://myapi.com/save', { method: 'PUT', body: 'data' });
704
+ * return null;
705
+ * }
706
+ * }
707
+ * ```
708
+ *
709
+ * The aborted action is ignored silently, as if it had never been dispatched.
710
+ *
711
+ * ## Advanced usage
712
+ *
713
+ * The non-reentrant check is, by default, based on the action class. This means it will
714
+ * abort an action if another action of the same class is currently running. Note subclasses
715
+ * are different classes, so they don't block each other. If you want to check based on more
716
+ * than simply the class, you can override the `nonReentrantKeyParams()` method. For example,
717
+ * here we use a field of the action to differentiate:
718
+ *
719
+ * ```ts
720
+ * class SaveItem extends KissAction<State> {
721
+ * nonReentrant = true;
722
+ * constructor(readonly itemId: string) { super(); }
723
+ * nonReentrantKeyParams() { return this.itemId; }
724
+ * ...
725
+ * }
726
+ * ```
727
+ *
728
+ * With this setup, `SaveItem('A')` and `SaveItem('B')` can run in parallel,
729
+ * but two `SaveItem('A')` cannot.
730
+ *
731
+ * You can also override `computeNonReentrantKey()` if you want different action classes
732
+ * to share the same non-reentrant key. Check the documentation of that method for more
733
+ * information.
734
+ *
735
+ * The key is released when the action finishes, with or without errors, after its `after()`
736
+ * method runs. This means dispatching the same action from its own `after()` method is
737
+ * aborted. To run it again when it finishes, dispatch it from where you awaited it instead.
738
+ *
739
+ * Notes:
740
+ * - It can be combined with `retry` and `checkInternet`. With `retry`, the key is only
741
+ * released after the last attempt.
742
+ * - It can be combined with `debounce`. The key is then checked and taken when the debounce
743
+ * period ends, right before the reducer runs, and not when the action is dispatched.
744
+ * - If `abortDispatch()` returns `true`, the action is aborted before the non-reentrant
745
+ * check, and doesn't take the key.
746
+ * - It should not be used in an `OptimisticCommand`, which is already non-reentrant.
747
+ * Dispatching it with `nonReentrant` throws a `StoreException`.
748
+ * - It should not be combined with `throttle`, `fresh` or `ignoreOld`. Doing so throws a
749
+ * `StoreException`.
750
+ * - It should not be combined with `unlimitedRetryCheckInternet`, which is already
751
+ * non-reentrant. Doing so throws a `StoreException`.
752
+ * - It can be combined with `sequential`. Duplicates are then dropped while the original
753
+ * action is waiting in the queue or running, and the actions that do get through still
754
+ * run one at a time.
755
+ */
756
+ nonReentrant = false;
757
+ /**
758
+ * By default, the non-reentrant key is based on the action class.
759
+ * Override `nonReentrantKeyParams()` so that actions of the SAME CLASS but with different
760
+ * parameters don't block each other. For example:
761
+ *
762
+ * ```ts
763
+ * class SaveItem extends KissAction<State> {
764
+ * nonReentrant = true;
765
+ * constructor(readonly itemId: string) { super(); }
766
+ * nonReentrantKeyParams() { return this.itemId; }
767
+ * ...
768
+ * }
769
+ * ```
770
+ *
771
+ * Now `SaveItem('A')` and `SaveItem('B')` can run in parallel, but two concurrent dispatches
772
+ * of `SaveItem('A')` will not both run.
773
+ *
774
+ * Params are compared with `Object.is`, except arrays and plain objects, which are compared
775
+ * by their contents. For example, `[1, 'A']` and `{ id: 1 }` are valid params.
776
+ *
777
+ * This is used by `nonReentrant` actions, and by `OptimisticCommand`.
778
+ */
779
+ nonReentrantKeyParams() {
780
+ return null;
781
+ }
782
+ /**
783
+ * By default, the non-reentrant key combines the action class with `nonReentrantKeyParams()`.
784
+ * Override this method if you want different action classes to share the same key:
785
+ *
786
+ * ```ts
787
+ * class SaveUser extends KissAction<State> {
788
+ * nonReentrant = true;
789
+ * constructor(readonly userId: string) { super(); }
790
+ * computeNonReentrantKey() { return this.userId; }
791
+ * ...
792
+ * }
793
+ *
794
+ * class DeleteUser extends KissAction<State> {
795
+ * nonReentrant = true;
796
+ * constructor(readonly userId: string) { super(); }
797
+ * computeNonReentrantKey() { return this.userId; }
798
+ * ...
799
+ * }
800
+ * ```
801
+ *
802
+ * With this setup, `SaveUser('123')` and `DeleteUser('123')` can't run at the same time,
803
+ * because they share the same key.
804
+ *
805
+ * Keys are compared with `Object.is`, except arrays and plain objects, which are compared
806
+ * by their contents.
807
+ *
808
+ * This is used by `nonReentrant` actions, and by `OptimisticCommand`. They share the same
809
+ * keys, so a `nonReentrant` action and an `OptimisticCommand` with the same key can't run
810
+ * at the same time either.
811
+ */
812
+ computeNonReentrantKey() {
813
+ return [this.constructor, this.nonReentrantKeyParams()];
814
+ }
815
+ /**
816
+ * For Kiss internal use only.
817
+ * The non-reentrant key of this action, saved by the store when the action is dispatched
818
+ * (or, with `debounce`, when its debounce period ends).
819
+ * @internal
820
+ */
821
+ _nonReentrantKey = undefined;
822
+ /**
823
+ * For Kiss internal use only.
824
+ * How many times `store.clearInternalActionProps()` had been called when this action was
825
+ * dispatched. If it's called again later, the action stops retrying.
826
+ * @internal
827
+ */
828
+ _clearCountAtDispatch = 0;
829
+ /**
830
+ * For Kiss internal use only.
831
+ * How many times `store.logOut()` had been called when this action was dispatched. If it's
832
+ * called again later, the result of this action is discarded when it finishes.
833
+ * @internal
834
+ */
835
+ _logOutCountAtDispatch = 0;
836
+ /**
837
+ * For Kiss internal use only.
838
+ * When this action is dispatched by another action (with `this.dispatch` and similar), it's
839
+ * the `_logOutCountAtDispatch` of that other action. If `store.logOut()` was called after
840
+ * that other action was dispatched, the store doesn't accept this action. Otherwise, `null`.
841
+ * @internal
842
+ */
843
+ _parentLogOutCount = null;
844
+ // Marks the given actions as dispatched by this action. See `_parentLogOutCount`.
845
+ _markAsChildren(actions) {
846
+ for (const action of actions)
847
+ action._parentLogOutCount = this._logOutCountAtDispatch;
848
+ }
849
+ /**
850
+ * For Kiss internal use only.
851
+ * True if the action was dispatched with `dispatchSync`, which threw because the action is
852
+ * ASYNC. Its async work was already running, and its result is ignored, so it stops retrying.
853
+ * @internal
854
+ */
855
+ _isDiscardedByDispatchSync = false;
856
+ /**
857
+ * The default lock for debouncing is the action class, meaning it will debounce the dispatch
858
+ * of actions of the same class. Override this method to customize the lock to any value.
859
+ * For example, you can return a string, and actions with the same lock value will debounce
860
+ * each other:
861
+ *
862
+ * ```ts
863
+ * class MyAction extends KissAction<State> {
864
+ * debounce = true;
865
+ * debounceLockBuilder() { return 'myLock'; }
866
+ * ...
867
+ * }
868
+ * ```
869
+ *
870
+ * Locks are compared with `Object.is`, except arrays and plain objects, which are compared
871
+ * by their contents. For example, `[this.constructor, this.userId]` is a valid lock.
872
+ */
873
+ debounceLockBuilder() {
874
+ return this.constructor;
875
+ }
876
+ /**
877
+ * Removes all debounce locks. Actions that are still waiting for their debounce period
878
+ * finish right away, without running their reducer.
879
+ * You generally don't need to call this method.
880
+ */
881
+ removeAllDebounceLocks() {
882
+ this.store._removeAllDebounceLocks();
883
+ }
884
+ /**
885
+ * For Kiss internal use only.
886
+ * The debounce wait time in milliseconds, or `null` if the action doesn't debounce.
887
+ * @internal
888
+ */
889
+ get _debounceMillis() {
890
+ if (this.debounce === true)
891
+ return 333;
892
+ if (typeof this.debounce === 'number')
893
+ return this.debounce;
894
+ return null;
895
+ }
896
+ /**
897
+ * Set `ignoreOld` to `true` so that, when the action is dispatched again, the actions of the
898
+ * previous dispatches that are still running become "old": their results are ignored, and
899
+ * their requests can be cancelled. Only the newest dispatch changes the state.
900
+ *
901
+ * This prevents a slow request that finishes late from overwriting the newer information. For
902
+ * example, when the user selects a tab, you load the items of that tab:
903
+ *
904
+ * ```ts
905
+ * class LoadTab extends KissAction<State> {
906
+ * constructor(readonly tab: string) { super(); }
907
+ *
908
+ * ignoreOld = true; // Here!
909
+ *
910
+ * async reduce() {
911
+ * let response = await fetch(`/api/items?tab=${this.tab}`, { signal: this.abortSignal });
912
+ * let items = await response.json();
913
+ * return (state: State) => state.copy({ items });
914
+ * }
915
+ * }
916
+ * ```
917
+ *
918
+ * If the user selects tab "A" and then tab "B", without `ignoreOld` both requests run, and if
919
+ * the request for "A" is slower and finishes last, the items of "A" are shown while tab "B" is
920
+ * selected. With `ignoreOld`, as soon as "B" is dispatched, the action for "A" is old. Its
921
+ * request is cancelled (since it got the `abortSignal`), and even if it finishes, its result
922
+ * is ignored. The screen keeps what it showed before, until the items of "B" arrive.
923
+ *
924
+ * In more detail:
925
+ *
926
+ * - The actions are numbered in the order they are dispatched. When an action is dispatched,
927
+ * all the actions with the same key that are still running become old.
928
+ *
929
+ * - The old actions are aborted (see `isAborted`): their `abortSignal` is aborted. Pass it
930
+ * to `fetch` (or to any other API that accepts an `AbortSignal`, like axios), so that their
931
+ * requests are cancelled. You may also check `isAborted` yourself, after some `await`.
932
+ *
933
+ * - An old action finishes silently: its result is ignored (it doesn't change the state),
934
+ * and so are its errors (no error dialog, it doesn't count as failed, and it isn't
935
+ * retried). This includes the error `fetch` rejects with when its signal is aborted. Its
936
+ * status has `isDispatchAborted: true`, and `dispatchAndWait` resolves.
937
+ *
938
+ * - The newest action is never old, even if it fails. In that case the state is not changed,
939
+ * and the error is processed as usual.
940
+ *
941
+ * - A dispatch that is aborted before it runs (by `abortDispatch()`, `throttle` or `fresh`)
942
+ * doesn't make the other actions old. Neither does a dispatch with `Poll.stop`, or with
943
+ * `Poll.start` while polling is already active, since they don't run the reducer.
944
+ *
945
+ * - Only the state returned by the reducer is ignored. Anything else the reducer did still
946
+ * happened, like dispatching other actions. To avoid that, check `isAborted`:
947
+ *
948
+ * ```ts
949
+ * async reduce() {
950
+ * let items = await loadItems(this.tab);
951
+ * if (!this.isAborted) this.dispatch(new LoadItemImages(items));
952
+ * return (state: State) => state.copy({ items });
953
+ * }
954
+ * ```
955
+ *
956
+ * ## Keys
957
+ *
958
+ * By default, the key is based on the action class. This means dispatching an action makes
959
+ * the running actions of the same class old. Note subclasses are different classes, so they
960
+ * don't affect each other. Override `ignoreOldKeyParams()` so that actions of the same class
961
+ * but with different parameters don't affect each other, or `computeIgnoreOldKey()` so that
962
+ * different action classes share the same key.
963
+ *
964
+ * Choose the key according to the part of the state the actions change. Actions that change
965
+ * the same part of the state should share the key, and actions that change different parts
966
+ * should not. For example, if `LoadItem` always puts the item into the same `selectedItem`
967
+ * field, keep the default key, so that loading item "B" makes loading item "A" old. But if it
968
+ * puts each item into a cache, by id, use the id in the key, since item "A" is still useful:
969
+ *
970
+ * ```ts
971
+ * class LoadItem extends KissAction<State> {
972
+ * constructor(readonly itemId: string) { super(); }
973
+ * ignoreOld = true;
974
+ * ignoreOldKeyParams() { return this.itemId; }
975
+ *
976
+ * async reduce() {
977
+ * let item = await loadItem(this.itemId, this.abortSignal);
978
+ * return (state: State) => state.withCachedItem(item);
979
+ * }
980
+ * }
981
+ * ```
982
+ *
983
+ * ## Combining with other features
984
+ *
985
+ * - Use it with `debounce` to search while the user types. The `debounce` avoids sending a
986
+ * request for each key pressed. But if the user pauses for longer than the wait time and
987
+ * then types again, the older request would still be running. With `ignoreOld`, it's
988
+ * cancelled, and its results don't overwrite the newer ones. Note that without `debounce`,
989
+ * each key pressed would cancel the previous request, and no results would be shown until
990
+ * the user stops typing. Also note an action replaced during its wait time is old too, so
991
+ * it's aborted (instead of finishing without running its reducer).
992
+ *
993
+ * - It can be combined with `retry` and `checkInternet`. An action that becomes old while
994
+ * waiting to retry stops waiting, and is aborted right away.
995
+ *
996
+ * - It can be combined with `throttle` and `fresh`. These abort the dispatches inside their
997
+ * period, so those don't make the running action old. But when the period ends while an
998
+ * older action is still running, the next dispatch runs, and makes it old.
999
+ *
1000
+ * - When polling, add it to the action returned by `createPollingAction()`. It's useful when
1001
+ * `pollWaitsForRun` is `false`, or when you also dispatch the action yourself, for example
1002
+ * from a "refresh" button.
1003
+ *
1004
+ * - It should not be combined with `nonReentrant` or `unlimitedRetryCheckInternet`, since
1005
+ * those never let two actions with the same key run at the same time, nor with
1006
+ * `sequential`, which already applies the results in the dispatch order. It also should not
1007
+ * be used in an `OptimisticCommand`, `OptimisticSync`, `OptimisticSyncWithPush` or
1008
+ * `ServerPush`, which already decide which values win. Doing so throws a `StoreException`.
1009
+ *
1010
+ * Other notes:
1011
+ * - It works with both SYNC and ASYNC reducers. Even SYNC reducers can be affected, when an
1012
+ * ASYNC `before` (for example, the one of `checkInternet`) makes an older action reach its
1013
+ * reducer after a newer one was dispatched.
1014
+ * - `store.clearInternalActionProps()` forgets the keys. The actions dispatched after it
1015
+ * don't make the ones dispatched before it old.
1016
+ */
1017
+ ignoreOld = false;
1018
+ /**
1019
+ * By default, the `ignoreOld` key is based on the action class. Override
1020
+ * `ignoreOldKeyParams()` so that actions of the SAME CLASS but with different parameters
1021
+ * don't affect each other. For example:
1022
+ *
1023
+ * ```ts
1024
+ * class LoadItem extends KissAction<State> {
1025
+ * ignoreOld = true;
1026
+ * constructor(readonly itemId: string) { super(); }
1027
+ * ignoreOldKeyParams() { return this.itemId; }
1028
+ * ...
1029
+ * }
1030
+ * ```
1031
+ *
1032
+ * Now dispatching `LoadItem('A')` makes only the running `LoadItem('A')` actions old. The
1033
+ * `LoadItem('B')` actions are not affected.
1034
+ *
1035
+ * Params are compared with `Object.is`, except arrays and plain objects, which are compared
1036
+ * by their contents. For example, `[1, 'A']` and `{ id: 1 }` are valid params.
1037
+ */
1038
+ ignoreOldKeyParams() {
1039
+ return null;
1040
+ }
1041
+ /**
1042
+ * By default, the `ignoreOld` key combines the action class with `ignoreOldKeyParams()`.
1043
+ * Override this method if you want different action classes to share the same key:
1044
+ *
1045
+ * ```ts
1046
+ * class LoadUserProfile extends KissAction<State> {
1047
+ * ignoreOld = true;
1048
+ * constructor(readonly userId: string) { super(); }
1049
+ * computeIgnoreOldKey() { return 'selectedUser'; }
1050
+ * ...
1051
+ * }
1052
+ *
1053
+ * class LoadUserSummary extends KissAction<State> {
1054
+ * ignoreOld = true;
1055
+ * constructor(readonly userId: string) { super(); }
1056
+ * computeIgnoreOldKey() { return 'selectedUser'; }
1057
+ * ...
1058
+ * }
1059
+ * ```
1060
+ *
1061
+ * With this setup, dispatching a `LoadUserSummary` makes the running `LoadUserProfile`
1062
+ * actions old, and vice versa.
1063
+ *
1064
+ * Keys are compared with `Object.is`, except arrays and plain objects, which are compared
1065
+ * by their contents.
1066
+ */
1067
+ computeIgnoreOldKey() {
1068
+ return [this.constructor, this.ignoreOldKeyParams()];
1069
+ }
1070
+ /**
1071
+ * Returns `true` if this action was aborted, which means its `abortSignal` is aborted, and
1072
+ * its result and errors will be ignored. An action is aborted:
1073
+ *
1074
+ * - By `ignoreOld`, when an action with the same key is dispatched after it.
1075
+ * - By `store.abort(ActionType)`, which aborts all the actions of the type in progress.
1076
+ * - By its own `abort()` method.
1077
+ *
1078
+ * You can check it inside `reduce`, after some `await`, to avoid doing things that don't
1079
+ * make sense anymore, like dispatching other actions:
1080
+ *
1081
+ * ```ts
1082
+ * async reduce() {
1083
+ * let items = await loadItems(this.tab);
1084
+ * if (!this.isAborted) this.dispatch(new LoadItemImages(items));
1085
+ * return (state: State) => state.copy({ items });
1086
+ * }
1087
+ * ```
1088
+ *
1089
+ * Once aborted, it stays aborted. It's `false` for actions that were not aborted, including
1090
+ * the ones that were not dispatched yet.
1091
+ */
1092
+ get isAborted() {
1093
+ return this._abortController?.signal.aborted ?? false;
1094
+ }
1095
+ /**
1096
+ * Aborts this action: its `abortSignal` is aborted, `isAborted` becomes `true`, and the
1097
+ * action finishes silently: its result is ignored (it doesn't change the state), and so are
1098
+ * its errors (no error dialog, it doesn't count as failed, and it isn't retried). Its status
1099
+ * has `isDispatchAborted: true`, and `dispatchAndWait` resolves.
1100
+ *
1101
+ * - If the request uses the `abortSignal`, it's cancelled right away. Otherwise, the action
1102
+ * is still in progress (`isWaiting` is `true`) until the request finishes, and only then
1103
+ * its result is ignored.
1104
+ * - An action aborted before it's dispatched doesn't run at all: `before`, `reduce` and
1105
+ * `after` are not called.
1106
+ * - Aborting an action that already finished has no effect.
1107
+ *
1108
+ * To abort all the actions of a type in progress, use `store.abort(ActionType)`. For
1109
+ * example, in `useStoreEffect`, with `onUnmount: (store) => store.abort(LoadUser)`.
1110
+ */
1111
+ abort() {
1112
+ if (this.status.isCompleted)
1113
+ return;
1114
+ this._abort('The action was aborted by abort().');
1115
+ }
1116
+ /**
1117
+ * An `AbortSignal` that is aborted when this action is aborted (see `isAborted`): by
1118
+ * `ignoreOld`, when an action with the same key is dispatched after this one; by
1119
+ * `store.abort(ActionType)`; or by its own `abort()` method. Pass it to `fetch`, or to any
1120
+ * other API that accepts an `AbortSignal`, so that the request is cancelled as soon as the
1121
+ * action is aborted:
1122
+ *
1123
+ * ```ts
1124
+ * class LoadTab extends KissAction<State> {
1125
+ * constructor(readonly tab: string) { super(); }
1126
+ * ignoreOld = true;
1127
+ *
1128
+ * async reduce() {
1129
+ * let response = await fetch(`/api/items?tab=${this.tab}`, { signal: this.abortSignal });
1130
+ * let items = await response.json();
1131
+ * return (state: State) => state.copy({ items });
1132
+ * }
1133
+ * }
1134
+ * ```
1135
+ *
1136
+ * When the signal is aborted, `fetch` rejects with an `AbortError`. You don't need to catch
1137
+ * it: the errors of an aborted action are ignored, and the action finishes silently.
1138
+ *
1139
+ * For work that doesn't accept a signal, you can check it yourself, between the steps:
1140
+ *
1141
+ * ```ts
1142
+ * let user = await loadUser(this.userId);
1143
+ * this.abortSignal.throwIfAborted();
1144
+ * let posts = await loadPosts(user);
1145
+ * ```
1146
+ *
1147
+ * The signal of an action that is never aborted is never aborted either.
1148
+ */
1149
+ get abortSignal() {
1150
+ this._abortController ??= new AbortController();
1151
+ return this._abortController.signal;
1152
+ }
1153
+ /**
1154
+ * For Kiss internal use only.
1155
+ * The controller of `abortSignal`. Created by `abortSignal` when it's first used, or by
1156
+ * `_abort()`.
1157
+ * @internal
1158
+ */
1159
+ _abortController = null;
1160
+ /**
1161
+ * For Kiss internal use only.
1162
+ * Aborts the action: its `abortSignal` is aborted, and `isAborted` becomes `true`. The
1163
+ * signal's reason is an `AbortError` (a `DOMException`, as when `fetch` is aborted) with the
1164
+ * given `reason` as its message. The store uses it in the `AbortDispatchException` that
1165
+ * finishes the action silently (see `Store._abortError`).
1166
+ * @internal
1167
+ */
1168
+ _abort(reason) {
1169
+ this._abortController ??= new AbortController();
1170
+ this._abortController.abort(new DOMException(reason, 'AbortError'));
1171
+ }
1172
+ /**
1173
+ * Override this getter if you want the action to ignore the throttle period under some
1174
+ * conditions. When it returns `true`, the action runs even inside the throttle period, and
1175
+ * starts a new throttle period. For example:
1176
+ *
1177
+ * ```ts
1178
+ * class MyAction extends KissAction<State> {
1179
+ * constructor(readonly force = false) { super(); }
1180
+ * get ignoreThrottle() { return this.force; } // Here!
1181
+ * throttle = 500;
1182
+ * ...
1183
+ * }
1184
+ * ```
1185
+ */
1186
+ get ignoreThrottle() {
1187
+ return false;
1188
+ }
1189
+ /**
1190
+ * The default lock for throttling is the action class, meaning it will throttle the dispatch
1191
+ * of actions of the same class. Override this method to customize the lock to any value.
1192
+ * For example, you can return a string, and actions with the same lock value will throttle
1193
+ * each other:
1194
+ *
1195
+ * ```ts
1196
+ * class MyAction extends KissAction<State> {
1197
+ * throttle = 500;
1198
+ * throttleLockBuilder() { return 'myLock'; }
1199
+ * ...
1200
+ * }
1201
+ * ```
1202
+ *
1203
+ * Locks are compared with `Object.is`, except arrays and plain objects, which are compared
1204
+ * by their contents. For example, `[this.constructor, this.userId]` is a valid lock.
1205
+ *
1206
+ * Note: Expired locks are removed, to prevent memory leaks.
1207
+ */
1208
+ throttleLockBuilder() {
1209
+ return this.constructor;
1210
+ }
1211
+ /**
1212
+ * Removes the throttle lock of this action, allowing an action with the same lock to be
1213
+ * dispatched again right away. You generally don't need to call this method.
1214
+ */
1215
+ removeThrottleLock() {
1216
+ this.store._removeThrottleLock(this.throttleLockBuilder());
1217
+ }
1218
+ /**
1219
+ * Removes all throttle locks, allowing all actions to be dispatched again right away.
1220
+ * You generally don't need to call this method.
1221
+ */
1222
+ removeAllThrottleLocks() {
1223
+ this.store._removeAllThrottleLocks();
1224
+ }
1225
+ /**
1226
+ * For Kiss internal use only.
1227
+ * The throttle period in milliseconds, or `null` if the action doesn't throttle, or if its
1228
+ * `throttle` value is invalid (in which case the dispatch throws).
1229
+ * @internal
1230
+ */
1231
+ get _throttleMillis() {
1232
+ const throttle = this.throttle;
1233
+ if (throttle === true)
1234
+ return 1000;
1235
+ if (typeof throttle === 'number' && Number.isFinite(throttle) && throttle >= 0)
1236
+ return throttle;
1237
+ return null;
1238
+ }
1239
+ /**
1240
+ * Override this getter if you want the action to run even while its data is still fresh.
1241
+ * When it returns `true`, the action always runs, and also starts a new fresh period for
1242
+ * its key. For example:
1243
+ *
1244
+ * ```ts
1245
+ * class LoadInformation extends KissAction<State> {
1246
+ * constructor(readonly force = false) { super(); }
1247
+ * get ignoreFresh() { return this.force; } // Here!
1248
+ * fresh = 5000;
1249
+ * ...
1250
+ * }
1251
+ * ```
1252
+ *
1253
+ * Note: If a forced run fails, its key becomes stale, even if it was fresh before.
1254
+ */
1255
+ get ignoreFresh() {
1256
+ return false;
1257
+ }
1258
+ /**
1259
+ * By default the fresh-key is based on the action class. For example, all actions of class
1260
+ * `LoadText` share the same freshness:
1261
+ *
1262
+ * ```ts
1263
+ * // This action runs.
1264
+ * dispatch(new LoadText('https://example.com'));
1265
+ *
1266
+ * // This does NOT run, because the previous LoadText is still fresh.
1267
+ * dispatch(new LoadText('https://another-url.com'));
1268
+ * ```
1269
+ *
1270
+ * You can override `freshKeyParams()` so that actions of the SAME CLASS but with different
1271
+ * parameters do not affect each other's freshness. In this example, the `url` field becomes
1272
+ * part of the fresh-key:
1273
+ *
1274
+ * ```ts
1275
+ * class LoadText extends KissAction<State> {
1276
+ * fresh = true;
1277
+ * constructor(readonly url: string) { super(); }
1278
+ *
1279
+ * // The fresh-key includes the url.
1280
+ * freshKeyParams() { return this.url; }
1281
+ * ...
1282
+ * }
1283
+ * ```
1284
+ *
1285
+ * Now, dispatching two `LoadText` actions with different `url` values allows both of them
1286
+ * to run, because each one uses a different fresh-key:
1287
+ *
1288
+ * ```ts
1289
+ * // This action runs.
1290
+ * dispatch(new LoadText('https://example.com'));
1291
+ *
1292
+ * // This also runs, because the url is different, so it has a different fresh-key.
1293
+ * dispatch(new LoadText('https://another-url.com'));
1294
+ * ```
1295
+ *
1296
+ * ## In more detail
1297
+ *
1298
+ * The default fresh-key, as returned by `computeFreshKey()`, combines the action class with
1299
+ * the value returned by `freshKeyParams()`.
1300
+ *
1301
+ * Most of the time you override `freshKeyParams()` to return one field, or an array of
1302
+ * fields:
1303
+ *
1304
+ * ```ts
1305
+ * // Fresh-key is the action class + url
1306
+ * freshKeyParams() { return this.url; }
1307
+ *
1308
+ * // Fresh-key is the action class + userId + cartId
1309
+ * freshKeyParams() { return [this.userId, this.cartId]; }
1310
+ * ```
1311
+ *
1312
+ * When `freshKeyParams()` returns `null`, the key is just the action class. In that case all
1313
+ * actions of that class share the same freshness.
1314
+ *
1315
+ * Params are compared with `Object.is`, except arrays and plain objects, which are compared
1316
+ * by their contents. For example, `[1, 'A']` and `{ id: 1 }` are valid params.
1317
+ *
1318
+ * See also:
1319
+ * - `computeFreshKey()` if you want full control over how the key is built.
1320
+ */
1321
+ freshKeyParams() {
1322
+ return null;
1323
+ }
1324
+ /**
1325
+ * In most cases you want to use the default fresh-key computation, which combines the
1326
+ * action class with the value returned by `freshKeyParams()`:
1327
+ *
1328
+ * ```ts
1329
+ * computeFreshKey() { return [this.constructor, this.freshKeyParams()]; }
1330
+ * ```
1331
+ *
1332
+ * However, if you want different action classes to share the same fresh period, you must
1333
+ * override `computeFreshKey()` and return any key you want. Some examples:
1334
+ *
1335
+ * ```ts
1336
+ * // The fresh-key is only the url, without the action class.
1337
+ * computeFreshKey() { return this.url; }
1338
+ *
1339
+ * // The fresh-key is a pair of values, without the action class.
1340
+ * computeFreshKey() { return [this.userId, this.cartId]; }
1341
+ *
1342
+ * // The fresh-key is a constant string.
1343
+ * computeFreshKey() { return 'myKey'; }
1344
+ *
1345
+ * // The fresh-key is an enum value.
1346
+ * computeFreshKey() { return MyFreshnessKey.myKey; }
1347
+ * ```
1348
+ *
1349
+ * For example, suppose you have two different actions, and you want them to share the same
1350
+ * fresh-key:
1351
+ *
1352
+ * ```ts
1353
+ * class LoadUserProfile extends KissAction<State> {
1354
+ * fresh = true;
1355
+ * constructor(readonly userId: string) { super(); }
1356
+ *
1357
+ * // The key is the userId only, without the action class.
1358
+ * computeFreshKey() { return this.userId; }
1359
+ * ...
1360
+ * }
1361
+ *
1362
+ * class LoadUserSettings extends KissAction<State> {
1363
+ * fresh = true;
1364
+ * constructor(readonly userId: string) { super(); }
1365
+ *
1366
+ * // The key is the userId only, without the action class.
1367
+ * computeFreshKey() { return this.userId; }
1368
+ * ...
1369
+ * }
1370
+ * ```
1371
+ *
1372
+ * With this setup, if you dispatch `new LoadUserProfile('123')`, then
1373
+ * `new LoadUserSettings('123')` will be aborted if dispatched within the fresh period of the
1374
+ * first action.
1375
+ *
1376
+ * Keys are compared with `Object.is`, except arrays and plain objects, which are compared
1377
+ * by their contents.
1378
+ *
1379
+ * See also:
1380
+ * - `freshKeyParams()` when you want to differentiate fresh-keys by some of the fields of
1381
+ * the action.
1382
+ */
1383
+ computeFreshKey() {
1384
+ return [this.constructor, this.freshKeyParams()];
1385
+ }
1386
+ /**
1387
+ * Removes the fresh-key used by this action, allowing an action using the same fresh-key to
1388
+ * be dispatched and run again, right away. Calling this method will make the action stale
1389
+ * immediately. You generally do not need to call this method, but if you do, use it only
1390
+ * from your action's `reduce()` or `before()` methods.
1391
+ */
1392
+ removeFreshKey() {
1393
+ this.store._removeFreshKey(this.computeFreshKey());
1394
+ }
1395
+ /**
1396
+ * Removes all fresh-keys, allowing all actions to be dispatched and run again right away.
1397
+ * Calling this method will make all actions stale immediately. You generally do not need to
1398
+ * call this method, but if you do, use it only from your action's `reduce()` or `before()`
1399
+ * methods.
1400
+ */
1401
+ removeAllFreshKeys() {
1402
+ this.store._removeAllFreshKeys();
1403
+ }
1404
+ /**
1405
+ * For Kiss internal use only.
1406
+ * The fresh period in milliseconds, or `null` if the action doesn't use `fresh`, or if its
1407
+ * `fresh` value is invalid (in which case the dispatch throws).
1408
+ * @internal
1409
+ */
1410
+ get _freshMillis() {
1411
+ const fresh = this.fresh;
1412
+ if (fresh === true)
1413
+ return 1000;
1414
+ if (typeof fresh === 'number' && Number.isFinite(fresh) && fresh >= 0)
1415
+ return fresh;
1416
+ return null;
1417
+ }
1418
+ /**
1419
+ * Set `sequential` to `true` to make actions run one at a time, in the exact order they were
1420
+ * dispatched. For example:
1421
+ *
1422
+ * ```ts
1423
+ * class SaveItem extends KissAction<State> {
1424
+ * sequential = true;
1425
+ * constructor(readonly item: Item) { super(); }
1426
+ *
1427
+ * async reduce() {
1428
+ * await fetch('https://myapi.com/items', { method: 'PUT', body: JSON.stringify(this.item) });
1429
+ * return null;
1430
+ * }
1431
+ * }
1432
+ * ```
1433
+ *
1434
+ * All actions with `sequential = true` share a single FIFO queue (first in, first out). When
1435
+ * an action is dispatched, it takes its place at the end of the queue, and then waits until
1436
+ * every action dispatched before it has finished. Only then does it run its `before`,
1437
+ * `reduce` and `after` methods.
1438
+ *
1439
+ * This works across all sequential action classes: if `SaveItem` and `DeleteItem` are both
1440
+ * sequential, they wait for each other. Two actions of the same class also enter the queue
1441
+ * and run one after the other.
1442
+ *
1443
+ * The queue position is reserved synchronously, at the moment `dispatch` is called. This
1444
+ * guarantees the run order is the dispatch order, even if the actions are dispatched from
1445
+ * different places or in quick succession.
1446
+ *
1447
+ * When an action finishes, the next action in the queue is released. This happens regardless
1448
+ * of how the action finished:
1449
+ *
1450
+ * - It completed successfully.
1451
+ * - It threw an error (from `before` or `reduce`).
1452
+ * - It was aborted by throwing an `AbortDispatchException` (from `before` or `reduce`).
1453
+ *
1454
+ * Note that when the dispatch is aborted (for example, when `abortDispatch()` returns `true`),
1455
+ * the action never enters the queue.
1456
+ *
1457
+ * ## Keys: multiple independent queues
1458
+ *
1459
+ * By default, all sequential actions share ONE queue, whose key is `null`. If you want
1460
+ * independent queues, override `sequentialKeyParams()` to return any value. Actions with the
1461
+ * same key wait for each other, while actions with different keys run in parallel. For
1462
+ * example, here each user has its own queue, so the actions of different users don't block
1463
+ * each other:
1464
+ *
1465
+ * ```ts
1466
+ * class SaveUser extends KissAction<State> {
1467
+ * sequential = true;
1468
+ * constructor(readonly userId: string) { super(); }
1469
+ * sequentialKeyParams() { return this.userId; }
1470
+ * ...
1471
+ * }
1472
+ *
1473
+ * class DeleteUser extends KissAction<State> {
1474
+ * sequential = true;
1475
+ * constructor(readonly userId: string) { super(); }
1476
+ * sequentialKeyParams() { return this.userId; }
1477
+ * ...
1478
+ * }
1479
+ * ```
1480
+ *
1481
+ * With this setup, `SaveUser('A')` and `DeleteUser('A')` run one after the other, but
1482
+ * `SaveUser('A')` and `SaveUser('B')` may run at the same time.
1483
+ *
1484
+ * Keys are removed from memory as soon as their queue becomes empty.
1485
+ *
1486
+ * ## Discarding the queue when an action fails
1487
+ *
1488
+ * Actions are often queued because each one depends on the previous ones. For example, an
1489
+ * action that creates an item, followed by one that updates it. In that case, if the first
1490
+ * action fails, running the rest makes no sense. Override `discardQueueOnError()` to return
1491
+ * `true` when you want a failure to abort all the actions that are waiting behind the failed
1492
+ * one:
1493
+ *
1494
+ * ```ts
1495
+ * class SaveItem extends KissAction<State> {
1496
+ * sequential = true;
1497
+ * discardQueueOnError(error: any) { return !(error instanceof AbortDispatchException); }
1498
+ * ...
1499
+ * }
1500
+ * ```
1501
+ *
1502
+ * The discarded actions are aborted: they don't run their `before` and `reduce` methods, and
1503
+ * they finish with an `AbortDispatchException` (which the store treats silently, without
1504
+ * showing any error dialog). Their `status.isDispatchAborted` is `true`. You can check
1505
+ * `wasDiscardedFromSequentialQueue` on those actions, if you need to know. Actions dispatched
1506
+ * after the failure are not affected, and start a fresh queue. The default is `false`, which
1507
+ * means the queue simply continues.
1508
+ *
1509
+ * ## IMPORTANT: Do not wait for an action in the same queue
1510
+ *
1511
+ * An action that is running (and therefore holds the queue) must NOT wait for another action
1512
+ * that uses the same queue. If it does, both actions will wait for each other forever
1513
+ * (a deadlock):
1514
+ *
1515
+ * ```ts
1516
+ * class Parent extends KissAction<State> {
1517
+ * sequential = true;
1518
+ *
1519
+ * async reduce() {
1520
+ * // WRONG: `Child` enters the queue behind `Parent`, and waits for
1521
+ * // `Parent` to finish. But `Parent` waits for `Child` here. Deadlock!
1522
+ * await this.dispatchAndWait(new Child());
1523
+ * return null;
1524
+ * }
1525
+ * }
1526
+ *
1527
+ * class Child extends KissAction<State> {
1528
+ * sequential = true;
1529
+ * ...
1530
+ * }
1531
+ * ```
1532
+ *
1533
+ * The same applies to any other way of waiting for a queued action, such as
1534
+ * `waitActionType(Child)`, `waitAllActions`, or a `waitCondition` that only becomes true
1535
+ * after `Child` runs.
1536
+ *
1537
+ * If you need to dispatch another action of the same queue from inside a running action, you
1538
+ * have these options:
1539
+ *
1540
+ * - Dispatch it without waiting for it: `this.dispatch(new Child())`. The child is queued and
1541
+ * will run right after the parent finishes.
1542
+ * - Give the child a different key, so it uses a different queue.
1543
+ * - Don't make the child sequential.
1544
+ *
1545
+ * ## Other notes
1546
+ *
1547
+ * - Sequential actions are always ASYNC, even if their `before` and `reduce` methods are
1548
+ * SYNC. This means you can't dispatch them with `dispatchSync`. Doing so throws a
1549
+ * `StoreException`.
1550
+ *
1551
+ * - The action only runs its `before` method when it gets its turn. So you can override
1552
+ * `before`, `reduce` and `after` as usual, and all of them run when it's the action's turn.
1553
+ *
1554
+ * - While an action is waiting in the queue, it counts as being "in progress", so
1555
+ * `isWaiting(MyAction)` returns `true` for it. This is usually what you want, as it lets
1556
+ * you show a spinner as soon as the action is dispatched. You can also check
1557
+ * `isWaitingInSequentialQueue` on the action itself.
1558
+ *
1559
+ * - Calling `store.clearInternalActionProps()` (or `store.setShutDown(true)`) discards the
1560
+ * actions waiting in all queues, as if a failed action had discarded them. The actions that
1561
+ * are running keep running, but actions dispatched after that start new queues, and don't
1562
+ * wait for them.
1563
+ *
1564
+ * ## Combining with other features
1565
+ *
1566
+ * - It can be combined with `retry` and `checkInternet`. Retries happen while the action
1567
+ * holds the queue, and the internet check happens when the action gets its turn. Note
1568
+ * that with unlimited retries, a single failing action blocks every action behind it, for
1569
+ * as long as it keeps failing. To keep the ordering and still retry, prefer a limited
1570
+ * number of retries, possibly together with `discardQueueOnError()`.
1571
+ *
1572
+ * - It can also be combined with `nonReentrant`, `throttle`, `fresh` and `OptimisticCommand`.
1573
+ * For example, `nonReentrant` plus `sequential` means duplicates are dropped while the
1574
+ * original is queued or running, and the ones that get through still run one at a time.
1575
+ * Note the throttle and fresh periods start when the action is dispatched, not when it
1576
+ * gets its turn in the queue. And the optimistic value of an `OptimisticCommand` is only
1577
+ * applied to the state when the action gets its turn, and not as soon as it's dispatched.
1578
+ *
1579
+ * - It should NOT be combined with `debounce`, because the debounce period would only start
1580
+ * when the action gets its turn in the queue, which defeats the purpose of debouncing.
1581
+ * Dispatching it with `debounce` throws a `StoreException`.
1582
+ *
1583
+ * - It should NOT be combined with `unlimitedRetryCheckInternet`. That feature aborts the
1584
+ * dispatch while another action with the same key is in progress (and a queued action does
1585
+ * count as in progress), so two actions of the same class would never queue behind each
1586
+ * other. It also retries forever while holding the queue. Dispatching it with
1587
+ * `unlimitedRetryCheckInternet` throws a `StoreException`.
1588
+ *
1589
+ * - It should NOT be combined with `ignoreOld`, since the actions already run, and apply
1590
+ * their results, in the dispatch order. Dispatching it with `ignoreOld` throws a
1591
+ * `StoreException`.
1592
+ */
1593
+ sequential = false;
1594
+ /**
1595
+ * By default, all sequential actions share a single queue, whose key is `null`. Override
1596
+ * this method to return a different key, so that only actions with the same key wait for
1597
+ * each other. The returned value is used as the queue key itself.
1598
+ *
1599
+ * For example, here each user has its own queue:
1600
+ *
1601
+ * ```ts
1602
+ * class SaveUser extends KissAction<State> {
1603
+ * sequential = true;
1604
+ * constructor(readonly userId: string) { super(); }
1605
+ * sequentialKeyParams() { return this.userId; }
1606
+ * ...
1607
+ * }
1608
+ * ```
1609
+ *
1610
+ * You may also return the action class, so that only actions of the same class wait for
1611
+ * each other:
1612
+ *
1613
+ * ```ts
1614
+ * sequentialKeyParams() { return this.constructor; }
1615
+ * ```
1616
+ *
1617
+ * Keys are compared with `Object.is`, except arrays and plain objects, which are compared
1618
+ * by their contents. For example, `[1, 'A']` and `{ id: 1 }` are valid keys.
1619
+ */
1620
+ sequentialKeyParams() {
1621
+ return null;
1622
+ }
1623
+ /**
1624
+ * Called when this sequential action finishes with an error, with that error. Return `true`
1625
+ * to abort all the actions that are currently waiting in the same queue, behind this one.
1626
+ * They will not run their `before` and `reduce` methods, and will finish with an
1627
+ * `AbortDispatchException`. Actions dispatched after this action finished are not affected.
1628
+ *
1629
+ * The default is `false`: the queue continues with the next action.
1630
+ *
1631
+ * Note the `error` is the original error thrown by `before` or `reduce`, before being
1632
+ * processed by `wrapError`. It may be an `AbortDispatchException`, if this action was
1633
+ * aborted. You may want to keep the queue in that case:
1634
+ *
1635
+ * ```ts
1636
+ * discardQueueOnError(error: any) { return !(error instanceof AbortDispatchException); }
1637
+ * ```
1638
+ *
1639
+ * Note: If `discardQueueOnError()` throws an error, the error is logged, and the queue
1640
+ * continues with the next action.
1641
+ */
1642
+ discardQueueOnError(_error) {
1643
+ return false;
1644
+ }
1645
+ /**
1646
+ * Returns `true` while this sequential action is waiting for previous actions in its queue
1647
+ * to finish. Returns `false` before the action is dispatched, once it gets its turn, and
1648
+ * after it finishes.
1649
+ */
1650
+ get isWaitingInSequentialQueue() {
1651
+ return this._isWaitingInSequentialQueue;
1652
+ }
1653
+ /**
1654
+ * Returns `true` if this sequential action was aborted because a previous action in the
1655
+ * same queue failed and returned `true` from `discardQueueOnError()`, or because the queues
1656
+ * were reset with `store.clearInternalActionProps()` (or `store.setShutDown(true)`) while it
1657
+ * was waiting.
1658
+ */
1659
+ get wasDiscardedFromSequentialQueue() {
1660
+ return this._wasDiscardedFromSequentialQueue;
1661
+ }
1662
+ /**
1663
+ * For Kiss internal use only.
1664
+ * Set by the store while this sequential action waits for its turn in the queue.
1665
+ * @internal
1666
+ */
1667
+ _isWaitingInSequentialQueue = false;
1668
+ /**
1669
+ * For Kiss internal use only.
1670
+ * Set by the store when this sequential action is discarded from its queue.
1671
+ * @internal
1672
+ */
1673
+ _wasDiscardedFromSequentialQueue = false;
1674
+ /**
1675
+ * Must return a new action instance that the timer will dispatch on each tick. This can be
1676
+ * the same action class with `Poll.once`, or a completely different action class (see the
1677
+ * documentation of `poll` for both patterns).
1678
+ *
1679
+ * Every action that uses polling must override this method. Otherwise, dispatching it throws
1680
+ * a `StoreException`.
1681
+ */
1682
+ createPollingAction() {
1683
+ throw new StoreException(`Action ${this.constructor.name} uses polling, but doesn't override createPollingAction().`);
1684
+ }
1685
+ /**
1686
+ * By default, the polling key is based on the action class. All instances of the same action
1687
+ * class share one polling timer.
1688
+ *
1689
+ * Override this to give each instance its own timer based on some field:
1690
+ *
1691
+ * ```ts
1692
+ * // Each address gets its own polling timer.
1693
+ * pollingKeyParams() { return this.address; }
1694
+ *
1695
+ * // Each (userId, walletId) pair gets its own timer.
1696
+ * pollingKeyParams() { return [this.userId, this.walletId]; }
1697
+ * ```
1698
+ *
1699
+ * When `pollingKeyParams()` returns `null` (the default), the key is just the action class.
1700
+ *
1701
+ * Params are compared with `Object.is`, except arrays and plain objects, which are compared
1702
+ * by their contents. For example, `[1, 'A']` and `{ id: 1 }` are valid params.
1703
+ */
1704
+ pollingKeyParams() {
1705
+ return null;
1706
+ }
1707
+ /**
1708
+ * Returns the key used to identify this action's polling timer.
1709
+ *
1710
+ * The default combines the action class with `pollingKeyParams()`:
1711
+ *
1712
+ * ```ts
1713
+ * computePollingKey() { return [this.constructor, this.pollingKeyParams()]; }
1714
+ * ```
1715
+ *
1716
+ * Override this for full control, for example to share a timer across different action
1717
+ * classes:
1718
+ *
1719
+ * ```ts
1720
+ * computePollingKey() { return 'shared-market-data'; }
1721
+ * ```
1722
+ *
1723
+ * Keys are compared with `Object.is`, except arrays and plain objects, which are compared
1724
+ * by their contents.
1725
+ */
1726
+ computePollingKey() {
1727
+ return [this.constructor, this.pollingKeyParams()];
1728
+ }
1729
+ /**
1730
+ * Stops all polling at once, for all polling keys, as if `Poll.stop` was dispatched for each
1731
+ * of them. This is probably useful during logout or similar scenarios. Runs that are already
1732
+ * in progress still finish, but no new ticks are dispatched.
1733
+ */
1734
+ stopAllPolling() {
1735
+ this.store._stopAllPolling();
1736
+ }
1737
+ /**
1738
+ * For Kiss internal use only.
1739
+ * The delay between polling ticks in milliseconds, or `null` if the `pollInterval` value is
1740
+ * invalid (in which case the dispatch throws).
1741
+ * @internal
1742
+ */
1743
+ get _pollIntervalMillis() {
1744
+ const pollInterval = this.pollInterval;
1745
+ if (pollInterval === undefined)
1746
+ return 10000;
1747
+ if (typeof pollInterval === 'number' && Number.isFinite(pollInterval) && pollInterval >= 0)
1748
+ return pollInterval;
1749
+ return null;
1750
+ }
1751
+ /** @internal */
1752
+ _retry = {
1753
+ on: false,
1754
+ attempts: 0,
1755
+ initialDelay: 350,
1756
+ multiplier: 2,
1757
+ maxRetries: 3,
1758
+ maxDelay: 5000,
1759
+ unlimitedRetries: false,
1760
+ currentDelay: null,
1761
+ };
1762
+ get ifRetryIsOn() {
1763
+ return this.retry?.on === true;
1764
+ }
1765
+ /**
1766
+ * Returns true if the action should retry after it failed with the given `error`. It's called
1767
+ * by `retry` and `unlimitedRetryCheckInternet`, after each failed attempt that still has
1768
+ * retries left, and by an `OptimisticCommand` with `retry`, after each failed
1769
+ * `sendCommandToServer`.
1770
+ *
1771
+ * The default returns `true` for every error, including `UserException`s: a `UserException`
1772
+ * thrown by the reducer may well be transient ("Could not reach the server"), and only the
1773
+ * action knows. Override it to give up on errors that are permanent, like a 404, a 401, or a
1774
+ * validation error from the server, which would fail again on every retry:
1775
+ *
1776
+ * ```ts
1777
+ * class LoadUser extends Action {
1778
+ * retry = { on: true };
1779
+ *
1780
+ * shouldRetry(error: unknown, attempt: number) {
1781
+ * return !(error instanceof NotFoundError) && !(error instanceof UnauthorizedError);
1782
+ * }
1783
+ *
1784
+ * async reduce() { ... }
1785
+ * }
1786
+ * ```
1787
+ *
1788
+ * - `error` is the error thrown by the attempt that just failed.
1789
+ * - `attempt` is the number of that attempt, starting at `1`. It's the same as `this.attempts`.
1790
+ *
1791
+ * When it returns `false`, the action fails right away with that error, as if the retries had
1792
+ * run out. With `unlimitedRetryCheckInternet`, this is the only way to stop an action that
1793
+ * would otherwise retry forever. It's not called when there is no internet, since the action
1794
+ * then waits for the internet, and doesn't fail.
1795
+ *
1796
+ * It's not called when the retries ran out (the action fails anyway), nor for an
1797
+ * `AbortDispatchException`, which means the action was aborted on purpose, and is never
1798
+ * retried. If `shouldRetry` itself throws, the action fails with that error.
1799
+ */
1800
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
1801
+ shouldRetry(error, attempt) {
1802
+ return true;
1803
+ }
1804
+ /**
1805
+ * For Kiss internal use only.
1806
+ * Calls the (protected) `shouldRetry()` method.
1807
+ * @internal
1808
+ */
1809
+ _shouldRetry(error, attempt) {
1810
+ return this.shouldRetry(error, attempt);
1811
+ }
1812
+ /**
1813
+ * For Kiss internal use only.
1814
+ * Start with the `initialDelay`, and then increase it by `multiplier` each time this is called.
1815
+ * If the delay exceeds the given `maxDelay` (by default, the retry `maxDelay`), it will be set
1816
+ * to `maxDelay`.
1817
+ * @internal
1818
+ */
1819
+ _nextRetryDelay(maxDelay = this._retry.maxDelay) {
1820
+ const retry = this._retry;
1821
+ retry.currentDelay = (retry.currentDelay == null)
1822
+ ? retry.initialDelay
1823
+ : retry.currentDelay * retry.multiplier;
1824
+ if (retry.currentDelay > maxDelay)
1825
+ retry.currentDelay = maxDelay;
1826
+ return retry.currentDelay;
1827
+ }
1828
+ /**
1829
+ * For Kiss internal use only.
1830
+ * True if `unlimitedRetryCheckInternet` is turned on. Note this doesn't validate it, which
1831
+ * only happens when the action is dispatched.
1832
+ * @internal
1833
+ */
1834
+ get _isUnlimitedRetryCheckInternet() {
1835
+ const value = this.unlimitedRetryCheckInternet;
1836
+ return value === true || (typeof value === 'object' && value !== null);
1837
+ }
1838
+ /**
1839
+ * For Kiss internal use only.
1840
+ * The maximum delay between retries when there is no internet, for actions that use
1841
+ * `unlimitedRetryCheckInternet`. Set when the action is dispatched.
1842
+ * @internal
1843
+ */
1844
+ _maxDelayNoInternet = 1000;
1845
+ /**
1846
+ * For Kiss internal use only.
1847
+ * Checks the internet connection with the (protected) `hasInternet()` method, unless it's
1848
+ * being simulated with `internetOnOffSimulation`, which takes precedence. Used by
1849
+ * `checkInternet` and `unlimitedRetryCheckInternet`.
1850
+ * @internal
1851
+ */
1852
+ _hasInternet() {
1853
+ const simulation = this.internetOnOffSimulation;
1854
+ if (simulation === true || simulation === false)
1855
+ return Promise.resolve(simulation);
1856
+ return this.hasInternet();
1857
+ }
1858
+ /**
1859
+ * Returns a promise which will resolve when the given state `condition` is true.
1860
+ * If the condition is already true when the method is called, the promise resolves immediately.
1861
+ *
1862
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
1863
+ * is not met in `timeoutMillis` milliseconds, the promise rejects with a `TimeoutException`,
1864
+ * and the condition stops being checked. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
1865
+ * (or -1, or `Infinity`):
1866
+ *
1867
+ * ```ts
1868
+ * await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 }); // 1 second.
1869
+ * await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 0 }); // No timeout.
1870
+ * ```
1871
+ *
1872
+ * To handle the timeout, you can catch the `TimeoutException`:
1873
+ *
1874
+ * ```ts
1875
+ * try { await this.waitCondition(condition, { timeoutMillis: 5000 }); }
1876
+ * catch (error) { if (error instanceof TimeoutException) { ... } else throw error; }
1877
+ * ```
1878
+ *
1879
+ * Or, you can pass an `onTimeout` callback. If the timeout expires, `onTimeout` is called,
1880
+ * and the promise resolves with `null` instead of rejecting. If `onTimeout` throws, the
1881
+ * promise rejects with that error:
1882
+ *
1883
+ * ```ts
1884
+ * await this.waitCondition(condition, { timeoutMillis: 5000, onTimeout: () => { ... } });
1885
+ * ```
1886
+ *
1887
+ * This method is useful in tests, and it returns the action which changed
1888
+ * the store state into the condition, in case you need it:
1889
+ *
1890
+ * ```typescript
1891
+ * let action = await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
1892
+ * expect(action instanceof ChangeNameAction).toBe(true);
1893
+ * ```
1894
+ *
1895
+ * This method is also eventually useful in production code, but note that while it waits,
1896
+ * the condition runs on EVERY state change. A few short-lived waits are fine. But many waits,
1897
+ * or waits that may never complete (especially with no timeout), add a cost to every state
1898
+ * change, for as long as the store lives, since there is no way to cancel a wait. In
1899
+ * production, it's often better to put the logic in an action, or to react to the selected
1900
+ * state in your components.
1901
+ *
1902
+ * Examples:
1903
+ *
1904
+ * ```ts
1905
+ * // Dispatches an actions that changes the state, then await for the state change:
1906
+ * expect(this.state.name).toBe('John');
1907
+ * this.dispatch(new ChangeNameAction('Bill'));
1908
+ * let action = await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
1909
+ * expect(action instanceof ChangeNameAction).toBe(true);
1910
+ * expect(this.state.name).toBe('Bill');
1911
+ *
1912
+ * // Dispatches two actions in PARALLEL and wait for their TYPES:
1913
+ * expect(this.state.portfolio).toEqual(['TSLA']);
1914
+ * this.dispatch(new BuyAction('IBM'));
1915
+ * this.dispatch(new SellAction('TSLA'));
1916
+ * await this.waitAllActionTypes([BuyAction, SellAction]);
1917
+ * expect(this.state.portfolio).toEqual(['IBM']);
1918
+ *
1919
+ * // Dispatches two actions in PARALLEL and wait for them:
1920
+ * let action1 = new BuyAction('IBM');
1921
+ * let action2 = new SellAction('TSLA');
1922
+ * this.dispatch(action1);
1923
+ * this.dispatch(action2);
1924
+ * await this.waitAllActions([action1, action2]);
1925
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
1926
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
1927
+ *
1928
+ * // Dispatches two actions in SERIES and wait for them:
1929
+ * await this.dispatchAndWait(new BuyAction('IBM'));
1930
+ * await this.dispatchAndWait(new SellAction('TSLA'));
1931
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
1932
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
1933
+ *
1934
+ * // Dispatches an action and waits until no action of its type is in progress.
1935
+ * this.dispatch(new ChangeNameAction('Bill'));
1936
+ * let action = await this.waitActionType(ChangeNameAction);
1937
+ * expect(action instanceof ChangeNameAction).toBe(true);
1938
+ * expect(action?.status.isCompletedOk).toBe(true);
1939
+ * expect(this.state.name).toBe('Bill');
1940
+ *
1941
+ * // Wait until some action of the given types is dispatched.
1942
+ * this.dispatch(new ProcessStocksAction());
1943
+ * let action = await this.waitAnyActionTypeFinishes([BuyAction, SellAction]);
1944
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
1945
+ * ```
1946
+ *
1947
+ * See also:
1948
+ * `waitCondition` - Waits until the state is in a given condition.
1949
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
1950
+ * `waitAllActions` - Waits until the given actions are NOT in progress.
1951
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
1952
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1953
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1954
+ */
1955
+ waitCondition(condition, { timeoutMillis, onTimeout, }) {
1956
+ return this.store.waitCondition(condition, { timeoutMillis, onTimeout });
1957
+ }
1958
+ /**
1959
+ * Returns a Promise that resolves when some actions meet the given `condition`.
1960
+ *
1961
+ * If `completeImmediately` is false (the default), this method will throw an error if the
1962
+ * condition was already true when the method was called. Otherwise, the promise will complete
1963
+ * immediately and throw no error.
1964
+ *
1965
+ * The `condition` is a function that takes the set of actions "in progress", as well as an
1966
+ * action that just entered the set (by being dispatched) or left the set (by finishing
1967
+ * dispatching). The function should return `true` when the condition is met, and `false`
1968
+ * otherwise. For example:
1969
+ *
1970
+ * ```ts
1971
+ * let action = await this.waitActionCondition((actionsInProgress, triggerAction) => { ... });
1972
+ * ```
1973
+ *
1974
+ * Important: Your condition function should NOT modify the set of actions.
1975
+ *
1976
+ * You get back the set of the actions being dispatched that met the condition, as well as
1977
+ * the action that triggered the condition by being added or removed from the set.
1978
+ *
1979
+ * Note: The condition is only checked when some action is dispatched or finishes dispatching.
1980
+ * It's not checked every time action statuses change.
1981
+ *
1982
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1983
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1984
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1985
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1986
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1987
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1988
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1989
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1990
+ *
1991
+ * Examples:
1992
+ *
1993
+ * ```ts
1994
+ * // Dispatches an actions that changes the state, then await for the state change:
1995
+ * expect(this.state.name).toBe('John');
1996
+ * this.dispatch(new ChangeNameAction('Bill'));
1997
+ * let action = await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
1998
+ * expect(action instanceof ChangeNameAction).toBe(true);
1999
+ * expect(this.state.name).toBe('Bill');
2000
+ *
2001
+ * // Dispatches two actions in PARALLEL and wait for their TYPES:
2002
+ * expect(this.state.portfolio).toEqual(['TSLA']);
2003
+ * this.dispatch(new BuyAction('IBM'));
2004
+ * this.dispatch(new SellAction('TSLA'));
2005
+ * await this.waitAllActionTypes([BuyAction, SellAction]);
2006
+ * expect(this.state.portfolio).toEqual(['IBM']);
2007
+ *
2008
+ * // Dispatches two actions in PARALLEL and wait for them:
2009
+ * let action1 = new BuyAction('IBM');
2010
+ * let action2 = new SellAction('TSLA');
2011
+ * this.dispatch(action1);
2012
+ * this.dispatch(action2);
2013
+ * await this.waitAllActions([action1, action2]);
2014
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2015
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2016
+ *
2017
+ * // Dispatches two actions in SERIES and wait for them:
2018
+ * await this.dispatchAndWait(new BuyAction('IBM'));
2019
+ * await this.dispatchAndWait(new SellAction('TSLA'));
2020
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2021
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2022
+ *
2023
+ * // Dispatches an action and waits until no action of its type is in progress.
2024
+ * this.dispatch(new ChangeNameAction('Bill'));
2025
+ * let action = await this.waitActionType(ChangeNameAction);
2026
+ * expect(action instanceof ChangeNameAction).toBe(true);
2027
+ * expect(action?.status.isCompletedOk).toBe(true);
2028
+ * expect(this.state.name).toBe('Bill');
2029
+ *
2030
+ * // Wait until some action of the given types is dispatched.
2031
+ * this.dispatch(new ProcessStocksAction());
2032
+ * let action = await this.waitAnyActionTypeFinishes([BuyAction, SellAction]);
2033
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2034
+ * ```
2035
+ *
2036
+ * See also:
2037
+ * `waitCondition` - Waits until the state is in a given condition.
2038
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
2039
+ * `waitAllActions` - Waits until the given actions are NOT in progress.
2040
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
2041
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
2042
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
2043
+ *
2044
+ * You should only use this method in tests.
2045
+ */
2046
+ async waitActionCondition(
2047
+ //
2048
+ /// The condition receives the current actions in progress, and the action that triggered the condition.
2049
+ condition, {
2050
+ // If `completeImmediately` is `false` (the default), this method will throw an error if the
2051
+ // condition is already true when the method is called. Otherwise, the promise will complete
2052
+ // immediately and throw no error.
2053
+ completeImmediately = false,
2054
+ //
2055
+ // The maximum time to wait for the condition to be met. The default is 3 seconds.
2056
+ // To disable the timeout, make it 0 or -1.
2057
+ timeoutMillis = null, onTimeout, } = {}) {
2058
+ return this.store.waitActionCondition(condition, {
2059
+ completeImmediately: completeImmediately,
2060
+ timeoutMillis: timeoutMillis,
2061
+ onTimeout: onTimeout,
2062
+ });
2063
+ }
2064
+ /**
2065
+ * Returns a promise that resolves when ALL given actions finished dispatching.
2066
+ * You MUST provide at least one action, or the promise rejects with a `StoreException`.
2067
+ *
2068
+ * If `completeImmediately` is false (the default), this method will throw an error if none
2069
+ * of the given actions are in progress when the method is called. Otherwise, the promise will
2070
+ * complete immediately and throw no error.
2071
+ *
2072
+ * The current action itself is ignored if present in `actions`. The current action is in
2073
+ * progress while its reducer runs, so waiting for it would never complete. If `actions`
2074
+ * contains only the current action, there is nothing else to wait for, and the promise
2075
+ * completes immediately.
2076
+ *
2077
+ * Note: Unlike `store.waitAllActions`, this method can't wait until NO actions are in
2078
+ * progress (by passing an empty list or `null`), since the current action is itself in
2079
+ * progress. Waiting for specific actions to finish is safe in production, as long as you're
2080
+ * waiting for actions you just dispatched.
2081
+ *
2082
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
2083
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
2084
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
2085
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
2086
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
2087
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
2088
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
2089
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
2090
+ *
2091
+ * Examples:
2092
+ *
2093
+ * ```ts
2094
+ * // Dispatches an actions that changes the state, then await for the state change:
2095
+ * expect(this.state.name).toBe('John');
2096
+ * this.dispatch(new ChangeNameAction('Bill'));
2097
+ * let action = await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
2098
+ * expect(action instanceof ChangeNameAction).toBe(true);
2099
+ * expect(this.state.name).toBe('Bill');
2100
+ *
2101
+ * // Dispatches two actions in PARALLEL and wait for their TYPES:
2102
+ * expect(this.state.portfolio).toEqual(['TSLA']);
2103
+ * this.dispatch(new BuyAction('IBM'));
2104
+ * this.dispatch(new SellAction('TSLA'));
2105
+ * await this.waitAllActionTypes([BuyAction, SellAction]);
2106
+ * expect(this.state.portfolio).toEqual(['IBM']);
2107
+ *
2108
+ * // Dispatches two actions in PARALLEL and wait for them:
2109
+ * let action1 = new BuyAction('IBM');
2110
+ * let action2 = new SellAction('TSLA');
2111
+ * this.dispatch(action1);
2112
+ * this.dispatch(action2);
2113
+ * await this.waitAllActions([action1, action2]);
2114
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2115
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2116
+ *
2117
+ * // Dispatches two actions in SERIES and wait for them:
2118
+ * await this.dispatchAndWait(new BuyAction('IBM'));
2119
+ * await this.dispatchAndWait(new SellAction('TSLA'));
2120
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2121
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2122
+ *
2123
+ * // Dispatches an action and waits until no action of its type is in progress.
2124
+ * this.dispatch(new ChangeNameAction('Bill'));
2125
+ * let action = await this.waitActionType(ChangeNameAction);
2126
+ * expect(action instanceof ChangeNameAction).toBe(true);
2127
+ * expect(action?.status.isCompletedOk).toBe(true);
2128
+ * expect(this.state.name).toBe('Bill');
2129
+ *
2130
+ * // Wait until some action of the given types is dispatched.
2131
+ * this.dispatch(new ProcessStocksAction());
2132
+ * let action = await this.waitAnyActionTypeFinishes([BuyAction, SellAction]);
2133
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2134
+ * ```
2135
+ *
2136
+ * See also:
2137
+ * `waitCondition` - Waits until the state is in a given condition.
2138
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
2139
+ * `waitAllActions` - Waits until the given actions are NOT in progress.
2140
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
2141
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
2142
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
2143
+ *
2144
+ * You should only use this method in tests.
2145
+ */
2146
+ waitAllActions(actions, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
2147
+ // The current action is in progress, so waiting until no actions are in progress would
2148
+ // never complete.
2149
+ if (!actions || (actions.length === 0))
2150
+ return Promise.reject(new StoreException('Inside an action, you have to provide a non-empty list of actions to waitAllActions, ' +
2151
+ 'since the action itself is in progress, so waiting until no actions are in progress ' +
2152
+ 'would never complete.'));
2153
+ // The current action is in progress, so waiting for it would never complete.
2154
+ const otherActions = actions.filter(action => action !== this);
2155
+ // Nothing else to wait for: resolve right away, with the actions in progress.
2156
+ if (otherActions.length === 0)
2157
+ return this.store.waitActionCondition(() => true, { completeImmediately: true });
2158
+ return this.store.waitAllActions(otherActions, {
2159
+ completeImmediately: completeImmediately,
2160
+ timeoutMillis: timeoutMillis,
2161
+ onTimeout: onTimeout,
2162
+ });
2163
+ }
2164
+ /**
2165
+ * Returns a promise that completes when an action of the given type is NOT in progress
2166
+ * (it's not being dispatched):
2167
+ *
2168
+ * - If NO action of the given type is currently in progress when the method is called,
2169
+ * and `completeImmediately` is false, this method will throw an error.
2170
+ *
2171
+ * - If NO action of the given type is currently in progress when the method is called,
2172
+ * and `completeImmediately` is true (the default), the promise completes immediately, returns `null`,
2173
+ * and throws no error.
2174
+ *
2175
+ * - If an action of the given type is in progress, the promise completes when the action
2176
+ * finishes, and returns the action. You can use the returned action to check its `status`:
2177
+ *
2178
+ * ```ts
2179
+ * let action = await this.waitActionType(MyAction);
2180
+ * expect(action?.status.originalError).toBeInstanceOf(UserException);
2181
+ * ```
2182
+ *
2183
+ * An action can't wait for its own type, since the action itself is in progress while its
2184
+ * reducer runs, so the wait would never complete. Calling `waitActionType` with the type of
2185
+ * the current action rejects right away with a `StoreException`. To run actions of the same
2186
+ * type one at a time, use `sequential = true` instead.
2187
+ *
2188
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
2189
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
2190
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
2191
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
2192
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
2193
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
2194
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
2195
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
2196
+ *
2197
+ * Examples:
2198
+ *
2199
+ * ```ts
2200
+ * // Dispatches an actions that changes the state, then await for the state change:
2201
+ * expect(this.state.name).toBe('John');
2202
+ * this.dispatch(new ChangeNameAction('Bill'));
2203
+ * let action = await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
2204
+ * expect(action instanceof ChangeNameAction).toBe(true);
2205
+ * expect(this.state.name).toBe('Bill');
2206
+ *
2207
+ * // Dispatches two actions in PARALLEL and wait for their TYPES:
2208
+ * expect(this.state.portfolio).toEqual(['TSLA']);
2209
+ * this.dispatch(new BuyAction('IBM'));
2210
+ * this.dispatch(new SellAction('TSLA'));
2211
+ * await this.waitAllActionTypes([BuyAction, SellAction]);
2212
+ * expect(this.state.portfolio).toEqual(['IBM']);
2213
+ *
2214
+ * // Dispatches two actions in PARALLEL and wait for them:
2215
+ * let action1 = new BuyAction('IBM');
2216
+ * let action2 = new SellAction('TSLA');
2217
+ * this.dispatch(action1);
2218
+ * this.dispatch(action2);
2219
+ * await this.waitAllActions([action1, action2]);
2220
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2221
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2222
+ *
2223
+ * // Dispatches two actions in SERIES and wait for them:
2224
+ * await this.dispatchAndWait(new BuyAction('IBM'));
2225
+ * await this.dispatchAndWait(new SellAction('TSLA'));
2226
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2227
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2228
+ *
2229
+ * // Dispatches an action and waits until no action of its type is in progress.
2230
+ * this.dispatch(new ChangeNameAction('Bill'));
2231
+ * let action = await this.waitActionType(ChangeNameAction);
2232
+ * expect(action instanceof ChangeNameAction).toBe(true);
2233
+ * expect(action?.status.isCompletedOk).toBe(true);
2234
+ * expect(this.state.name).toBe('Bill');
2235
+ *
2236
+ * // Wait until some action of the given types is dispatched.
2237
+ * this.dispatch(new ProcessStocksAction());
2238
+ * let action = await this.waitAnyActionTypeFinishes([BuyAction, SellAction]);
2239
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2240
+ * ```
2241
+ *
2242
+ * See also:
2243
+ * `waitCondition` - Waits until the state is in a given condition.
2244
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
2245
+ * `waitAllActions` - Waits until the given actions are NOT in progress.
2246
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
2247
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
2248
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
2249
+ *
2250
+ * You should only use this method in tests.
2251
+ */
2252
+ async waitActionType(actionType, { completeImmediately = true, timeoutMillis = null, onTimeout, } = {}) {
2253
+ // The current action is in progress, so waiting for its own type would never complete.
2254
+ if (actionType === this.constructor)
2255
+ throw new StoreException(`Action ${actionType.name} cannot wait for its own type with ` +
2256
+ `waitActionType(${actionType.name}), because it would wait forever for itself to ` +
2257
+ 'finish. To run actions of the same type one at a time, use sequential = true instead.');
2258
+ return this.store.waitActionType(actionType, {
2259
+ completeImmediately: completeImmediately,
2260
+ timeoutMillis: timeoutMillis,
2261
+ onTimeout: onTimeout,
2262
+ });
2263
+ }
2264
+ /**
2265
+ * Returns a promise that completes when ALL actions of the given type are NOT in progress
2266
+ * (none of them is being dispatched):
2267
+ *
2268
+ * - If NO action of the given types is currently in progress when the method is called,
2269
+ * and `completeImmediately` is false, this method will throw an error.
2270
+ *
2271
+ * - If NO action of the given type is currently in progress when the method is called,
2272
+ * and `completeImmediately` is true (the default), the promise completes immediately and throws no error.
2273
+ *
2274
+ * - If any action of the given types is in progress, the promise completes only when
2275
+ * no action of the given types is in progress anymore.
2276
+ *
2277
+ * You MUST provide at least one action type, or the promise rejects with a `StoreException`.
2278
+ * Unlike `store.waitAllActionTypes`, this method can't wait until NO actions are in progress
2279
+ * (by passing an empty list), since the current action is itself in progress.
2280
+ *
2281
+ * The type of the current action is ignored if present in `actionTypes`, since the current
2282
+ * action is in progress while its reducer runs, so waiting for its type would never complete.
2283
+ * If `actionTypes` contains only the type of the current action, there is nothing else to
2284
+ * wait for, and the promise completes immediately.
2285
+ *
2286
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
2287
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
2288
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
2289
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
2290
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
2291
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
2292
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
2293
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
2294
+ *
2295
+ * Examples:
2296
+ *
2297
+ * ```ts
2298
+ * // Dispatches an actions that changes the state, then await for the state change:
2299
+ * expect(this.state.name).toBe('John');
2300
+ * this.dispatch(new ChangeNameAction('Bill'));
2301
+ * let action = await this.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
2302
+ * expect(action instanceof ChangeNameAction).toBe(true);
2303
+ * expect(this.state.name).toBe('Bill');
2304
+ *
2305
+ * // Dispatches two actions in PARALLEL and wait for their TYPES:
2306
+ * expect(this.state.portfolio).toEqual(['TSLA']);
2307
+ * this.dispatch(new BuyAction('IBM'));
2308
+ * this.dispatch(new SellAction('TSLA'));
2309
+ * await this.waitAllActionTypes([BuyAction, SellAction]);
2310
+ * expect(this.state.portfolio).toEqual(['IBM']);
2311
+ *
2312
+ * // Dispatches two actions in PARALLEL and wait for them:
2313
+ * let action1 = new BuyAction('IBM');
2314
+ * let action2 = new SellAction('TSLA');
2315
+ * this.dispatch(action1);
2316
+ * this.dispatch(action2);
2317
+ * await this.waitAllActions([action1, action2]);
2318
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2319
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2320
+ *
2321
+ * // Dispatches two actions in SERIES and wait for them:
2322
+ * await this.dispatchAndWait(new BuyAction('IBM'));
2323
+ * await this.dispatchAndWait(new SellAction('TSLA'));
2324
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2325
+ * expect(this.state.portfolio.includes('TSLA')).toBe(false);
2326
+ *
2327
+ * // Dispatches an action and waits until no action of its type is in progress.
2328
+ * this.dispatch(new ChangeNameAction('Bill'));
2329
+ * let action = await this.waitActionType(ChangeNameAction);
2330
+ * expect(action instanceof ChangeNameAction).toBe(true);
2331
+ * expect(action?.status.isCompletedOk).toBe(true);
2332
+ * expect(this.state.name).toBe('Bill');
2333
+ *
2334
+ * // Wait until some action of the given types is dispatched.
2335
+ * this.dispatch(new ProcessStocksAction());
2336
+ * let action = await this.waitAnyActionTypeFinishes([BuyAction, SellAction]);
2337
+ * expect(this.state.portfolio.includes('IBM')).toBe(true);
2338
+ * ```
2339
+ *
2340
+ * See also:
2341
+ * `waitCondition` - Waits until the state is in a given condition.
2342
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
2343
+ * `waitAllActions` - Waits until the given actions are NOT in progress.
2344
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
2345
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
2346
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
2347
+ *
2348
+ * You should only use this method in tests.
2349
+ */
2350
+ async waitAllActionTypes(actionTypes, { completeImmediately = true, timeoutMillis = null, onTimeout, } = {}) {
2351
+ // The current action is in progress, so waiting until no actions are in progress would
2352
+ // never complete.
2353
+ if (actionTypes.length === 0)
2354
+ throw new StoreException('Inside an action, you have to provide a non-empty list of action types to ' +
2355
+ 'waitAllActionTypes, since the action itself is in progress, so waiting until no ' +
2356
+ 'actions are in progress would never complete.');
2357
+ // The current action is in progress, so waiting for its own type would never complete.
2358
+ const otherTypes = actionTypes.filter(type => type !== this.constructor);
2359
+ // Nothing else to wait for.
2360
+ if (otherTypes.length === 0)
2361
+ return;
2362
+ return this.store.waitAllActionTypes(otherTypes, {
2363
+ completeImmediately: completeImmediately,
2364
+ timeoutMillis: timeoutMillis,
2365
+ onTimeout: onTimeout,
2366
+ });
2367
+ }
2368
+ async waitAnyActionTypeFinishes(actionTypes, { timeoutMillis = null, onTimeout, } = {}) {
2369
+ return this.store.waitAnyActionTypeFinishes(actionTypes, {
2370
+ timeoutMillis: timeoutMillis,
2371
+ onTimeout: onTimeout,
2372
+ });
2373
+ }
2374
+ /**
2375
+ * For Kiss internal use only.
2376
+ * Sets the store and the initial state, so that the action can access them.
2377
+ * @internal
2378
+ */
2379
+ _setStore(_store) {
2380
+ this._store = _store;
2381
+ this._initialState = _store.state;
2382
+ }
2383
+ /**
2384
+ * For Kiss internal use only.
2385
+ * @internal
2386
+ */
2387
+ _injectStore(_store) {
2388
+ this._setStore(_store);
2389
+ if (this.retry) {
2390
+ this._validateRetry(this.retry);
2391
+ // Options that are not set (`undefined`) must not replace their defaults.
2392
+ const options = Object.fromEntries(Object.entries(this.retry).filter(([, value]) => value !== undefined));
2393
+ this._retry = { ...this._retry, on: true, ...options };
2394
+ this.retry = this._retry;
2395
+ }
2396
+ const debounce = this.debounce;
2397
+ if (debounce !== undefined && typeof debounce !== 'boolean' &&
2398
+ !(typeof debounce === 'number' && Number.isFinite(debounce) && debounce >= 0))
2399
+ throw new StoreException(`Action ${this.constructor.name} has an invalid debounce: ` +
2400
+ `it must be a boolean, or a number >= 0 (milliseconds), but got ` +
2401
+ `${typeof debounce === 'string' ? `"${debounce}"` : String(debounce)}.`);
2402
+ if (this._debounceMillis !== null && this.ifRetryIsOn)
2403
+ throw new StoreException(`Action ${this.constructor.name} uses both debounce and retry, which can't be combined. ` +
2404
+ 'Remove one of them.');
2405
+ const throttle = this.throttle;
2406
+ if (throttle !== undefined && typeof throttle !== 'boolean' && this._throttleMillis === null)
2407
+ throw new StoreException(`Action ${this.constructor.name} has an invalid throttle: ` +
2408
+ `it must be a boolean, or a number >= 0 (milliseconds), but got ` +
2409
+ `${typeof throttle === 'string' ? `"${throttle}"` : String(throttle)}.`);
2410
+ if (this._throttleMillis !== null && this.nonReentrant)
2411
+ throw new StoreException(`Action ${this.constructor.name} uses both throttle and nonReentrant, which can't be combined. ` +
2412
+ 'Remove one of them.');
2413
+ const fresh = this.fresh;
2414
+ if (fresh !== undefined && typeof fresh !== 'boolean' && this._freshMillis === null)
2415
+ throw new StoreException(`Action ${this.constructor.name} has an invalid fresh: ` +
2416
+ `it must be a boolean, or a number >= 0 (milliseconds), but got ` +
2417
+ `${typeof fresh === 'string' ? `"${fresh}"` : String(fresh)}.`);
2418
+ if (this._freshMillis !== null && this.nonReentrant)
2419
+ throw new StoreException(`Action ${this.constructor.name} uses both fresh and nonReentrant, which can't be combined. ` +
2420
+ 'Remove one of them.');
2421
+ if (this._freshMillis !== null && this._throttleMillis !== null)
2422
+ throw new StoreException(`Action ${this.constructor.name} uses both fresh and throttle, which can't be combined. ` +
2423
+ 'Remove one of them.');
2424
+ const checkInternet = this.checkInternet;
2425
+ if (checkInternet && checkInternet.abort === true && checkInternet.dialog !== undefined)
2426
+ throw new StoreException(`Action ${this.constructor.name} has an invalid checkInternet: ` +
2427
+ 'it can\'t have both `dialog` and `abort: true`. Remove one of them.');
2428
+ if (this.sequential && this._debounceMillis !== null)
2429
+ throw new StoreException(`Action ${this.constructor.name} uses both sequential and debounce, which can't be combined. ` +
2430
+ 'Remove one of them.');
2431
+ if (this.ignoreOld)
2432
+ this._validateIgnoreOld();
2433
+ if (this.poll !== undefined)
2434
+ this._validatePolling();
2435
+ if (this.unlimitedRetryCheckInternet !== undefined)
2436
+ this._injectUnlimitedRetryCheckInternet();
2437
+ }
2438
+ /**
2439
+ * Throws a `StoreException` if this action uses `unlimitedRetryCheckInternet` in a way that is
2440
+ * not allowed. Otherwise, if it's on, sets up its retry options.
2441
+ */
2442
+ _injectUnlimitedRetryCheckInternet() {
2443
+ const value = this.unlimitedRetryCheckInternet;
2444
+ const name = this.constructor.name;
2445
+ if (typeof value !== 'boolean' && (typeof value !== 'object' || value === null || Array.isArray(value)))
2446
+ throw new StoreException(`Action ${name} has an invalid unlimitedRetryCheckInternet: ` +
2447
+ `it must be a boolean, or an object with the retry options, but got ` +
2448
+ `${typeof value === 'string' ? `"${value}"` : String(value)}.`);
2449
+ if (!this._isUnlimitedRetryCheckInternet)
2450
+ return;
2451
+ const options = (value === true) ? {} : value;
2452
+ const isNumber = (v) => typeof v === 'number' && Number.isFinite(v);
2453
+ const check = (option, isValid, rule) => {
2454
+ const optionValue = options[option];
2455
+ if (optionValue !== undefined && !isValid(optionValue))
2456
+ throw new StoreException(`Action ${name} has an invalid unlimitedRetryCheckInternet option: ` +
2457
+ `unlimitedRetryCheckInternet.${option} ${rule}, but got ` +
2458
+ `${typeof optionValue === 'string' ? `"${optionValue}"` : String(optionValue)}.`);
2459
+ };
2460
+ check('initialDelay', v => isNumber(v) && v >= 0, 'must be a number >= 0 (milliseconds)');
2461
+ check('maxDelay', v => isNumber(v) && v >= 0, 'must be a number >= 0 (milliseconds)');
2462
+ check('maxDelayNoInternet', v => isNumber(v) && v >= 0, 'must be a number >= 0 (milliseconds)');
2463
+ check('multiplier', v => isNumber(v) && v >= 1, 'must be a number >= 1 (use 1 for a constant delay)');
2464
+ const incompatible = (feature, isUsed, hint = 'Remove one of them.') => {
2465
+ if (isUsed)
2466
+ throw new StoreException(`Action ${name} uses both unlimitedRetryCheckInternet and ${feature}, which can't be combined. ` +
2467
+ hint);
2468
+ };
2469
+ const already = (feature) => `Remove its \`${feature}\` property, since unlimitedRetryCheckInternet already does that.`;
2470
+ incompatible('retry', this.ifRetryIsOn, already('retry'));
2471
+ incompatible('checkInternet', !!this.checkInternet, already('checkInternet'));
2472
+ incompatible('nonReentrant', this.nonReentrant, already('nonReentrant'));
2473
+ incompatible('debounce', this._debounceMillis !== null);
2474
+ incompatible('throttle', this._throttleMillis !== null);
2475
+ incompatible('fresh', this._freshMillis !== null);
2476
+ incompatible('sequential', this.sequential);
2477
+ incompatible('polling', this.poll !== undefined, 'Remove one of them, or add unlimitedRetryCheckInternet to the action returned by createPollingAction().');
2478
+ if (this instanceof OptimisticCommand)
2479
+ throw new StoreException(`Action ${name} is an OptimisticCommand, which can't use unlimitedRetryCheckInternet. ` +
2480
+ 'Remove its `unlimitedRetryCheckInternet` property.');
2481
+ const { initialDelay, multiplier, maxDelay, maxDelayNoInternet } = options;
2482
+ this._retry = {
2483
+ ...this._retry,
2484
+ ...(initialDelay !== undefined && { initialDelay }),
2485
+ ...(multiplier !== undefined && { multiplier }),
2486
+ ...(maxDelay !== undefined && { maxDelay }),
2487
+ unlimitedRetries: true,
2488
+ };
2489
+ if (maxDelayNoInternet !== undefined)
2490
+ this._maxDelayNoInternet = maxDelayNoInternet;
2491
+ }
2492
+ /**
2493
+ * Throws a `StoreException` if this action uses `ignoreOld` with a feature it can't use.
2494
+ * The optimistic classes check it themselves.
2495
+ */
2496
+ _validateIgnoreOld() {
2497
+ const incompatible = (feature, isUsed, reason) => {
2498
+ if (isUsed)
2499
+ throw new StoreException(`Action ${this.constructor.name} uses both ignoreOld and ${feature}, which can't be combined, ` +
2500
+ `since ${reason}. Remove one of them.`);
2501
+ };
2502
+ const neverOverlap = 'it never lets two actions with the same key run at the same time';
2503
+ incompatible('nonReentrant', this.nonReentrant, neverOverlap);
2504
+ incompatible('unlimitedRetryCheckInternet', this._isUnlimitedRetryCheckInternet, neverOverlap);
2505
+ incompatible('sequential', this.sequential, 'it already applies the results in the dispatch order');
2506
+ }
2507
+ /**
2508
+ * Throws a `StoreException` if this action uses polling in a way that is not allowed.
2509
+ */
2510
+ _validatePolling() {
2511
+ const poll = this.poll;
2512
+ if (!Object.values(Poll).includes(poll))
2513
+ throw new StoreException(`Action ${this.constructor.name} has an invalid poll: ` +
2514
+ `it must be Poll.start, Poll.stop, Poll.runNowAndRestart or Poll.once, but got ` +
2515
+ `${typeof poll === 'string' ? `"${poll}"` : String(poll)}.`);
2516
+ if (this.createPollingAction === KissAction.prototype.createPollingAction)
2517
+ throw new StoreException(`Action ${this.constructor.name} uses polling, but doesn't override createPollingAction().`);
2518
+ const pollInterval = this.pollInterval;
2519
+ if (this._pollIntervalMillis === null)
2520
+ throw new StoreException(`Action ${this.constructor.name} has an invalid pollInterval: ` +
2521
+ `it must be a number >= 0 (milliseconds), but got ` +
2522
+ `${typeof pollInterval === 'string' ? `"${pollInterval}"` : String(pollInterval)}.`);
2523
+ for (const name of ['pollOnlyWhenFocused', 'pollOnlyWhenOnline']) {
2524
+ const value = this[name];
2525
+ if (value !== undefined && typeof value !== 'boolean')
2526
+ throw new StoreException(`Action ${this.constructor.name} has an invalid ${name}: ` +
2527
+ `it must be true or false, but got ${typeof value === 'string' ? `"${value}"` : String(value)}.`);
2528
+ }
2529
+ if (this.ifRetryIsOn)
2530
+ throw new StoreException(`Action ${this.constructor.name} uses both polling and retry, which can't be combined. ` +
2531
+ 'Remove one of them, or add the retry to the action returned by createPollingAction().');
2532
+ if (this._debounceMillis !== null)
2533
+ throw new StoreException(`Action ${this.constructor.name} uses both polling and debounce, which can't be combined. ` +
2534
+ 'Remove one of them.');
2535
+ if (this instanceof OptimisticCommand)
2536
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which can't use polling. ` +
2537
+ 'Remove its `poll` property.');
2538
+ }
2539
+ /**
2540
+ * Throws a `StoreException` if some `retry` option has an invalid value.
2541
+ * Options that are not set (`undefined`) use their defaults.
2542
+ */
2543
+ _validateRetry(retry) {
2544
+ const fail = (option, rule, value) => {
2545
+ throw new StoreException(`Action ${this.constructor.name} has an invalid retry option: ` +
2546
+ `retry.${option} ${rule}, but got ${typeof value === 'string' ? `"${value}"` : String(value)}.`);
2547
+ };
2548
+ const isNumber = (v) => typeof v === 'number' && Number.isFinite(v);
2549
+ const check = (option, isValid, rule) => {
2550
+ const value = retry[option];
2551
+ if (value !== undefined && !isValid(value))
2552
+ fail(option, rule, value);
2553
+ };
2554
+ check('on', v => typeof v === 'boolean', 'must be a boolean');
2555
+ check('unlimitedRetries', v => typeof v === 'boolean', 'must be a boolean');
2556
+ check('initialDelay', v => isNumber(v) && v >= 0, 'must be a number >= 0 (milliseconds)');
2557
+ check('maxDelay', v => isNumber(v) && v >= 0, 'must be a number >= 0 (milliseconds)');
2558
+ check('multiplier', v => isNumber(v) && v >= 1, 'must be a number >= 1 (use 1 for a constant delay)');
2559
+ check('maxRetries', v => Number.isInteger(v) && v >= -1, 'must be an integer >= -1 (use -1 for unlimited retries)');
2560
+ }
2561
+ /**
2562
+ * For Kiss internal use only.
2563
+ * @internal
2564
+ */
2565
+ _changeStatus(params = {}) {
2566
+ this._status = this._status.copy(params);
2567
+ }
2568
+ /**
2569
+ * For Kiss internal use only.
2570
+ * @internal
2571
+ */
2572
+ _createPromise() {
2573
+ return new Promise((resolve, reject) => {
2574
+ this._resolve = resolve;
2575
+ this._reject = reject;
2576
+ });
2577
+ }
2578
+ /**
2579
+ * For Kiss internal use only.
2580
+ * @internal
2581
+ */
2582
+ _resolvePromise(failure = null) {
2583
+ // Settles the promise created by `dispatchAndWait()`. It rejects with the error, if the
2584
+ // action failed with an error that was not swallowed. Otherwise, it resolves with the status.
2585
+ if (failure !== null)
2586
+ this._reject?.(failure.error);
2587
+ else
2588
+ this._resolve?.(this.status);
2589
+ }
2590
+ /**
2591
+ * For Kiss internal use only.
2592
+ * Returns true if the action was dispatched with `dispatchAndWait()`.
2593
+ * @internal
2594
+ */
2595
+ _isAwaited() {
2596
+ return this._resolve !== null;
2597
+ }
2598
+ /**
2599
+ * Prints a readable description of the action, for debugging purposes.
2600
+ * Example: `MyAction(increment:10)`.
2601
+ */
2602
+ toString() {
2603
+ // Initialize an array to hold key-value pairs as strings
2604
+ const keyValuePairs = [];
2605
+ for (const key of Object.keys(this)) {
2606
+ if (!key.startsWith('_') && (key != 'nonReentrant') && (key != 'ignoreOld') && (key != 'retry') && (key != 'checkInternet') && (key != 'wrapReduce') && (key != 'debounce') && (key != 'throttle') && (key != 'removeThrottleLockOnError') && (key != 'fresh') && (key != 'sequential') && (key != 'pollInterval') && (key != 'pollWaitsForRun') && (key != 'unlimitedRetryCheckInternet')) { // Continue to exclude base class/internal fields
2607
+ // For each property, push "key:value" string to the array
2608
+ // Note: This simple line assumes that `value` can be meaningfully represented as a string.
2609
+ // You might need a more complex handling for objects, arrays, etc.
2610
+ const value = this[key];
2611
+ keyValuePairs.push(`${key}:${describeValue(value)}`);
2612
+ }
2613
+ }
2614
+ // Join all key-value pairs with a comma and space, and format it according to your requirements
2615
+ return `${this.constructor.name}(${keyValuePairs.join(', ').replace(/"/g, '')})`;
2616
+ }
2617
+ }
2618
+ /**
2619
+ * The `status` is a property of the action, used to keep track of the action's lifecycle.
2620
+ * If you have a reference to the action you can check its status at any time with `action.status`:
2621
+ *
2622
+ * ```ts
2623
+ * const action = new MyAction();
2624
+ * await store.dispatchAndWait(action);
2625
+ * if (action.status.isCompletedOk) { ... }
2626
+ * ```
2627
+ *
2628
+ * However, `dispatchAndWait` also returns the action status after it finishes:
2629
+ *
2630
+ * ```ts
2631
+ * const status = await store.dispatchAndWait(new MyAction());
2632
+ * if (status.isCompletedOk) { ... }
2633
+ * ```
2634
+ */
2635
+ export class ActionStatus {
2636
+ /**
2637
+ * Returns true if the action was already dispatched. An action cannot be dispatched
2638
+ * more than once, which means that you have to create a new action each time.
2639
+ *
2640
+ * Note this may be true even if the action has not yet FINISHED dispatching.
2641
+ * To check if it has finished, use `action.status.isCompleted`.
2642
+ */
2643
+ isDispatched;
2644
+ /**
2645
+ * Is true if the dispatch of the action was aborted:
2646
+ * - Because `abortDispatch()` returned `true`.
2647
+ * - Because the action is `nonReentrant` (or an `OptimisticCommand`), and another action
2648
+ * with the same non-reentrant key was running.
2649
+ * - Because of its `throttle` period, or because its `fresh` data was still fresh.
2650
+ * - Because it was mocked as `null`, or the store was shut down.
2651
+ * - Because an `AbortDispatchException` was thrown by the action's `before` or `reduce`
2652
+ * methods, or returned by its `wrapError` or by the `errorObserver`. This includes a
2653
+ * `sequential` action discarded from its queue, and an `ignoreOld` action that became old.
2654
+ *
2655
+ * Note in the last case the action was dispatched and finished (the `after` method ran),
2656
+ * but in the other cases it was never dispatched (`isDispatched` is `false`).
2657
+ */
2658
+ isDispatchAborted;
2659
+ /**
2660
+ * Is true when the `before` method finished executing normally.
2661
+ * Is false if it has not yet finished executing or if it threw an error.
2662
+ */
2663
+ hasFinishedMethodBefore;
2664
+ /**
2665
+ * Is true when the `reduce` method finished executing normally, returning a value.
2666
+ * Is false if it has not yet finished executing or if it threw an error.
2667
+ */
2668
+ hasFinishedMethodReduce;
2669
+ /**
2670
+ * Is true if the `after` method finished executing. Note the `after` method should
2671
+ * never throw any errors, but if it does the error will be swallowed and ignored.
2672
+ * Is false if it has not yet finished executing.
2673
+ */
2674
+ hasFinishedMethodAfter;
2675
+ /**
2676
+ * Holds the error thrown by the action's before/reduce methods, if any.
2677
+ * This may or may not be equal to the error thrown by the action, because the original error
2678
+ * will still be processed by the action's `wrapError` and the `errorObserver`. However,
2679
+ * if `originalError` is non-null, it means the reducer did not finish running.
2680
+ *
2681
+ * If the action was aborted by throwing an `AbortDispatchException`, this holds that
2682
+ * exception. If it was thrown by your code, it's still processed by `wrapError` and the
2683
+ * `errorObserver`. But not if Kiss itself aborted the action (for example, for `ignoreOld`
2684
+ * or `sequential`).
2685
+ *
2686
+ * If the before/reduce methods threw `null` or `undefined` (or a Promise was rejected with
2687
+ * no reason), this holds an `Error` that says so, and that's the error processed by
2688
+ * `wrapError` and the `errorObserver`.
2689
+ */
2690
+ originalError;
2691
+ /**
2692
+ * Holds the error thrown by the action. This may or may not be the same as `originalError`,
2693
+ * because any errors thrown by the action's before/reduce methods may still be changed or
2694
+ * cancelled by the action's `wrapError` and the `errorObserver`. This is the final error
2695
+ * after all these wraps.
2696
+ */
2697
+ wrappedError;
2698
+ /**
2699
+ * Returns true only if the action has completed executing, either with or without errors.
2700
+ * If this is true, the 'after' method already ran.
2701
+ */
2702
+ get isCompleted() {
2703
+ return this.hasFinishedMethodAfter;
2704
+ }
2705
+ /**
2706
+ * Returns true only if the action has completed, and none of the 'before' or 'reduce'
2707
+ * methods have thrown an error. This indicates that the 'reduce' method completed and
2708
+ * returned a result (even if the result was null). The 'after' method also already ran.
2709
+ *
2710
+ * This can be useful if you need to dispatch a second method only if the first method
2711
+ * succeeded:
2712
+ *
2713
+ * ```ts
2714
+ * let action = new LoadInfo();
2715
+ * await dispatchAndWait(action);
2716
+ * if (action.status.isCompletedOk) dispatch(new ShowInfo());
2717
+ * ```
2718
+ *
2719
+ * Or you can also get the state directly from `dispatchAndWait`:
2720
+ *
2721
+ * ```ts
2722
+ * let status = await dispatchAndWait(new LoadInfo());
2723
+ * if (status.isCompletedOk) dispatch(new ShowInfo());
2724
+ * ```
2725
+ */
2726
+ get isCompletedOk() {
2727
+ return this.isCompleted && (this.originalError === null);
2728
+ }
2729
+ /**
2730
+ * Returns true only if the action has completed (the 'after' method already ran), but either
2731
+ * the 'before' or the 'reduce' methods have thrown an error. If this is true, it indicates that
2732
+ * the reducer could NOT complete, and could not return a value to change the state.
2733
+ *
2734
+ * Note this is also true when the action was aborted by throwing an
2735
+ * `AbortDispatchException`. In that case, `isDispatchAborted` is also true.
2736
+ */
2737
+ get isCompletedFailed() {
2738
+ return this.isCompleted && (this.originalError != null);
2739
+ }
2740
+ constructor(params = {}) {
2741
+ this.isDispatched = params.isDispatched ?? false;
2742
+ this.isDispatchAborted = params.isDispatchAborted ?? false;
2743
+ this.hasFinishedMethodBefore = params.hasFinishedMethodBefore ?? false;
2744
+ this.hasFinishedMethodReduce = params.hasFinishedMethodReduce ?? false;
2745
+ this.hasFinishedMethodAfter = params.hasFinishedMethodAfter ?? false;
2746
+ this.originalError = params.originalError ?? null;
2747
+ this.wrappedError = params.wrappedError ?? null;
2748
+ }
2749
+ copy(params) {
2750
+ return new ActionStatus({
2751
+ isDispatched: params.isDispatched ?? this.isDispatched,
2752
+ isDispatchAborted: params.isDispatchAborted ?? this.isDispatchAborted,
2753
+ hasFinishedMethodBefore: params.hasFinishedMethodBefore ?? this.hasFinishedMethodBefore,
2754
+ hasFinishedMethodReduce: params.hasFinishedMethodReduce ?? this.hasFinishedMethodReduce,
2755
+ hasFinishedMethodAfter: params.hasFinishedMethodAfter ?? this.hasFinishedMethodAfter,
2756
+ originalError: params.originalError ?? this.originalError,
2757
+ wrappedError: params.wrappedError ?? this.wrappedError,
2758
+ });
2759
+ }
2760
+ }
2761
+ /**
2762
+ * The `OptimisticCommand` abstract class is for actions that represent a command.
2763
+ * A command is something you want to run on the server once per dispatch.
2764
+ * Typical examples are:
2765
+ *
2766
+ * - Create something (add todo, create comment, send message)
2767
+ * - Delete something
2768
+ * - Submit a form
2769
+ * - Upload a file
2770
+ * - Checkout, place order, confirm payment
2771
+ *
2772
+ * It gives fast UI feedback by applying an optimistic state change immediately, then running
2773
+ * the command on the server, and optionally rolling back and reloading.
2774
+ *
2775
+ * Note: It's not built for save operations where only the final value matters, and users may
2776
+ * tap many times quickly (like/follow toggles, settings switches, sliders, checkboxes). For
2777
+ * those, each tap would be a separate server call.
2778
+ *
2779
+ * ## The problem
2780
+ *
2781
+ * Let's use a Todo app as an example. We want to save a new Todo to a TodoList.
2782
+ * This code saves the Todo, then reloads the TodoList from the cloud:
2783
+ *
2784
+ * ```ts
2785
+ * class SaveTodo extends Action {
2786
+ * constructor(readonly newTodo: Todo) { super(); }
2787
+ *
2788
+ * async reduce() {
2789
+ * try {
2790
+ * // Saves the new Todo to the cloud.
2791
+ * await saveTodo(this.newTodo);
2792
+ * } finally {
2793
+ * // Loads the complete TodoList from the cloud.
2794
+ * let reloadedTodoList = await loadTodoList();
2795
+ * return (state: State) => state.copy({ todoList: reloadedTodoList });
2796
+ * }
2797
+ * }
2798
+ * }
2799
+ * ```
2800
+ *
2801
+ * The problem with the above code is that it may take a second to update the TodoList on
2802
+ * screen, while we save then load.
2803
+ *
2804
+ * The solution is to optimistically update the TodoList before saving:
2805
+ *
2806
+ * ```ts
2807
+ * class SaveTodo extends Action {
2808
+ * constructor(readonly newTodo: Todo) { super(); }
2809
+ *
2810
+ * async reduce() {
2811
+ * // Updates the TodoList optimistically.
2812
+ * this.dispatch(new UpdateStateAction((state: State) =>
2813
+ * state.copy({ todoList: state.todoList.add(this.newTodo) })));
2814
+ *
2815
+ * try {
2816
+ * // Saves the new Todo to the cloud.
2817
+ * await saveTodo(this.newTodo);
2818
+ * } finally {
2819
+ * // Loads the complete TodoList from the cloud.
2820
+ * let reloadedTodoList = await loadTodoList();
2821
+ * return (state: State) => state.copy({ todoList: reloadedTodoList });
2822
+ * }
2823
+ * }
2824
+ * }
2825
+ * ```
2826
+ *
2827
+ * That's better. But if saving fails, users still have to wait for the reload until they see
2828
+ * the reverted state. We can further improve this:
2829
+ *
2830
+ * ```ts
2831
+ * class SaveTodo extends Action {
2832
+ * constructor(readonly newTodo: Todo) { super(); }
2833
+ *
2834
+ * async reduce() {
2835
+ * // Updates the TodoList optimistically.
2836
+ * let newTodoList = this.state.todoList.add(this.newTodo);
2837
+ * this.dispatch(new UpdateStateAction((state: State) => state.copy({ todoList: newTodoList })));
2838
+ *
2839
+ * try {
2840
+ * // Saves the new Todo to the cloud.
2841
+ * await saveTodo(this.newTodo);
2842
+ * } catch (error) {
2843
+ * // If the state still contains our optimistic update, we roll back.
2844
+ * // If the state now contains something else, we do not roll back.
2845
+ * if (this.state.todoList === newTodoList) {
2846
+ * let initialTodoList = this.initialState.todoList;
2847
+ * this.dispatch(new UpdateStateAction((state: State) => state.copy({ todoList: initialTodoList })));
2848
+ * }
2849
+ * throw error;
2850
+ * } finally {
2851
+ * // Loads the complete TodoList from the cloud.
2852
+ * let reloadedTodoList = await loadTodoList();
2853
+ * this.dispatch(new UpdateStateAction((state: State) => state.copy({ todoList: reloadedTodoList })));
2854
+ * }
2855
+ * return null;
2856
+ * }
2857
+ * }
2858
+ * ```
2859
+ *
2860
+ * Now the user sees the rollback immediately after the saving fails. The `OptimisticCommand`
2861
+ * class helps you implement this pattern easily, and takes care of the edge cases.
2862
+ *
2863
+ * ## How to use it
2864
+ *
2865
+ * Extend `OptimisticCommand` instead of your base action, and DO NOT implement `reduce()`.
2866
+ * Instead, you must provide:
2867
+ *
2868
+ * - `optimisticValue()` returns the optimistic value you want to apply right away.
2869
+ * - `getValueFromState(state)` extracts the current value from a given state.
2870
+ * - `applyValueToState(state, value)` applies a value to a given state and returns the new state.
2871
+ * - `sendCommandToServer(optimisticValue)` runs the server command (it may use the action fields).
2872
+ *
2873
+ * And optionally:
2874
+ *
2875
+ * - `applyServerResponseToState(state, serverResponse)` applies the server response to the state.
2876
+ * - `reloadFromServer()` reloads from the server (do not implement it to skip reloading).
2877
+ * - `applyReloadResultToState(state, reloadResult)` applies the reload result to the state
2878
+ * (the default uses `applyValueToState`).
2879
+ * - `rollbackState`, `shouldRollback`, `shouldReload` and `shouldApplyReload`, to customize
2880
+ * when and how the rollback and the reload happen.
2881
+ *
2882
+ * Important details:
2883
+ *
2884
+ * - The optimistic update is applied immediately.
2885
+ *
2886
+ * - If `sendCommandToServer` fails, the rollback happens only if the current state still
2887
+ * matches the optimistic value created by this dispatch. The rollback restores the value
2888
+ * it had right before the optimistic value was applied. Then the action fails with the error
2889
+ * of `sendCommandToServer`.
2890
+ *
2891
+ * - The reload is optional. If implemented, it runs after `sendCommandToServer` finishes,
2892
+ * only in case of error (this can be changed by overriding `shouldReload`).
2893
+ *
2894
+ * Complete example:
2895
+ *
2896
+ * ```ts
2897
+ * class SaveTodo extends OptimisticCommand<State, Todo | undefined> {
2898
+ * constructor(readonly newTodo: Todo) { super(); }
2899
+ *
2900
+ * // The new Todo is going to be optimistically applied to the state, right away.
2901
+ * optimisticValue() { return this.newTodo; }
2902
+ *
2903
+ * // We teach the action how to read the Todo from the state.
2904
+ * getValueFromState(state: State) { return state.todoList.getById(this.newTodo.id); }
2905
+ *
2906
+ * // Apply the value to the state.
2907
+ * applyValueToState(state: State, todo: Todo | undefined) {
2908
+ * return state.copy({ todoList: (todo === undefined)
2909
+ * ? state.todoList.removeById(this.newTodo.id)
2910
+ * : state.todoList.add(todo) });
2911
+ * }
2912
+ *
2913
+ * // Contact the server to send the command (save the Todo).
2914
+ * async sendCommandToServer(newTodo: Todo) { return await saveTodo(newTodo); }
2915
+ *
2916
+ * // If the server returns a value, we may apply it to the state.
2917
+ * applyServerResponseToState(state: State, todo: Todo) {
2918
+ * return state.copy({ todoList: state.todoList.add(todo) });
2919
+ * }
2920
+ *
2921
+ * // Reload from the cloud (in case of error).
2922
+ * async reloadFromServer() { return await loadTodo(this.newTodo.id); }
2923
+ * }
2924
+ * ```
2925
+ *
2926
+ * ## Non-reentrant
2927
+ *
2928
+ * `OptimisticCommand` is always non-reentrant. If the same action is dispatched while a
2929
+ * previous dispatch is still running, the new dispatch is aborted. This prevents race
2930
+ * conditions such as:
2931
+ *
2932
+ * - Conflicting optimistic updates overwriting each other.
2933
+ * - Incorrect rollback behavior (the rollback check may no longer match).
2934
+ * - Race conditions in the reload phase.
2935
+ * - Server side conflicts from concurrent requests.
2936
+ *
2937
+ * Your UI should let the user know that the command is in progress, so they don't try to
2938
+ * dispatch it again until it finishes. That's easy to do, just check if the action is in
2939
+ * progress with `useIsWaiting(SaveTodo)`.
2940
+ *
2941
+ * By default, the non-reentrant check is based on the action class. If your action has
2942
+ * parameters and you want to allow concurrent dispatches for different parameters (for
2943
+ * example, saving different items), override `nonReentrantKeyParams()`. For example:
2944
+ *
2945
+ * ```ts
2946
+ * class SaveTodo extends OptimisticCommand<State> {
2947
+ * constructor(readonly todoId: string) { super(); }
2948
+ * nonReentrantKeyParams() { return this.todoId; }
2949
+ * ...
2950
+ * }
2951
+ * ```
2952
+ *
2953
+ * This allows `SaveTodo('A')` and `SaveTodo('B')` to run concurrently, while blocking
2954
+ * concurrent dispatches of `SaveTodo('A')` with itself. This is useful for commands you
2955
+ * **do** want to run in parallel, as long as they are for different items. Common examples
2956
+ * are uploading multiple files at the same time (key by fileId), or sending multiple chat
2957
+ * messages at the same time (key by clientMessageId).
2958
+ *
2959
+ * You can also override `computeNonReentrantKey()` if you want different action classes to
2960
+ * share the same non-reentrant key. These keys are shared with `nonReentrant` actions, so a
2961
+ * `nonReentrant` action and an `OptimisticCommand` with the same key can't run at the same time.
2962
+ *
2963
+ * ## Retry
2964
+ *
2965
+ * When combined with `retry`, only the `sendCommandToServer` call is retried, not the
2966
+ * optimistic update or rollback. This prevents UI flickering that would otherwise occur if the
2967
+ * entire reducer was retried on each attempt. The optimistic state remains in place during
2968
+ * retries, and the rollback only happens if all retry attempts fail. In a server store (created
2969
+ * with `server: true`, for server-side rendering), `sendCommandToServer` is called once, and
2970
+ * not retried. See the `server` option of `createStore`.
2971
+ *
2972
+ * Every error is retried, including `UserException`s, unless `shouldRetry(error, attempt)` returns
2973
+ * `false` for it. The command then gives up right away: it rolls back (if `shouldRollback` says
2974
+ * so), reloads (if `shouldReload` says so), and fails with that error.
2975
+ *
2976
+ * `store.clearInternalActionProps()` (which is also called by `store.setShutDown(true)`) stops
2977
+ * the retries, which is useful on logout. A command waiting to retry is aborted right away, and
2978
+ * a command whose server call is running is aborted if that call fails (if it succeeds, the
2979
+ * server response is applied as usual). It's aborted with an `AbortDispatchException`, so it
2980
+ * doesn't fail, and doesn't show errors. It also doesn't roll back the optimistic value, and
2981
+ * doesn't reload, since that would change the state of the next user.
2982
+ *
2983
+ * ## CheckInternet
2984
+ *
2985
+ * When combined with `checkInternet`, if there is no internet: no optimistic state is
2986
+ * applied, no server call is attempted, and the action fails (showing a dialog, if
2987
+ * `checkInternet` is `{ dialog: true }`), or is silently aborted (if `checkInternet` is
2988
+ * `{ abort: true }`).
2989
+ *
2990
+ * Notes:
2991
+ *
2992
+ * - The default rollback check compares values with `Object.is` (which is the same as `===`,
2993
+ * except that `NaN` is equal to `NaN`). So, make sure `getValueFromState` returns the same
2994
+ * object you applied, or override `shouldRollback`.
2995
+ * - It can be combined with `retry` and `checkInternet`.
2996
+ * - It can be combined with `sequential`. Note the optimistic value is then only applied to
2997
+ * the state when the action gets its turn in the queue, and not as soon as the action is
2998
+ * dispatched. So, if it fails, it rolls back to the value it had when it got its turn, which
2999
+ * keeps the commands that ran before it in the queue.
3000
+ * - It should not be combined with `nonReentrant` (it's already non-reentrant), nor with
3001
+ * unlimited retries (a command that never finishes would never release its non-reentrant
3002
+ * key), nor with `debounce`, `throttle`, `fresh` or `ignoreOld`. Dispatching it with those
3003
+ * throws a `StoreException`.
3004
+ */
3005
+ export class OptimisticCommand extends KissAction {
3006
+ /**
3007
+ * Override `applyServerResponseToState` to return a new state, where the given
3008
+ * `serverResponse` (previously received from the server when running `sendCommandToServer`)
3009
+ * is applied to the current `state`. Example:
3010
+ *
3011
+ * ```ts
3012
+ * applyServerResponseToState(state: State, serverResponse: Response) {
3013
+ * return state.copy({ todoList: serverResponse.todoList });
3014
+ * }
3015
+ * ```
3016
+ *
3017
+ * Note `serverResponse` is never `null` or `undefined` here, because this method is only
3018
+ * called when `sendCommandToServer` returned some value.
3019
+ *
3020
+ * If you DO NOT want to apply the server response to the state, return `null`
3021
+ * (which is the default).
3022
+ *
3023
+ * If this method throws, the action fails with that error. But since the command itself
3024
+ * succeeded, the state is not rolled back, and there is no reload.
3025
+ */
3026
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3027
+ applyServerResponseToState(state, serverResponse) {
3028
+ return null;
3029
+ }
3030
+ /**
3031
+ * Returns the state to apply when the command fails and it's safe to roll back.
3032
+ *
3033
+ * This method is called only when `sendCommandToServer` throws, AND `shouldRollback` returns
3034
+ * true. By default, `shouldRollback` returns true only if the current value in the store still
3035
+ * matches the optimistic value created by this dispatch (so we don't roll back over newer
3036
+ * changes).
3037
+ *
3038
+ * Parameters:
3039
+ *
3040
+ * - `initialValue` is the value extracted with `getValueFromState` right before the
3041
+ * optimistic value was applied. It's usually what the value was when this action was
3042
+ * dispatched. But if the action waited before applying it (for its turn in the `sequential`
3043
+ * queue, or for the internet check of `checkInternet`), it's the value after that wait.
3044
+ *
3045
+ * - `optimisticValue` is the value returned by `optimisticValue()` and applied
3046
+ * optimistically by this dispatch.
3047
+ *
3048
+ * - `error` is the error thrown by `sendCommandToServer`.
3049
+ *
3050
+ * By default, it restores `initialValue` by calling `applyValueToState`.
3051
+ *
3052
+ * Override this method if rollback is not simply "put the old value back".
3053
+ * For example, you may want to:
3054
+ * - Keep the optimistic item but mark it as failed.
3055
+ * - Remove only the item you added, while keeping other local changes.
3056
+ * - Roll back multiple parts of the state, not just the value handled by `applyValueToState`.
3057
+ *
3058
+ * Return `null` to skip the rollback.
3059
+ */
3060
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3061
+ rollbackState({ initialValue, optimisticValue, error }) {
3062
+ return this.applyValueToState(this.state, initialValue);
3063
+ }
3064
+ /**
3065
+ * Returns true if it should roll back after `sendCommandToServer` fails. This method is
3066
+ * called only when `sendCommandToServer` throws.
3067
+ *
3068
+ * The default is to roll back only if the current value in the store still matches the
3069
+ * optimistic value created by this dispatch (compared with `Object.is`). This avoids
3070
+ * rolling back over newer changes that may have happened while the request was in flight.
3071
+ *
3072
+ * Override this if you need a different safety rule. For example:
3073
+ * - You want to always roll back, even if something else changed.
3074
+ * - You want to roll back only if a specific item is still present.
3075
+ * - You want to roll back only for some errors.
3076
+ */
3077
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3078
+ shouldRollback({ currentValue, initialValue, optimisticValue, error }) {
3079
+ // Default: roll back only if we are still seeing our own optimistic value.
3080
+ return Object.is(currentValue, optimisticValue);
3081
+ }
3082
+ /**
3083
+ * Whether it should call `reloadFromServer()`. Only called if `reloadFromServer` is
3084
+ * implemented. It's called after `sendCommandToServer` finishes, both on success and on error.
3085
+ *
3086
+ * Parameters:
3087
+ *
3088
+ * - `currentValue` is the value currently in the store (extracted with `getValueFromState`)
3089
+ * at the moment we are deciding whether to reload.
3090
+ *
3091
+ * - `lastAppliedValue` is the last value this action applied for the same state slice.
3092
+ * It is the optimistic value, or the value from the server response if it was applied,
3093
+ * or the rollback value if the rollback was applied.
3094
+ *
3095
+ * - `optimisticValue` is the value returned by `optimisticValue()` and applied
3096
+ * optimistically by this dispatch.
3097
+ *
3098
+ * - `rollbackValue` is `undefined` if no rollback state was applied. If the rollback was
3099
+ * applied, this is the value extracted from the rollback state using `getValueFromState`.
3100
+ *
3101
+ * - `error` is `null` on success, or the error thrown by `sendCommandToServer` on failure.
3102
+ *
3103
+ * The default is to reload only on error.
3104
+ *
3105
+ * Override this method to reload in other cases. For example, to also reload on success,
3106
+ * or to skip the reload when the value already changed to something else:
3107
+ *
3108
+ * ```ts
3109
+ * shouldReload({ currentValue, lastAppliedValue }: {
3110
+ * currentValue: Todo | undefined,
3111
+ * lastAppliedValue: Todo | undefined,
3112
+ * }) {
3113
+ * return currentValue === lastAppliedValue;
3114
+ * }
3115
+ * ```
3116
+ */
3117
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3118
+ shouldReload({ currentValue, lastAppliedValue, optimisticValue, rollbackValue, error }) {
3119
+ return error !== null;
3120
+ }
3121
+ /**
3122
+ * Returns true if it should apply the result returned by `reloadFromServer` to the state.
3123
+ *
3124
+ * This method is called after `reloadFromServer` completes, both when the command
3125
+ * succeeded and when it failed.
3126
+ *
3127
+ * Parameters are the same as `shouldReload`, plus `reloadResult`, which is whatever
3128
+ * `reloadFromServer` returned. Note `currentValue` is read again after the reload finishes,
3129
+ * because the state may have changed while reloading.
3130
+ *
3131
+ * The default is to always apply the reload result. This matches the common expectation
3132
+ * that if you chose to reload, the server is the source of truth.
3133
+ *
3134
+ * Override this method if you want to avoid overwriting newer local changes, or if you need
3135
+ * custom rules based on `reloadResult` or `error`.
3136
+ */
3137
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3138
+ shouldApplyReload({ currentValue, lastAppliedValue, optimisticValue, rollbackValue, reloadResult, error }) {
3139
+ return true;
3140
+ }
3141
+ /**
3142
+ * Applies the result returned by `reloadFromServer` to the state.
3143
+ *
3144
+ * Override this method when `reloadFromServer` returns something that is not the same type
3145
+ * or shape expected by `applyValueToState`, or when applying the reload requires updating
3146
+ * multiple parts of the state.
3147
+ *
3148
+ * Return `null` to ignore the reload result.
3149
+ */
3150
+ applyReloadResultToState(state, reloadResult) {
3151
+ return this.applyValueToState(state, reloadResult);
3152
+ }
3153
+ /**
3154
+ * Do NOT override this method. Implement `optimisticValue`, `getValueFromState`,
3155
+ * `applyValueToState` and `sendCommandToServer` instead.
3156
+ */
3157
+ async reduce() {
3158
+ // The value to roll back to. It's read now, and not from `initialState`, because the action
3159
+ // may have waited since it was dispatched (for its turn in the `sequential` queue, or for
3160
+ // the internet check), and the value may have changed meanwhile.
3161
+ const initialValue = this.getValueFromState(this.state);
3162
+ // Updates the value optimistically.
3163
+ const optimistic = this.optimisticValue();
3164
+ this._applyState(this.applyValueToState(this.state, optimistic));
3165
+ let commandFailed = false;
3166
+ let commandError = null;
3167
+ let lastAppliedValue = optimistic; // What this action last wrote.
3168
+ let rollbackValue = undefined; // Value slice after the rollback, if any.
3169
+ let serverResponse = undefined;
3170
+ try {
3171
+ // Sends the command to the server.
3172
+ // If retry is on, only this call is retried, keeping the optimistic state in place.
3173
+ serverResponse = await this._sendCommandWithRetryIfNeeded(optimistic);
3174
+ }
3175
+ catch (error) {
3176
+ // When the command stopped retrying because `clearInternalActionProps()` was called (for
3177
+ // example, on logout), it doesn't roll back and doesn't reload, since that would change
3178
+ // the state of the next user. It's aborted, so it doesn't fail, and doesn't show errors.
3179
+ if (this._hasStoppedRetrying)
3180
+ throw error;
3181
+ commandFailed = true;
3182
+ commandError = error;
3183
+ // Decides if it's safe to roll back (default: only if we are still seeing our own
3184
+ // optimistic value, to avoid undoing newer changes made while the request was in flight).
3185
+ if (this.shouldRollback({
3186
+ currentValue: this.getValueFromState(this.state),
3187
+ initialValue,
3188
+ optimisticValue: optimistic,
3189
+ error,
3190
+ })) {
3191
+ const rollback = this.rollbackState({ initialValue, optimisticValue: optimistic, error });
3192
+ if (rollback !== null) {
3193
+ this._applyState(rollback);
3194
+ rollbackValue = this.getValueFromState(rollback);
3195
+ lastAppliedValue = rollbackValue;
3196
+ }
3197
+ }
3198
+ }
3199
+ // Applies the server response, if any. This is outside the `try` above, because the command
3200
+ // succeeded: if applying the response throws, the action fails with that error, but there
3201
+ // is no rollback and no reload.
3202
+ if (!commandFailed && serverResponse !== null && serverResponse !== undefined) {
3203
+ const newState = this.applyServerResponseToState(this.state, serverResponse);
3204
+ if (newState !== null) {
3205
+ this._applyState(newState);
3206
+ lastAppliedValue = this.getValueFromState(newState);
3207
+ }
3208
+ }
3209
+ // Reloads from the server, if `reloadFromServer` was implemented.
3210
+ if (this.reloadFromServer !== undefined) {
3211
+ try {
3212
+ const doReload = this.shouldReload({
3213
+ currentValue: this.getValueFromState(this.state),
3214
+ lastAppliedValue,
3215
+ optimisticValue: optimistic,
3216
+ rollbackValue,
3217
+ error: commandError,
3218
+ });
3219
+ if (doReload) {
3220
+ const reloadResult = await this.reloadFromServer();
3221
+ // Reads the current value again, because the state may have changed while reloading.
3222
+ const apply = this.shouldApplyReload({
3223
+ currentValue: this.getValueFromState(this.state),
3224
+ lastAppliedValue,
3225
+ optimisticValue: optimistic,
3226
+ rollbackValue,
3227
+ reloadResult,
3228
+ error: commandError,
3229
+ });
3230
+ if (apply) {
3231
+ const newState = this.applyReloadResultToState(this.state, reloadResult);
3232
+ if (newState !== null)
3233
+ this._applyState(newState);
3234
+ }
3235
+ }
3236
+ }
3237
+ catch (reloadError) {
3238
+ // A reload failure does not hide the original command error.
3239
+ if (!commandFailed)
3240
+ throw reloadError;
3241
+ }
3242
+ }
3243
+ // Rethrows, so that the action fails, and the user can be notified.
3244
+ if (commandFailed)
3245
+ throw commandError;
3246
+ return null;
3247
+ }
3248
+ _applyState(newState) {
3249
+ this.dispatch(new UpdateStateAction(() => newState));
3250
+ }
3251
+ /**
3252
+ * When retry is on, retries only the `sendCommandToServer` call, keeping the optimistic
3253
+ * update in place and avoiding UI flickering. Note the store does not retry the reducer
3254
+ * of an `OptimisticCommand`.
3255
+ */
3256
+ async _sendCommandWithRetryIfNeeded(optimistic) {
3257
+ // A server store doesn't retry (see the `server` option of `createStore`).
3258
+ if (!this.ifRetryIsOn || this.store.isServer)
3259
+ return this.sendCommandToServer(optimistic);
3260
+ while (true) {
3261
+ try {
3262
+ return await this.sendCommandToServer(optimistic);
3263
+ }
3264
+ catch (error) {
3265
+ // An aborted command is not retried.
3266
+ if (error instanceof AbortDispatchException)
3267
+ throw error;
3268
+ // When `dispatchSync` threw because the command is ASYNC, its result is ignored, so
3269
+ // there's no point retrying.
3270
+ if (this._isDiscardedByDispatchSync)
3271
+ throw error;
3272
+ // When `clearInternalActionProps()` was called (for example, on logout), stops retrying.
3273
+ if (this.store._wereInternalActionPropsCleared(this))
3274
+ throw this._stopRetrying();
3275
+ this._retry.attempts++;
3276
+ if (this._retry.attempts > this._retry.maxRetries)
3277
+ throw error;
3278
+ // The command can give up on some errors (`shouldRetry`).
3279
+ if (!this.shouldRetry(error, this._retry.attempts))
3280
+ throw error;
3281
+ try {
3282
+ // It also stops waiting right away when `clearInternalActionProps()` is called.
3283
+ await this.store._waitRetryDelay(this, this._nextRetryDelay());
3284
+ }
3285
+ catch {
3286
+ throw this._stopRetrying();
3287
+ }
3288
+ }
3289
+ }
3290
+ }
3291
+ // True if the command stopped retrying because `clearInternalActionProps()` was called.
3292
+ _hasStoppedRetrying = false;
3293
+ _stopRetrying() {
3294
+ this._hasStoppedRetrying = true;
3295
+ return kissAbort('The internal action props were cleared, so the command stopped retrying.');
3296
+ }
3297
+ /**
3298
+ * For Kiss internal use only.
3299
+ * @internal
3300
+ */
3301
+ _injectStore(_store) {
3302
+ super._injectStore(_store);
3303
+ if (this.nonReentrant)
3304
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which is always non-reentrant. ` +
3305
+ 'Remove its `nonReentrant` property.');
3306
+ if (this._debounceMillis !== null)
3307
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which can't use debounce. ` +
3308
+ 'Remove its `debounce` property.');
3309
+ if (this._throttleMillis !== null)
3310
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which can't use throttle. ` +
3311
+ 'Remove its `throttle` property.');
3312
+ if (this._freshMillis !== null)
3313
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which can't use fresh. ` +
3314
+ 'Remove its `fresh` property.');
3315
+ if (this.ignoreOld)
3316
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which can't use ignoreOld. ` +
3317
+ 'Remove its `ignoreOld` property.');
3318
+ if (this.ifRetryIsOn && (this._retry.unlimitedRetries || this._retry.maxRetries === -1))
3319
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which can't use unlimited retries. ` +
3320
+ 'Use a `retry.maxRetries` of 0 or more.');
3321
+ }
3322
+ }
3323
+ /**
3324
+ * The `OptimisticSync` abstract class is for actions where user interactions (like toggling a
3325
+ * "like" button) should update the UI immediately and send the updated value to the server,
3326
+ * making sure the server and the UI are eventually consistent.
3327
+ *
3328
+ * ---
3329
+ *
3330
+ * The action is not throttled or debounced in any way, and every dispatch applies an optimistic
3331
+ * update to the state immediately. This guarantees a very good user experience, because there
3332
+ * is immediate feedback on every interaction.
3333
+ *
3334
+ * However, while the first updated value (created by the first time the action is dispatched)
3335
+ * is immediately sent to the server, any other value changes that occur while the first request
3336
+ * is in flight will NOT be sent immediately.
3337
+ *
3338
+ * Instead, when the first request completes, it checks if the state is still the same as the
3339
+ * value that was sent. If not, a follow-up request is sent with the latest value. This process
3340
+ * repeats until the state stabilizes.
3341
+ *
3342
+ * Note this guarantees that only **one** request is in flight at a time per key, potentially
3343
+ * reducing the number of requests sent to the server while still coalescing intermediate
3344
+ * changes.
3345
+ *
3346
+ * Optionally:
3347
+ *
3348
+ * - If the server responds with a value, that value is applied to the state. This is useful
3349
+ * when the server normalizes or modifies values.
3350
+ *
3351
+ * - When the state finally stabilizes and the request finishes, `onFinish` is called, allowing
3352
+ * you to perform side effects.
3353
+ *
3354
+ * - In special, if the last request fails, the optimistic state remains, but in `onFinish` you
3355
+ * can then load the current state from the server, or handle the error as you see fit, by
3356
+ * returning a state that will be applied.
3357
+ *
3358
+ * In other words, it makes it easy for you to maintain perfect UI responsiveness while
3359
+ * minimizing server load, and making sure the server and the UI eventually agree on the same
3360
+ * value.
3361
+ *
3362
+ * Note: It's not built for commands that must run once per dispatch (create, delete, submit,
3363
+ * upload, checkout...). For those, use `OptimisticCommand`.
3364
+ *
3365
+ * Note: If your app receives server pushes (WebSockets, Server-Sent Events, Firebase) that may
3366
+ * change the same value, use `OptimisticSyncWithPush` instead.
3367
+ *
3368
+ * ---
3369
+ *
3370
+ * ## How it works
3371
+ *
3372
+ * 1. **Immediate UI feedback**: Every dispatch applies `valueToApply()` to the state
3373
+ * immediately, using `applyOptimisticValueToState`.
3374
+ *
3375
+ * 2. **Single in-flight request**: Only one request runs at a time per key (see
3376
+ * `optimisticSyncKeyParams()`). The first dispatch takes the key and calls
3377
+ * `sendValueToServer` to send a request to the server.
3378
+ *
3379
+ * 3. **Follow-up requests**: If the store state changed while a request started by
3380
+ * `sendValueToServer` was in flight (for example, the user tapped a "like" button again while
3381
+ * the first request was pending), a follow-up request is automatically sent after the current
3382
+ * one completes. The change is detected by comparing `getValueFromState` with the value that
3383
+ * was sent (see `ifShouldSendAnotherRequest`).
3384
+ *
3385
+ * 4. **No unnecessary requests**: If, while the request is in flight, the state changes but then
3386
+ * returns to the same value as before (for example, the user tapped a "like" button again
3387
+ * TWICE while the first request was pending), `getValueFromState` matches the sent value, and
3388
+ * no follow-up request is needed.
3389
+ *
3390
+ * 5. **Server response handling**: If `sendValueToServer` returns a value (not `null` or
3391
+ * `undefined`), it's applied to the state using `applyServerResponseToState`, when the state
3392
+ * stabilizes. This is optional but useful.
3393
+ *
3394
+ * 6. **Completion callback**: When the synchronization for this key finishes, `onFinish` is
3395
+ * called. On success, it runs after the state is stable (no follow-up needed) and the key has
3396
+ * been released. On failure, it runs right after the request fails and the key is released,
3397
+ * and then the action fails with the error.
3398
+ *
3399
+ * ```
3400
+ * State: liked = false (server confirmed)
3401
+ *
3402
+ * User taps LIKE:
3403
+ * → State: liked = true (optimistic)
3404
+ * → Key taken, Request 1 sends: setLiked(true)
3405
+ *
3406
+ * User taps UNLIKE (Request 1 still in flight):
3407
+ * → State: liked = false (optimistic)
3408
+ * → No request sent (key is taken)
3409
+ *
3410
+ * User taps LIKE (Request 1 still in flight):
3411
+ * → State: liked = true (optimistic)
3412
+ * → No request sent (key is taken)
3413
+ *
3414
+ * Request 1 completes:
3415
+ * → Sent value was `true`, current state is `true`
3416
+ * → They match, no follow-up needed, key released
3417
+ * ```
3418
+ *
3419
+ * If the state had been `false` when Request 1 completed, a follow-up Request 2 would
3420
+ * automatically be sent with `false`.
3421
+ *
3422
+ * ## How to use it
3423
+ *
3424
+ * Extend `OptimisticSync` instead of your base action, and DO NOT implement `reduce()`.
3425
+ * Instead, you must provide:
3426
+ *
3427
+ * - `valueToApply()` returns the value to apply optimistically, and then send to the server.
3428
+ * - `applyOptimisticValueToState(state, optimisticValue)` applies the value to the state.
3429
+ * - `getValueFromState(state)` reads the value from the state (to detect if a follow-up is needed).
3430
+ * - `sendValueToServer(value)` sends the value to the server.
3431
+ *
3432
+ * And optionally:
3433
+ *
3434
+ * - `optimisticSyncKeyParams()` so that different items can have concurrent requests.
3435
+ * - `applyServerResponseToState(state, serverResponse)` applies the server response to the state.
3436
+ * - `onFinish(error)` runs when the synchronization finishes, with or without errors.
3437
+ * - `ifShouldSendAnotherRequest` and `maxFollowUpRequests`, to customize the follow-ups.
3438
+ *
3439
+ * ```ts
3440
+ * class ToggleLike extends OptimisticSync<State, boolean> {
3441
+ * constructor(readonly itemId: string) { super(); }
3442
+ *
3443
+ * // Different items can have concurrent requests.
3444
+ * optimisticSyncKeyParams() { return this.itemId; }
3445
+ *
3446
+ * // The new value to apply (toggle the current state).
3447
+ * valueToApply() { return !this.state.items.get(this.itemId).liked; }
3448
+ *
3449
+ * // Apply the optimistic value to the state.
3450
+ * applyOptimisticValueToState(state: State, isLiked: boolean) {
3451
+ * return state.copy({ items: state.items.setLiked(this.itemId, isLiked) });
3452
+ * }
3453
+ *
3454
+ * // Read the current value from the state (used to detect if a follow-up is needed).
3455
+ * getValueFromState(state: State) { return state.items.get(this.itemId).liked; }
3456
+ *
3457
+ * // Send the value to the server, and optionally return the server-confirmed value.
3458
+ * async sendValueToServer(isLiked: boolean) {
3459
+ * const response = await api.setLiked(this.itemId, isLiked);
3460
+ * return response.liked; // Or return null if the server doesn't return a value.
3461
+ * }
3462
+ *
3463
+ * // Apply the server response to the state (can be different from the optimistic value).
3464
+ * applyServerResponseToState(state: State, liked: boolean) {
3465
+ * return state.copy({ items: state.items.setLiked(this.itemId, liked) });
3466
+ * }
3467
+ *
3468
+ * // Called when the state stabilizes (optional). Return a state to apply, or null.
3469
+ * async onFinish(error: any) {
3470
+ * if (error !== null) {
3471
+ * // Handle the error: reload from the server to restore the correct state.
3472
+ * const reloaded = await api.getItem(this.itemId);
3473
+ * return this.state.copy({ items: this.state.items.update(this.itemId, reloaded) });
3474
+ * }
3475
+ * return null; // Success, no state change needed.
3476
+ * }
3477
+ * }
3478
+ * ```
3479
+ *
3480
+ * ## Server response handling
3481
+ *
3482
+ * `sendValueToServer` can return a value from the server. If it's not `null` or `undefined`,
3483
+ * this value is applied to the state **only when the state stabilizes** (no pending changes).
3484
+ * This is useful when:
3485
+ * - The server normalizes or modifies values.
3486
+ * - You want to confirm the server accepted the change.
3487
+ * - The server returns the current state after the update.
3488
+ *
3489
+ * The server response is applied as is, and doesn't start a follow-up request.
3490
+ *
3491
+ * ## Error handling
3492
+ *
3493
+ * On failure, the optimistic state remains, `onFinish` is called with the error, and then the
3494
+ * action fails with the error. There are no follow-up requests after a failure.
3495
+ *
3496
+ * ## Difference from other features
3497
+ *
3498
+ * - **vs `debounce`**: Debounce waits for inactivity before sending *any* request.
3499
+ * `OptimisticSync` sends the first request immediately, and only coalesces subsequent changes.
3500
+ *
3501
+ * - **vs `nonReentrant`**: NonReentrant aborts subsequent dispatches entirely. `OptimisticSync`
3502
+ * applies the optimistic update and, if needed, sends a follow-up request.
3503
+ *
3504
+ * - **vs `OptimisticCommand`**: An `OptimisticCommand` runs once per dispatch, rolls back on
3505
+ * failure, and is non-reentrant, so it aborts the dispatches made while it's running.
3506
+ * `OptimisticSync` is designed for rapid toggling, where only the final value matters.
3507
+ *
3508
+ * ## Rollback support
3509
+ *
3510
+ * Two fields help with rollback logic in `onFinish`:
3511
+ *
3512
+ * - `optimisticValue`: The value returned by `valueToApply()` for this dispatch. It's set once
3513
+ * when the reducer starts, and remains available until the action finishes, including in
3514
+ * `onFinish`.
3515
+ *
3516
+ * - `lastSentValue`: The most recent value passed to `sendValueToServer`. Updated right before
3517
+ * each server request. Useful for debugging and logging.
3518
+ *
3519
+ * Example rollback guard using `optimisticValue`:
3520
+ *
3521
+ * ```ts
3522
+ * async onFinish(error: any) {
3523
+ * if (error !== null) {
3524
+ * // Only roll back if the state still reflects our optimistic update.
3525
+ * // If the user made another change, don't overwrite it.
3526
+ * if (this.getValueFromState(this.state) === this.optimisticValue) {
3527
+ * return this.applyOptimisticValueToState(this.state, this.getValueFromState(this.initialState));
3528
+ * }
3529
+ * }
3530
+ * return null;
3531
+ * }
3532
+ * ```
3533
+ *
3534
+ * Note `initialState` is the state when the action that sends the requests was dispatched.
3535
+ * If some of its requests succeeded before one failed, the server may already have a newer
3536
+ * value. That's why reloading is usually a safer choice than rolling back.
3537
+ *
3538
+ * Another possibility is to use `onFinish` to reload the value from the server. For example:
3539
+ *
3540
+ * ```ts
3541
+ * async onFinish(error: any) {
3542
+ * try {
3543
+ * const fresh = await api.fetchValue(this.itemId);
3544
+ * return this.applyServerResponseToState(this.state, fresh);
3545
+ * } catch (_) {
3546
+ * return null; // Ignore reload failures and keep the current state.
3547
+ * }
3548
+ * }
3549
+ * ```
3550
+ *
3551
+ * ## Which dispatch sends the requests
3552
+ *
3553
+ * Only the dispatch that took the key sends the requests (including the follow-ups), and only
3554
+ * it waits for them: `dispatchAndWait` waits until the state stabilizes, and `isWaiting` is
3555
+ * `true` meanwhile. The dispatches made while the key is taken apply their optimistic value,
3556
+ * and then finish right away.
3557
+ *
3558
+ * ## Clearing
3559
+ *
3560
+ * `store.clearInternalActionProps()` (which is also called by `store.setShutDown(true)`)
3561
+ * releases all keys at once, which is useful on logout. The dispatches made from then on take
3562
+ * the key again, and send their own requests. An action whose request was in flight when the
3563
+ * keys were released stops when that request finishes: it doesn't send follow-up requests,
3564
+ * doesn't apply the server response, and doesn't call `onFinish`. It's aborted with an
3565
+ * `AbortDispatchException`, so it doesn't fail, and doesn't show errors.
3566
+ *
3567
+ * Notes:
3568
+ * - It can be combined with `checkInternet`, both `{ dialog: true | false }` and
3569
+ * `{ abort: true }`. If there is no internet, the optimistic value is not applied, and no
3570
+ * request is sent.
3571
+ * - It should not be combined with `nonReentrant`, `retry`, `unlimitedRetryCheckInternet`,
3572
+ * `debounce`, `throttle`, `fresh`, `ignoreOld` or polling. Dispatching it with those throws
3573
+ * a `StoreException`.
3574
+ * - It should not be combined with `sequential`, which throws a `StoreException` too.
3575
+ * `OptimisticSync` needs dispatches to overlap: it applies the optimistic value as soon as the
3576
+ * action is dispatched, and coalesces the dispatches made while a request is in flight into a
3577
+ * single follow-up request. With `sequential`, the UI would stop responding immediately, and
3578
+ * nothing would ever be coalesced. Note `OptimisticSync` already guarantees a single
3579
+ * in-flight request per key, so you don't need `sequential` to serialize the requests.
3580
+ */
3581
+ export class OptimisticSync extends KissAction {
3582
+ /**
3583
+ * The optimistic value that was applied to the state by this dispatch. It's set once, when
3584
+ * the reducer starts, to the value returned by `valueToApply()`, and remains available in
3585
+ * `onFinish` for rollback logic.
3586
+ */
3587
+ optimisticValue;
3588
+ /**
3589
+ * The most recent value that was passed to `sendValueToServer`. It's updated right before
3590
+ * each server request (including follow-ups), and is `undefined` if this dispatch sent no
3591
+ * request (because another dispatch was already sending them). Useful for debugging, logging,
3592
+ * or implementing custom guards.
3593
+ */
3594
+ lastSentValue = undefined;
3595
+ /**
3596
+ * Safety limit for the number of follow-up requests, to avoid infinite loops. If the state is
3597
+ * still changing after this many follow-ups, the action fails with a `StoreException`.
3598
+ * Use `-1` for no limit. The default is 10000.
3599
+ */
3600
+ maxFollowUpRequests = 10000;
3601
+ /**
3602
+ * Optionally, override `optimisticSyncKeyParams()` to differentiate the coalescing by the
3603
+ * action parameters. For example, if you have a like button per item, return the item ID, so
3604
+ * that different items can have concurrent requests:
3605
+ *
3606
+ * ```ts
3607
+ * optimisticSyncKeyParams() { return this.itemId; }
3608
+ * ```
3609
+ *
3610
+ * You can also return an array of values:
3611
+ *
3612
+ * ```ts
3613
+ * optimisticSyncKeyParams() { return [this.userId, this.itemId]; }
3614
+ * ```
3615
+ *
3616
+ * Params are compared with `Object.is`, except arrays and plain objects, which are compared
3617
+ * by their contents.
3618
+ *
3619
+ * Important: If the action changes a different part of the state depending on its fields,
3620
+ * make the key depend on them too. Otherwise, while `ToggleLike('A')` has a request in flight,
3621
+ * `ToggleLike('B')` changes the state but doesn't send its own request, and the follow-up of
3622
+ * `ToggleLike('A')` only checks item A, so item B may never be sent to the server.
3623
+ *
3624
+ * See also: `computeOptimisticSyncKey()`, which uses this method by default to build the key.
3625
+ */
3626
+ optimisticSyncKeyParams() {
3627
+ return null;
3628
+ }
3629
+ /**
3630
+ * By default, the coalescing key combines the action class with `optimisticSyncKeyParams()`.
3631
+ * Override this method if you want different action classes to share the same coalescing key.
3632
+ *
3633
+ * Keys are compared with `Object.is`, except arrays and plain objects, which are compared by
3634
+ * their contents.
3635
+ */
3636
+ computeOptimisticSyncKey() {
3637
+ return [this.constructor, this.optimisticSyncKeyParams()];
3638
+ }
3639
+ /**
3640
+ * Override `applyServerResponseToState` to return a new state, where the given
3641
+ * `serverResponse` (previously received from the server when running `sendValueToServer`) is
3642
+ * applied to the current `state`. Example:
3643
+ *
3644
+ * ```ts
3645
+ * applyServerResponseToState(state: State, serverResponse: Response) {
3646
+ * return state.copy({ items: state.items.setLiked(this.itemId, serverResponse.isLiked) });
3647
+ * }
3648
+ * ```
3649
+ *
3650
+ * Note `serverResponse` is never `null` or `undefined` here, because this method is only
3651
+ * called when `sendValueToServer` returned some value.
3652
+ *
3653
+ * If you DO NOT want to apply the server response to the state, return `null`
3654
+ * (which is the default).
3655
+ */
3656
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3657
+ applyServerResponseToState(state, serverResponse) {
3658
+ return null;
3659
+ }
3660
+ /**
3661
+ * Optionally, override `onFinish` to run any code after the synchronization completes. For
3662
+ * example, you might want to reload related data from the server, show a confirmation message,
3663
+ * or perform cleanup.
3664
+ *
3665
+ * Note `onFinish` is called in both success and failure scenarios. On success, it runs only
3666
+ * after the state is stable for this key. On failure, it runs immediately after the request
3667
+ * fails (there is no further stabilization or follow-up).
3668
+ *
3669
+ * Important: The key is released *before* `onFinish` runs. This means new dispatches for the
3670
+ * same key may start a new request while `onFinish` is still running.
3671
+ *
3672
+ * The `error` parameter is `null` on success, or contains the error if the request failed.
3673
+ *
3674
+ * If `onFinish` returns a state (not `null`), it will be applied automatically. If it returns
3675
+ * `null`, no state change is made.
3676
+ *
3677
+ * ```ts
3678
+ * async onFinish(error: any) {
3679
+ * if (error === null) {
3680
+ * // Success: show a confirmation, log analytics, etc.
3681
+ * return null;
3682
+ * } else {
3683
+ * // Failure:
3684
+ * // - Show a dialog.
3685
+ * // - Reload data from the server.
3686
+ * // - Roll back the optimistic update.
3687
+ * }
3688
+ * }
3689
+ * ```
3690
+ *
3691
+ * To show an error dialog in `onFinish`:
3692
+ *
3693
+ * ```ts
3694
+ * this.dispatch(new UserExceptionAction('The server request failed. Info reloaded.'));
3695
+ * ```
3696
+ *
3697
+ * To reload data from the server in `onFinish`:
3698
+ *
3699
+ * ```ts
3700
+ * return this.state.copy({ info: await api.loadInfo() });
3701
+ * ```
3702
+ *
3703
+ * To roll back the optimistic update in `onFinish`:
3704
+ *
3705
+ * ```ts
3706
+ * return this.state.copy({ isLiked: this.getValueFromState(this.initialState) });
3707
+ * ```
3708
+ *
3709
+ * You can combine the above strategies as needed:
3710
+ *
3711
+ * ```ts
3712
+ * async onFinish(error: any) {
3713
+ * if (error === null) return null;
3714
+ *
3715
+ * // 1. Show an error message to the user.
3716
+ * this.dispatch(new UserExceptionAction('The server request failed. Info reloaded.'));
3717
+ *
3718
+ * // 2. Immediately roll back to the value before the action.
3719
+ * this.dispatch(new UpdateStateAction((state: State) =>
3720
+ * state.copy({ isLiked: this.getValueFromState(this.initialState) })));
3721
+ *
3722
+ * // 3. Then, to be sure, reload the value from the server.
3723
+ * return this.state.copy({ info: await api.loadInfo() });
3724
+ * }
3725
+ * ```
3726
+ *
3727
+ * Important:
3728
+ *
3729
+ * - If `onFinish(error)` throws, the original `error` is lost, and the error thrown by
3730
+ * `onFinish` becomes the action error. You can handle it in `wrapError`.
3731
+ *
3732
+ * - Same on success: If `onFinish(null)` throws, the whole action fails even though the
3733
+ * server request succeeded. You can handle it in `wrapError`.
3734
+ */
3735
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3736
+ onFinish(error) {
3737
+ return null;
3738
+ }
3739
+ /**
3740
+ * If `ifShouldSendAnotherRequest` returns true, the action will send one more request, with
3741
+ * the value from the state.
3742
+ *
3743
+ * The default behavior of this method is to compare:
3744
+ * - The `stateValue`, which is the value currently in the store state.
3745
+ * - The `sentValue`, which is the value that was sent to the server.
3746
+ *
3747
+ * If they are different, it means the state was changed after we sent the request, so we
3748
+ * should send another request with the new value.
3749
+ *
3750
+ * Values are compared with `Object.is` (which is the same as `===`, except that `NaN` is equal
3751
+ * to `NaN`). So, make sure `getValueFromState` returns the same object you applied, or
3752
+ * override this method if you need custom equality logic.
3753
+ *
3754
+ * The `requestCount` is the number of requests already sent by this action (1 after the first
3755
+ * request). Note the number of follow-up requests is limited by `maxFollowUpRequests`.
3756
+ */
3757
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
3758
+ ifShouldSendAnotherRequest({ stateValue, sentValue, requestCount }) {
3759
+ return !Object.is(stateValue, sentValue);
3760
+ }
3761
+ /**
3762
+ * Do NOT override this method. Implement `valueToApply`, `applyOptimisticValueToState`,
3763
+ * `getValueFromState` and `sendValueToServer` instead.
3764
+ */
3765
+ async reduce() {
3766
+ const value = this.valueToApply();
3767
+ this.optimisticValue = value;
3768
+ // Always applies the optimistic update immediately.
3769
+ this._applyState(this.applyOptimisticValueToState(this.state, value));
3770
+ // If another dispatch has the key, its request is in flight. The optimistic update is
3771
+ // already applied, so we just finish. When that request completes, it checks if a
3772
+ // follow-up is needed.
3773
+ if (!this.store._takeOptimisticSyncKey(this.computeOptimisticSyncKey(), this))
3774
+ return null;
3775
+ await this._sendAndFollowUp(value);
3776
+ return null;
3777
+ }
3778
+ /**
3779
+ * Sends the request, and then sends follow-up requests while the value in the state (from
3780
+ * `getValueFromState`) is different from the value that was sent.
3781
+ */
3782
+ async _sendAndFollowUp(value) {
3783
+ let sentValue = value;
3784
+ let requestCount = 0;
3785
+ let finishError = null;
3786
+ try {
3787
+ while (true) {
3788
+ requestCount++;
3789
+ this.lastSentValue = sentValue;
3790
+ // Sends the value, and gets the server response (may be null or undefined).
3791
+ const serverResponse = await this.sendValueToServer(sentValue);
3792
+ // The keys were released by `store.clearInternalActionProps()` while the request was
3793
+ // in flight (for example, on logout). So, stop here.
3794
+ if (!this.store._hasOptimisticSyncKey(this))
3795
+ throw this._clearedError();
3796
+ const stateValue = this.getValueFromState(this.state);
3797
+ // If the state changed while the request was in flight, sends a follow-up request with
3798
+ // the current value, without applying the server response, since the state isn't stable.
3799
+ if (this.ifShouldSendAnotherRequest({ stateValue, sentValue, requestCount })) {
3800
+ if ((this.maxFollowUpRequests !== -1) && (requestCount > this.maxFollowUpRequests))
3801
+ throw new StoreException(`Too many follow-up requests in action ${this.constructor.name} (> ${this.maxFollowUpRequests}).`);
3802
+ sentValue = stateValue;
3803
+ continue;
3804
+ }
3805
+ // The state is stable for this key, so we apply the server response, if any.
3806
+ if (serverResponse !== null && serverResponse !== undefined) {
3807
+ const newState = this.applyServerResponseToState(this.state, serverResponse);
3808
+ if (newState !== null)
3809
+ this._applyState(newState);
3810
+ }
3811
+ break;
3812
+ }
3813
+ }
3814
+ catch (error) {
3815
+ if (!this.store._hasOptimisticSyncKey(this))
3816
+ throw this._clearedError();
3817
+ finishError = error;
3818
+ }
3819
+ // Releases the key before `onFinish`, so that new dispatches can send requests.
3820
+ this.store._releaseOptimisticSyncKey(this);
3821
+ const newState = await this.onFinish(finishError);
3822
+ if (newState !== null && newState !== undefined)
3823
+ this._applyState(newState);
3824
+ // Fails, so that the user can be notified.
3825
+ if (finishError !== null)
3826
+ throw finishError;
3827
+ }
3828
+ _clearedError() {
3829
+ return kissAbort('The internal action props were cleared, so the action stopped syncing.');
3830
+ }
3831
+ _applyState(newState) {
3832
+ this.dispatch(new UpdateStateAction(() => newState));
3833
+ }
3834
+ /**
3835
+ * For Kiss internal use only.
3836
+ * @internal
3837
+ */
3838
+ _injectStore(_store) {
3839
+ super._injectStore(_store);
3840
+ _checkIncompatibleFeatures(this, 'an OptimisticSync', false);
3841
+ }
3842
+ }
3843
+ // The device ID returned by the default `OptimisticSyncWithPush.deviceId`, generated once.
3844
+ let _deviceId = undefined;
3845
+ /**
3846
+ * The `OptimisticSyncWithPush` abstract class is for actions where:
3847
+ *
3848
+ * 1. Your app receives server-pushed updates (WebSockets, Server-Sent Events (SSE), Firebase)
3849
+ * that may change the same state this action controls. It must be resilient to out-of-order
3850
+ * delivery, and multiple devices can change the same data.
3851
+ *
3852
+ * 2. Non-blocking user interactions (like toggling a "like" button) should update the UI
3853
+ * immediately and send the updated value to the server, making sure the server and the UI
3854
+ * are eventually consistent.
3855
+ *
3856
+ * 3. You want "last write wins" semantics across devices. In other words, with multiple devices,
3857
+ * that's how we decide what the truth is when two devices disagree.
3858
+ *
3859
+ * In other words, it allows:
3860
+ * - Optimistic UI
3861
+ * - Multi-device writes
3862
+ * - Server push
3863
+ * - Out-of-order delivery
3864
+ *
3865
+ * **IMPORTANT:** If your app does not receive server-pushed updates, use `OptimisticSync`
3866
+ * instead. In any case, please read the documentation of `OptimisticSync` first, as this class
3867
+ * builds upon that behavior, with additional logic to handle server-pushed updates.
3868
+ *
3869
+ * ## How it works
3870
+ *
3871
+ * 1. **Immediate UI feedback**: The action is not throttled or debounced in any way, and every
3872
+ * dispatch applies an optimistic update to the state immediately. This guarantees a very good
3873
+ * user experience, because there is immediate feedback on every interaction. Technically,
3874
+ * every dispatch applies `valueToApply()` to the state immediately, using
3875
+ * `applyOptimisticValueToState`.
3876
+ *
3877
+ * 2. **Single in-flight request**: The first time the action is dispatched, the updated value is
3878
+ * immediately sent to the server. However, any other value changes that occur while the first
3879
+ * request is in flight will NOT be sent, at least not immediately. In other words, only
3880
+ * **one** request is in flight at a time per key (as defined by `computeOptimisticSyncKey()`
3881
+ * and `optimisticSyncKeyParams()`), because the first dispatch takes that key, and other
3882
+ * dispatches don't send requests while the key is taken. This potentially reduces the number
3883
+ * of requests sent to the server, while coalescing intermediate changes.
3884
+ *
3885
+ * 3. **Follow-up requests**: If the action is dispatched while a request started by
3886
+ * `sendValueToServer` is in flight (for example, the user tapped a "like" button again while
3887
+ * the first request was pending), a follow-up request may be automatically sent after the
3888
+ * current one completes. Whether a follow-up is needed is decided when the current request
3889
+ * finishes, using a local-revision that is kept for the key, and incremented by each
3890
+ * dispatch. This process repeats until the state stabilizes.
3891
+ *
3892
+ * 4. **Push handling**: If a server push changes the same state while a request is in flight,
3893
+ * when the request completes it checks whether the most recent change for this key came from
3894
+ * a PUSH. If so, no follow-up request is needed, because the push already came from the
3895
+ * server. This requires server pushes to be applied by an action that extends `ServerPush`,
3896
+ * with the same key as the corresponding `OptimisticSyncWithPush` action.
3897
+ * However, when the request completes, the server revision of its response may show that
3898
+ * the push is older than the request (the server applied the push first). In this case, the
3899
+ * pushed value is stale, so the latest local value is put back in the state (unless a newer
3900
+ * push arrived since then), and the most recent change counts as local. So, a follow-up
3901
+ * request is sent if the value was changed locally while the request was in flight.
3902
+ *
3903
+ * 5. **Fewer intermediate requests**: If the state changes many times while the request is in
3904
+ * flight, all those changes are coalesced into a single follow-up request. However, since
3905
+ * `OptimisticSyncWithPush` uses a local-revision to track changes, it can send a follow-up
3906
+ * request even if the final value is the same as the value that was sent. This is necessary
3907
+ * because here we assume other devices or users may have changed the value on the server in
3908
+ * the meantime. Note this is different from `OptimisticSync`, which assumes only the current
3909
+ * user/device changes the value, and compares the sent value with the current state value to
3910
+ * decide if a follow-up request is needed.
3911
+ *
3912
+ * 6. **Server response handling**: Your implementation of `sendValueToServer` must call
3913
+ * `informServerRevision()` after each successful request. If the revision is not informed,
3914
+ * the action fails with a `StoreException`. This is necessary to handle out-of-order pushes
3915
+ * correctly. Also, optionally, if `sendValueToServer` returns a value (not `null` or
3916
+ * `undefined`), it's applied to the state using `applyServerResponseToState` when the state
3917
+ * stabilizes, unless a newer server revision is already known for this key (for example,
3918
+ * because of a newer push).
3919
+ * Note: If the request started by `sendValueToServer` fails, then `sendValueToServer` should
3920
+ * throw an error, and not call `informServerRevision()`.
3921
+ *
3922
+ * 7. **Completion callback**: When the synchronization for this key finishes, `onFinish` is
3923
+ * called, allowing you to handle errors or perform side effects, like showing a message or
3924
+ * reloading data. On success, it runs after the state is stable (no follow-up needed) and the
3925
+ * key has been released. On failure, it runs right after the request fails and the key is
3926
+ * released, and then the action fails with the error.
3927
+ * Note: If the action is dispatched while the key is taken, it still applies the optimistic
3928
+ * update immediately, but it does not call `onFinish`. Only the dispatch that took the key
3929
+ * sends the requests and calls `onFinish`.
3930
+ *
3931
+ * 8. **Safety limit**: To avoid infinite loops, there is a maximum number of follow-up requests
3932
+ * (`maxFollowUpRequests`, default 10000). If exceeded, the action fails with a
3933
+ * `StoreException`. Change it to use a different limit, or use `-1` for no limit.
3934
+ *
3935
+ * ## Flow example
3936
+ *
3937
+ * ```
3938
+ * State: liked = false
3939
+ *
3940
+ * User taps LIKE:
3941
+ * → State: liked = true (optimistic).
3942
+ * → Key taken, Request 1 sends: setLiked(true).
3943
+ * → Local-revision is 1.
3944
+ *
3945
+ * User taps UNLIKE (Request 1 still in flight):
3946
+ * → State: liked = false (optimistic).
3947
+ * → No request sent (key is taken).
3948
+ * → Local-revision is 2.
3949
+ *
3950
+ * User taps LIKE (Request 1 still in flight):
3951
+ * → State: liked = true (optimistic).
3952
+ * → No request sent (key is taken).
3953
+ * → Local-revision is 3.
3954
+ *
3955
+ * Request 1 completes:
3956
+ * → The last state change was NOT done by a PUSH.
3957
+ * → Compares the local-revision of Request 1 (revision 1) with the current
3958
+ * local-revision (revision 3).
3959
+ * → They do NOT match, so a follow-up is needed.
3960
+ * → Request 2 sends: setLiked(true).
3961
+ *
3962
+ * Request 2 completes:
3963
+ * → The last state change was NOT done by a PUSH.
3964
+ * → Compares the local-revision of Request 2 (revision 3) with the current
3965
+ * local-revision (also revision 3).
3966
+ * → They match, no follow-up needed.
3967
+ * → Key released.
3968
+ * ```
3969
+ *
3970
+ * ## Flow example with PUSH
3971
+ *
3972
+ * ```
3973
+ * State: liked = false
3974
+ *
3975
+ * User taps LIKE:
3976
+ * → State: liked = true (optimistic).
3977
+ * → Key taken, Request 1 sends: setLiked(true).
3978
+ * → Local-revision is 1.
3979
+ *
3980
+ * User taps UNLIKE (Request 1 still in flight):
3981
+ * → State: liked = false (optimistic).
3982
+ * → No request sent (key is taken).
3983
+ * → Local-revision is 2.
3984
+ *
3985
+ * A PUSH arrives with liked = false.
3986
+ *
3987
+ * Request 1 completes:
3988
+ * → The last state change was done by a PUSH.
3989
+ * → So a follow-up is NOT needed.
3990
+ * → Key released.
3991
+ * ```
3992
+ *
3993
+ * ## How to use it
3994
+ *
3995
+ * Extend `OptimisticSyncWithPush` instead of your base action, and DO NOT implement `reduce()`.
3996
+ * Instead, you must provide:
3997
+ *
3998
+ * - `valueToApply()` returns the value to apply optimistically, and then send to the server.
3999
+ * - `applyOptimisticValueToState(state, optimisticValue)` applies the value to the state.
4000
+ * - `getValueFromState(state)` reads the value from the state (sent by the follow-up requests).
4001
+ * - `sendValueToServer(value, localRevision, deviceId)` sends the value to the server, and calls
4002
+ * `informServerRevision()` with the server revision of the response.
4003
+ * - `getServerRevisionFromState(state, key)` reads the server revision that `ServerPush` saved
4004
+ * in the state, or returns `-1`.
4005
+ *
4006
+ * And optionally:
4007
+ *
4008
+ * - `optimisticSyncKeyParams()` so that different items can have concurrent requests.
4009
+ * - `applyServerResponseToState(state, serverResponse)` applies the server response to the state.
4010
+ * - `onFinish(error)` runs when the synchronization finishes, with or without errors.
4011
+ * - `maxFollowUpRequests`, to limit the follow-up requests.
4012
+ *
4013
+ * ```ts
4014
+ * class ToggleLike extends OptimisticSyncWithPush<State, boolean> {
4015
+ * constructor(readonly itemId: string) { super(); }
4016
+ *
4017
+ * optimisticSyncKeyParams() { return this.itemId; }
4018
+ * valueToApply() { return !this.state.isLiked(this.itemId); }
4019
+ * applyOptimisticValueToState(state: State, liked: boolean) { return state.setLiked(this.itemId, liked); }
4020
+ * getValueFromState(state: State) { return state.isLiked(this.itemId); }
4021
+ * getServerRevisionFromState(state: State, key: any) { return state.revisionOf(key) ?? -1; }
4022
+ *
4023
+ * async sendValueToServer(liked: boolean, localRevision: number, deviceId: number) {
4024
+ * const response = await api.setLiked(this.itemId, liked, localRevision, deviceId);
4025
+ * if (!response.ok) throw new Error('Server error');
4026
+ * this.informServerRevision(response.serverRevision);
4027
+ * return response.liked;
4028
+ * }
4029
+ *
4030
+ * applyServerResponseToState(state: State, liked: boolean) { return state.setLiked(this.itemId, liked); }
4031
+ * }
4032
+ * ```
4033
+ *
4034
+ * The server pushes are applied by a separate action, that extends `ServerPush`, and whose
4035
+ * `associatedAction()` returns `ToggleLike`. See `ServerPush` for details.
4036
+ *
4037
+ * ## Clearing
4038
+ *
4039
+ * `store.clearInternalActionProps()` (which is also called by `store.setShutDown(true)`)
4040
+ * releases all keys, and removes all the revisions kept for them (local-revisions, and the
4041
+ * server revisions that are not in the state), which is useful on logout. An action whose
4042
+ * request was in flight when the keys were released stops when that request finishes: it
4043
+ * doesn't send follow-up requests, doesn't apply the server response, and doesn't call
4044
+ * `onFinish`. It's aborted with an `AbortDispatchException`, so it doesn't fail, and doesn't
4045
+ * show errors.
4046
+ *
4047
+ * Notes:
4048
+ * - It can be combined with `checkInternet`, both `{ dialog: true | false }` and
4049
+ * `{ abort: true }`. If there is no internet, the optimistic value is not applied, and no
4050
+ * request is sent.
4051
+ * - It should not be combined with `nonReentrant`, `retry`, `unlimitedRetryCheckInternet`,
4052
+ * `debounce`, `throttle`, `fresh`, `ignoreOld` or polling. Dispatching it with those throws
4053
+ * a `StoreException`.
4054
+ * - It should not be combined with `sequential`, which throws a `StoreException` too, for the
4055
+ * same reasons given in `OptimisticSync`, and also because the revision tracking assumes the
4056
+ * server pushes can be applied to the state while a request is in flight.
4057
+ * - Apply the server pushes with a separate action that extends `ServerPush`.
4058
+ */
4059
+ export class OptimisticSyncWithPush extends KissAction {
4060
+ /**
4061
+ * The device ID is used to tell apart the revisions of different devices. It's sent to the
4062
+ * server by `sendValueToServer`, and the server pushes must return it (see `ServerPush`), so
4063
+ * that the app can recognize the pushes of its own requests.
4064
+ *
4065
+ * The default is a random integer generated once per app run, but you can change it to
4066
+ * return a persistent unique ID per device:
4067
+ *
4068
+ * ```ts
4069
+ * OptimisticSyncWithPush.deviceId = () => myDeviceId;
4070
+ * ```
4071
+ */
4072
+ static deviceId = () => {
4073
+ _deviceId ??= Math.floor(Math.random() * 4294967296) + (Math.floor(Math.random() * 10000) * 10000000000);
4074
+ return _deviceId;
4075
+ };
4076
+ /**
4077
+ * The optimistic value that was applied to the state by this dispatch. It's set once, when
4078
+ * the reducer starts, to the value returned by `valueToApply()`, and remains available in
4079
+ * `onFinish` for rollback logic.
4080
+ */
4081
+ optimisticValue;
4082
+ /**
4083
+ * The most recent value that was passed to `sendValueToServer`. It's updated right before
4084
+ * each server request (including follow-ups), and is `undefined` if this dispatch sent no
4085
+ * request (because another dispatch was already sending them). Useful for debugging, logging,
4086
+ * or implementing custom guards.
4087
+ */
4088
+ lastSentValue = undefined;
4089
+ /**
4090
+ * Safety limit for the number of follow-up requests, to avoid infinite loops. If the state is
4091
+ * still changing after this many follow-ups, the action fails with a `StoreException`.
4092
+ * Use `-1` for no limit. The default is 10000.
4093
+ */
4094
+ maxFollowUpRequests = 10000;
4095
+ // The key of this dispatch, computed once when the reducer starts.
4096
+ _key = undefined;
4097
+ // The server revision informed by `informServerRevision()` during the current request, or
4098
+ // `null` if it was not informed. It's reset before each request.
4099
+ _informedServerRevision = null;
4100
+ // True if `informServerRevision()`, during the current request, found that the push applied
4101
+ // while the request was in flight is older than the request. It's reset before each request.
4102
+ _wasPushStale = false;
4103
+ /**
4104
+ * Optionally, override `optimisticSyncKeyParams()` to differentiate the coalescing by the
4105
+ * action parameters. For example, if you have a like button per item, return the item ID, so
4106
+ * that different items can have concurrent requests:
4107
+ *
4108
+ * ```ts
4109
+ * optimisticSyncKeyParams() { return this.itemId; }
4110
+ * ```
4111
+ *
4112
+ * You can also return an array of values:
4113
+ *
4114
+ * ```ts
4115
+ * optimisticSyncKeyParams() { return [this.userId, this.itemId]; }
4116
+ * ```
4117
+ *
4118
+ * Params are compared with `Object.is`, except arrays and plain objects, which are compared
4119
+ * by their contents.
4120
+ *
4121
+ * Important: If the action changes a different part of the state depending on its fields,
4122
+ * make the key depend on them too. Otherwise, while `ToggleLike('A')` has a request in flight,
4123
+ * `ToggleLike('B')` changes the state but doesn't send its own request, and the follow-up of
4124
+ * `ToggleLike('A')` only reads item A from the state, so item B may never be sent to the
4125
+ * server.
4126
+ *
4127
+ * The `ServerPush` actions that apply the pushes of this value must return the same params
4128
+ * from their own `optimisticSyncKeyParams()`.
4129
+ *
4130
+ * See also: `computeOptimisticSyncKey()`, which uses this method by default to build the key.
4131
+ */
4132
+ optimisticSyncKeyParams() {
4133
+ return null;
4134
+ }
4135
+ /**
4136
+ * By default, the coalescing key combines the action class with `optimisticSyncKeyParams()`.
4137
+ * Override this method if you want different action classes to share the same coalescing key.
4138
+ * In this case, override `computeOptimisticSyncKey()` in the `ServerPush` actions too, so
4139
+ * that they compute the same key.
4140
+ *
4141
+ * Keys are compared with `Object.is`, except arrays and plain objects, which are compared by
4142
+ * their contents.
4143
+ */
4144
+ computeOptimisticSyncKey() {
4145
+ return [this.constructor, this.optimisticSyncKeyParams()];
4146
+ }
4147
+ /**
4148
+ * Override `applyServerResponseToState` to return a new state, where the given
4149
+ * `serverResponse` (previously received from the server when running `sendValueToServer`) is
4150
+ * applied to the current `state`. Example:
4151
+ *
4152
+ * ```ts
4153
+ * applyServerResponseToState(state: State, serverResponse: Response) {
4154
+ * return state.copy({ items: state.items.setLiked(this.itemId, serverResponse.isLiked) });
4155
+ * }
4156
+ * ```
4157
+ *
4158
+ * Note `serverResponse` is never `null` or `undefined` here, because this method is only
4159
+ * called when `sendValueToServer` returned some value. It's also not called when a newer
4160
+ * server revision is known for the key (for example, because of a newer push), since then the
4161
+ * response is stale.
4162
+ *
4163
+ * If you DO NOT want to apply the server response to the state, return `null`
4164
+ * (which is the default).
4165
+ */
4166
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
4167
+ applyServerResponseToState(state, serverResponse) {
4168
+ return null;
4169
+ }
4170
+ /**
4171
+ * You must call `informServerRevision()` from your `sendValueToServer`, to inform the server
4172
+ * revision returned in the response. If you don't, the action fails with a `StoreException`.
4173
+ *
4174
+ * The server must provide a monotonically increasing revision number (for example, a
4175
+ * timestamp, or a version number), comparable across devices and users, that allows the app
4176
+ * to determine the ordering of the updates. You can also pass a `Date`, which is converted to
4177
+ * its milliseconds since the epoch.
4178
+ *
4179
+ * Kiss uses this information to:
4180
+ * - Track the latest known server revision (for "last write wins" ordering).
4181
+ * - Determine whether to apply the server response (stale responses are automatically
4182
+ * ignored).
4183
+ *
4184
+ * **Usage:** Just call this method with the server revision from the response. Kiss handles
4185
+ * all the logic, so you don't need to check or compare anything yourself. Example:
4186
+ *
4187
+ * ```ts
4188
+ * async sendValueToServer(isLiked: boolean, localRevision: number, deviceId: number) {
4189
+ * const response = await api.setLiked(this.itemId, isLiked, localRevision, deviceId);
4190
+ * if (!response.ok) throw new Error('Server error');
4191
+ * this.informServerRevision(response.serverRevision);
4192
+ * return response.liked;
4193
+ * }
4194
+ * ```
4195
+ *
4196
+ * **Behavior:** It only updates the server revision kept for this key if `revision` is greater
4197
+ * than the newest known server revision, considering both the revision kept by Kiss, and
4198
+ * `getServerRevisionFromState()`. This prevents regressions from stale or out-of-order
4199
+ * updates. The server response is only applied if this revision is not older than the newest
4200
+ * known revision. If a push was applied while the request was in flight, and `revision` is
4201
+ * greater than the server revision of that push, the push is stale: when the request
4202
+ * finishes, the latest local value is put back in the state.
4203
+ */
4204
+ informServerRevision(revision) {
4205
+ const value = (revision instanceof Date) ? revision.getTime() : revision;
4206
+ if (typeof value !== 'number' || !Number.isFinite(value))
4207
+ throw new StoreException(`Action ${this.constructor.name} informed an invalid server revision: ` +
4208
+ `it must be a finite number, or a valid Date, but got ${String(revision)}.`);
4209
+ this._informedServerRevision = value;
4210
+ // Only while this dispatch sends the requests. Otherwise, the key may have been released by
4211
+ // `store.clearInternalActionProps()`, and the revision would belong to the previous user.
4212
+ if (!this.store._hasOptimisticSyncKey(this))
4213
+ return;
4214
+ const known = this._revisionOf(this._key);
4215
+ // Only moves forward. Since this revision is newer than any push, the latest change is no
4216
+ // longer from a push. If a push was applied while the request was in flight, the server
4217
+ // applied it before this request, so the pushed value is stale.
4218
+ if (value > known.serverRevision) {
4219
+ if (known.isPush)
4220
+ this._wasPushStale = true;
4221
+ this.store._setOptimisticSyncRevision(this._key, { ...known, serverRevision: value, isPush: false });
4222
+ }
4223
+ }
4224
+ /**
4225
+ * Optionally, override `onFinish` to run any code after the synchronization completes. For
4226
+ * example, you might want to reload related data from the server, show a confirmation message,
4227
+ * or perform cleanup.
4228
+ *
4229
+ * Note `onFinish` is called in both success and failure scenarios. On success, it runs only
4230
+ * after the state is stable for this key. On failure, it runs immediately after the request
4231
+ * fails (there is no further stabilization or follow-up).
4232
+ *
4233
+ * Important: The key is released *before* `onFinish` runs. This means new dispatches for the
4234
+ * same key may start a new request while `onFinish` is still running.
4235
+ *
4236
+ * The `error` parameter is `null` on success, or contains the error if the request failed.
4237
+ *
4238
+ * If `onFinish` returns a state (not `null`), it will be applied automatically. If it returns
4239
+ * `null`, no state change is made.
4240
+ *
4241
+ * ```ts
4242
+ * async onFinish(error: any) {
4243
+ * if (error === null) {
4244
+ * // Success: show a confirmation, log analytics, etc.
4245
+ * return null;
4246
+ * } else {
4247
+ * // Failure: reload data from the server.
4248
+ * const reloadedInfo = await api.loadInfo();
4249
+ * return this.state.copy({ info: reloadedInfo });
4250
+ * }
4251
+ * }
4252
+ * ```
4253
+ *
4254
+ * Important:
4255
+ *
4256
+ * - If `onFinish(error)` throws, the original `error` is lost, and the error thrown by
4257
+ * `onFinish` becomes the action error. You can handle it in `wrapError`.
4258
+ *
4259
+ * - Same on success: If `onFinish(null)` throws, the whole action fails even though the
4260
+ * server request succeeded. You can handle it in `wrapError`.
4261
+ */
4262
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The parameters document the signature to override.
4263
+ onFinish(error) {
4264
+ return null;
4265
+ }
4266
+ /**
4267
+ * Do NOT override this method. Implement `valueToApply`, `applyOptimisticValueToState`,
4268
+ * `getValueFromState`, `sendValueToServer` and `getServerRevisionFromState` instead.
4269
+ */
4270
+ async reduce() {
4271
+ const key = this._key = this.computeOptimisticSyncKey();
4272
+ const value = this.valueToApply();
4273
+ this.optimisticValue = value;
4274
+ const newState = this.applyOptimisticValueToState(this.state, value);
4275
+ // Each dispatch is a new local change, so it increments the local-revision of the key.
4276
+ // The latest change is now local, and not from a push.
4277
+ const known = this._revisionOf(key);
4278
+ const localRevision = known.localRevision + 1;
4279
+ this.store._setOptimisticSyncRevision(key, {
4280
+ localRevision,
4281
+ serverRevision: known.serverRevision,
4282
+ isPush: false,
4283
+ localValue: this.getValueFromState(newState),
4284
+ });
4285
+ // Always applies the optimistic update immediately.
4286
+ this._applyState(newState);
4287
+ // If another dispatch has the key, its request is in flight. The optimistic update is
4288
+ // already applied, so we just finish. When that request completes, it checks if a
4289
+ // follow-up is needed.
4290
+ if (!this.store._takeOptimisticSyncKey(key, this))
4291
+ return null;
4292
+ await this._sendAndFollowUp(value, localRevision);
4293
+ return null;
4294
+ }
4295
+ /**
4296
+ * Sends the request, and then sends follow-up requests while the latest change of the key is
4297
+ * local (not from a push), and newer than the change that was sent.
4298
+ */
4299
+ async _sendAndFollowUp(value, localRevision) {
4300
+ let sentValue = value;
4301
+ let sentLocalRevision = localRevision;
4302
+ let requestCount = 0;
4303
+ let finishError = null;
4304
+ try {
4305
+ while (true) {
4306
+ requestCount++;
4307
+ this.lastSentValue = sentValue;
4308
+ // Reset before each request, to detect if `informServerRevision()` was called.
4309
+ this._informedServerRevision = null;
4310
+ this._wasPushStale = false;
4311
+ // Sends the value, and gets the server response (may be null or undefined).
4312
+ const serverResponse = await this.sendValueToServer(sentValue, sentLocalRevision, OptimisticSyncWithPush.deviceId());
4313
+ // The keys were released by `store.clearInternalActionProps()` while the request was
4314
+ // in flight (for example, on logout). So, stop here.
4315
+ if (!this.store._hasOptimisticSyncKey(this))
4316
+ throw this._clearedError();
4317
+ const informedServerRevision = this._informedServerRevision;
4318
+ if (informedServerRevision === null)
4319
+ throw new StoreException(`Action ${this.constructor.name} is an OptimisticSyncWithPush, which requires calling ` +
4320
+ '`informServerRevision()` inside `sendValueToServer()`. ' +
4321
+ 'If you don\'t need server-push handling, use `OptimisticSync` instead.');
4322
+ const known = this._revisionOf(this._key);
4323
+ // A push applied while the request was in flight is older than the request, so it
4324
+ // overwrote the latest local value with a stale value. Unless a newer push arrived since
4325
+ // then, puts the latest local value back in the state. It's then sent by the follow-up
4326
+ // request, if any, and otherwise it's the value the server has.
4327
+ if (this._wasPushStale && !known.isPush &&
4328
+ !Object.is(this.getValueFromState(this.state), known.localValue))
4329
+ this._applyState(this.applyOptimisticValueToState(this.state, known.localValue));
4330
+ // If the latest change was made locally (not by a push), and the local-revision advanced
4331
+ // since this request was sent, the user changed the value while the request was in
4332
+ // flight. So, sends a follow-up request with the current value, without applying the
4333
+ // server response, since the state isn't stable.
4334
+ if (!known.isPush && (known.localRevision > sentLocalRevision)) {
4335
+ if ((this.maxFollowUpRequests !== -1) && (requestCount > this.maxFollowUpRequests))
4336
+ throw new StoreException(`Too many follow-up requests in action ${this.constructor.name} (> ${this.maxFollowUpRequests}).`);
4337
+ sentValue = this.getValueFromState(this.state);
4338
+ sentLocalRevision = known.localRevision;
4339
+ continue;
4340
+ }
4341
+ // The state is stable for this key, so we apply the server response, if any, but only
4342
+ // if it's not stale (no newer server revision is known, for example from a push).
4343
+ if (serverResponse !== null && serverResponse !== undefined &&
4344
+ informedServerRevision >= known.serverRevision) {
4345
+ const newState = this.applyServerResponseToState(this.state, serverResponse);
4346
+ if (newState !== null)
4347
+ this._applyState(newState);
4348
+ }
4349
+ break;
4350
+ }
4351
+ }
4352
+ catch (error) {
4353
+ if (!this.store._hasOptimisticSyncKey(this))
4354
+ throw this._clearedError();
4355
+ finishError = error;
4356
+ }
4357
+ // Releases the key before `onFinish`, so that new dispatches can send requests.
4358
+ this.store._releaseOptimisticSyncKey(this);
4359
+ const newState = await this.onFinish(finishError);
4360
+ if (newState !== null && newState !== undefined)
4361
+ this._applyState(newState);
4362
+ // Fails, so that the user can be notified.
4363
+ if (finishError !== null)
4364
+ throw finishError;
4365
+ }
4366
+ /**
4367
+ * The revision kept for the given key, where the server revision is the newest of the one
4368
+ * kept by Kiss, and the one in the state.
4369
+ */
4370
+ _revisionOf(key) {
4371
+ return _revisionOf(this.store, key, this.getServerRevisionFromState(this.state, key));
4372
+ }
4373
+ _clearedError() {
4374
+ return kissAbort('The internal action props were cleared, so the action stopped syncing.');
4375
+ }
4376
+ _applyState(newState) {
4377
+ this.dispatch(new UpdateStateAction(() => newState));
4378
+ }
4379
+ /**
4380
+ * For Kiss internal use only.
4381
+ * @internal
4382
+ */
4383
+ _injectStore(_store) {
4384
+ super._injectStore(_store);
4385
+ _checkIncompatibleFeatures(this, 'an OptimisticSyncWithPush', false);
4386
+ }
4387
+ }
4388
+ /**
4389
+ * The revision kept in the store for the given key, where the server revision is the newest of
4390
+ * the one kept in the store, and the given one (which comes from the state).
4391
+ */
4392
+ function _revisionOf(store, key, serverRevisionFromState) {
4393
+ const kept = store._getOptimisticSyncRevision(key);
4394
+ return {
4395
+ localRevision: kept?.localRevision ?? 0,
4396
+ serverRevision: Math.max(kept?.serverRevision ?? -1, serverRevisionFromState),
4397
+ isPush: kept?.isPush ?? false,
4398
+ localValue: kept?.localValue,
4399
+ };
4400
+ }
4401
+ /**
4402
+ * The `ServerPush` abstract class is for actions that put in the store state the values that
4403
+ * were received by server push, through WebSockets, Server-Sent Events (SSE), Firebase, etc.
4404
+ *
4405
+ * It works together with `OptimisticSyncWithPush`, to make sure out-of-order pushes don't
4406
+ * corrupt the state, and that local optimistic updates are not overwritten by stale pushes.
4407
+ *
4408
+ * ## How it works
4409
+ *
4410
+ * Each push comes with its `PushMetadata` (the server revision, and the local-revision and
4411
+ * device ID that were sent by the device that changed the value). When the action is
4412
+ * dispatched:
4413
+ *
4414
+ * 1. If the push is not newer than the newest known server revision for the key (considering
4415
+ * both the revision kept by Kiss, and `getServerRevisionFromState()`), it's stale or out of
4416
+ * order, so it's ignored.
4417
+ *
4418
+ * 2. If the push is the echo of an older request of this same device (the user changed the
4419
+ * value again after that request was sent), it's not applied, since the state already has a
4420
+ * newer local value. Its server revision is still recorded, but it doesn't count as a push,
4421
+ * so the newer local value is still sent in a follow-up request.
4422
+ *
4423
+ * 3. Otherwise (a push from another device, or the echo of the latest request of this device),
4424
+ * it's applied with `applyServerPushToState`, and recorded as the latest change of the key.
4425
+ * Then, the `OptimisticSyncWithPush` request in flight for that key doesn't send a follow-up
4426
+ * request when it finishes, since the push already came from the server.
4427
+ *
4428
+ * ## How to use it
4429
+ *
4430
+ * Extend `ServerPush` instead of your base action, and DO NOT implement `reduce()`. Instead,
4431
+ * you must provide:
4432
+ *
4433
+ * - `associatedAction()` returns the `OptimisticSyncWithPush` class that controls the value.
4434
+ * - `pushMetadata()` returns the `PushMetadata` that came with the push.
4435
+ * - `applyServerPushToState(state, key, serverRevision)` applies the pushed value, and the
4436
+ * server revision, to the state.
4437
+ * - `getServerRevisionFromState(state, key)` reads the server revision saved in the state, or
4438
+ * returns `-1`.
4439
+ *
4440
+ * And optionally, `optimisticSyncKeyParams()`, which must return the same as the one of the
4441
+ * associated action.
4442
+ *
4443
+ * ```ts
4444
+ * class PushLikeUpdate extends ServerPush<State> {
4445
+ * constructor(readonly itemId: string, readonly liked: boolean, readonly metadata: PushMetadata) {
4446
+ * super();
4447
+ * }
4448
+ *
4449
+ * associatedAction() { return ToggleLike; }
4450
+ * optimisticSyncKeyParams() { return this.itemId; }
4451
+ * pushMetadata() { return this.metadata; }
4452
+ *
4453
+ * applyServerPushToState(state: State, key: any, serverRevision: number) {
4454
+ * return state.setLiked(this.itemId, this.liked).setRevision(key, serverRevision);
4455
+ * }
4456
+ *
4457
+ * getServerRevisionFromState(state: State, key: any) { return state.revisionOf(key) ?? -1; }
4458
+ * }
4459
+ *
4460
+ * // When the server pushes a change:
4461
+ * socket.on('like', (msg) => store.dispatch(new PushLikeUpdate(msg.itemId, msg.liked, {
4462
+ * serverRevision: msg.serverRevision,
4463
+ * localRevision: msg.localRevision,
4464
+ * deviceId: msg.deviceId,
4465
+ * })));
4466
+ * ```
4467
+ *
4468
+ * To reset the revisions shared with `OptimisticSyncWithPush` (for example, on logout), call
4469
+ * `store.clearInternalActionProps()`, which is also called by `store.setShutDown(true)`. The
4470
+ * server revisions you saved in the state are kept, and still used.
4471
+ *
4472
+ * Notes:
4473
+ * - This class should be used alone. It can't be combined with any other feature: dispatching
4474
+ * it with `checkInternet`, `nonReentrant`, `retry`, `unlimitedRetryCheckInternet`, `debounce`,
4475
+ * `throttle`, `fresh`, `ignoreOld`, `sequential` or polling throws a `StoreException`.
4476
+ * - In particular, it should not be combined with `sequential`. Pushed values must be applied to
4477
+ * the state as soon as they arrive, and `sequential` would delay them behind unrelated queued
4478
+ * actions. Worse, a push is also what tells an in-flight `OptimisticSyncWithPush` request that
4479
+ * no follow-up is needed, and that signal would arrive too late.
4480
+ * - Use it in a separate action from `OptimisticSyncWithPush`, which can't apply pushes itself.
4481
+ */
4482
+ export class ServerPush extends KissAction {
4483
+ /**
4484
+ * Same meaning as in `OptimisticSyncWithPush`: the params that differentiate the keys. It
4485
+ * must return the same as the `optimisticSyncKeyParams()` of the associated action. For
4486
+ * example, if each item has its own key:
4487
+ *
4488
+ * ```ts
4489
+ * optimisticSyncKeyParams() { return this.itemId; }
4490
+ * ```
4491
+ */
4492
+ optimisticSyncKeyParams() {
4493
+ return null;
4494
+ }
4495
+ /**
4496
+ * Must compute the same key as the `computeOptimisticSyncKey()` of the associated
4497
+ * `OptimisticSyncWithPush` action. By default, it combines `associatedAction()` with
4498
+ * `optimisticSyncKeyParams()`.
4499
+ */
4500
+ computeOptimisticSyncKey() {
4501
+ return [this.associatedAction(), this.optimisticSyncKeyParams()];
4502
+ }
4503
+ /**
4504
+ * Do NOT override this method. Implement `associatedAction`, `pushMetadata`,
4505
+ * `applyServerPushToState` and `getServerRevisionFromState` instead.
4506
+ */
4507
+ reduce() {
4508
+ const key = this.computeOptimisticSyncKey();
4509
+ const { serverRevision, localRevision, deviceId } = this.pushMetadata();
4510
+ // A non-finite revision would be recorded as the newest known one, and then no other push or
4511
+ // response could be compared with it.
4512
+ if (typeof serverRevision !== 'number' || !Number.isFinite(serverRevision))
4513
+ throw new StoreException(`Action ${this.constructor.name} pushed an invalid server revision: ` +
4514
+ `it must be a finite number, but got ${String(serverRevision)}.`);
4515
+ const known = _revisionOf(this.store, key, this.getServerRevisionFromState(this.state, key));
4516
+ // Ignores stale and out-of-order pushes.
4517
+ if (serverRevision <= known.serverRevision)
4518
+ return null;
4519
+ const isSelf = (deviceId === OptimisticSyncWithPush.deviceId());
4520
+ // The echo of an older request of this device: the state already has a newer local value.
4521
+ // So, it only records the server revision. It does NOT apply the push, and does NOT count
4522
+ // as a push, since then the newer local value would not be sent in a follow-up request.
4523
+ if (isSelf && (localRevision < known.localRevision)) {
4524
+ this.store._setOptimisticSyncRevision(key, { ...known, serverRevision, isPush: false });
4525
+ return null;
4526
+ }
4527
+ // Safe to apply (a push from another device, or the echo of the latest local value).
4528
+ const newState = this.applyServerPushToState(this.state, key, serverRevision);
4529
+ // Always records the newest known server revision, even if the push is ignored by
4530
+ // `applyServerPushToState` (which returned null). But an ignored push doesn't change the
4531
+ // state, so it doesn't count as a push: otherwise, a newer local change would not be sent
4532
+ // in a follow-up request.
4533
+ this.store._setOptimisticSyncRevision(key, {
4534
+ ...known,
4535
+ localRevision: isSelf ? Math.max(known.localRevision, localRevision) : known.localRevision,
4536
+ serverRevision,
4537
+ isPush: (newState === null) ? known.isPush : true,
4538
+ });
4539
+ return newState;
4540
+ }
4541
+ /**
4542
+ * For Kiss internal use only.
4543
+ * @internal
4544
+ */
4545
+ _injectStore(_store) {
4546
+ super._injectStore(_store);
4547
+ _checkIncompatibleFeatures(this, 'a ServerPush', true);
4548
+ }
4549
+ }
4550
+ /**
4551
+ * Throws a `StoreException` if the given action, which is described by `description` (for
4552
+ * example, "an OptimisticSync"), uses a feature it can't use. It can only use `checkInternet`,
4553
+ * unless `noCheckInternet` is true, in which case it can't use any feature.
4554
+ */
4555
+ function _checkIncompatibleFeatures(action, description, noCheckInternet) {
4556
+ const incompatible = (feature, isUsed) => {
4557
+ if (isUsed)
4558
+ throw new StoreException(`Action ${action.constructor.name} is ${description}, which can't use ${feature}. ` +
4559
+ `Remove its \`${feature === 'polling' ? 'poll' : feature}\` property.`);
4560
+ };
4561
+ if (noCheckInternet)
4562
+ incompatible('checkInternet', !!action.checkInternet);
4563
+ incompatible('nonReentrant', action.nonReentrant);
4564
+ incompatible('ignoreOld', action.ignoreOld);
4565
+ incompatible('unlimitedRetryCheckInternet', action._isUnlimitedRetryCheckInternet);
4566
+ incompatible('retry', action.ifRetryIsOn);
4567
+ incompatible('debounce', action._debounceMillis !== null);
4568
+ incompatible('throttle', action._throttleMillis !== null);
4569
+ incompatible('fresh', action._freshMillis !== null);
4570
+ incompatible('sequential', action.sequential);
4571
+ incompatible('polling', action.poll !== undefined);
4572
+ }
4573
+ /** @internal */
4574
+ export function _isSameNonReentrantKey(a, b) {
4575
+ if (Object.is(a, b))
4576
+ return true;
4577
+ if (Array.isArray(a) && Array.isArray(b))
4578
+ return a.length === b.length && a.every((value, i) => _isSameNonReentrantKey(value, b[i]));
4579
+ if (isPlainObject(a) && isPlainObject(b)) {
4580
+ const keysA = Object.keys(a);
4581
+ const keysB = Object.keys(b);
4582
+ return keysA.length === keysB.length &&
4583
+ keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && _isSameNonReentrantKey(a[key], b[key]));
4584
+ }
4585
+ return false;
4586
+ }
4587
+ /**
4588
+ * The `UpdateStateAction` replaces all the store state, synchronously,
4589
+ * using the given `stateUpdateFunction`.
4590
+ *
4591
+ * By default, `ifPersists` is true, which means the persistor may persist
4592
+ * the state change.
4593
+ *
4594
+ * However, if `ifPersists` is false, the persistor will ignore this state change,
4595
+ * and won't persist the state change. This is useful when you read some state from
4596
+ * the local persistence (the device disk) and you don't want to persist it again.
4597
+ */
4598
+ export class UpdateStateAction extends KissAction {
4599
+ updateFunction;
4600
+ ifPersists;
4601
+ constructor(updateFunction, ifPersists = true) {
4602
+ super();
4603
+ this.updateFunction = updateFunction;
4604
+ this.ifPersists = ifPersists;
4605
+ }
4606
+ reduce() {
4607
+ return this.updateFunction(this.state);
4608
+ }
4609
+ toString() {
4610
+ return `${this.constructor.name}(state)`;
4611
+ }
4612
+ }
4613
+ /**
4614
+ * Merges a slice of state loaded on the server into the store state, synchronously. It's
4615
+ * dispatched by `store.mergeServerState(slice)`, and by the `StoreSlice` component, which
4616
+ * gives each route of a server-rendered app its own server-loaded data. See "Server-side
4617
+ * rendering" in the README.
4618
+ *
4619
+ * The merge is the `mergeServerState` option given to `createStore`, or, without it, a
4620
+ * shallow merge for plain-object states: `{ ...state, ...slice }`. When nothing changes, the
4621
+ * state is kept as is (same reference), so that nothing is published.
4622
+ *
4623
+ * The persistor may persist the merged state, like any other state change.
4624
+ */
4625
+ export class MergeServerStateAction extends KissAction {
4626
+ slice;
4627
+ constructor(slice) {
4628
+ super();
4629
+ this.slice = slice;
4630
+ }
4631
+ reduce() {
4632
+ return this.store._mergeSlice(this.state, this.slice);
4633
+ }
4634
+ toString() {
4635
+ const keys = isPlainObject(this.slice) ? Object.keys(this.slice).join(', ') : 'slice';
4636
+ return `${this.constructor.name}(${keys})`;
4637
+ }
4638
+ }
4639
+ /** The `UserException` is a special type of error that Kiss automatically
4640
+ * catches and shows to the user in a dialog, or other UI of your choice.
4641
+ *
4642
+ * For this to work, you must throw the `UserException` from inside an action's
4643
+ * `before()` or `reduce()` functions. Only then, Kiss will be able to
4644
+ * catch the exception and show it to the user.
4645
+ *
4646
+ * However, if you are **not** inside an action, but you still want to show an
4647
+ * error dialog to the user, you may use the provided `UserExceptionAction`.
4648
+ *
4649
+ * ```ts
4650
+ * dispatch(new UserExceptionAction('Please enter a valid number'));
4651
+ * ```
4652
+ *
4653
+ * This action simply throws a corresponding `UserException` from its
4654
+ * own `reduce()` function.
4655
+ *
4656
+ * The `UserExceptionAction` is also useful inside of actions themselves,
4657
+ * if you want to display an error dialog to the user, but you don't want
4658
+ * to interrupt the action by throwing an exception.
4659
+ *
4660
+ * For example, here an invalid number will show an error dialog to the user,
4661
+ * but the action will continue running and set the counter state to `0`:
4662
+ *
4663
+ * ```ts
4664
+ * class ConvertAction extends Action {
4665
+ * constructor(private text: string) { super(); }
4666
+ *
4667
+ * reduce() {
4668
+ * let value = parseInt(this.text);
4669
+ *
4670
+ * if (isNaN(value)) {
4671
+ * this.dispatch(new UserExceptionAction('Please enter a valid number'));
4672
+ * value = 0;
4673
+ * }
4674
+ *
4675
+ * return { counter: value };
4676
+ * }
4677
+ * }
4678
+ * ```
4679
+ */
4680
+ export class UserExceptionAction extends KissAction {
4681
+ message;
4682
+ constructor(message) {
4683
+ super();
4684
+ this.message = message;
4685
+ }
4686
+ reduce() {
4687
+ throw new UserException(this.message);
4688
+ }
4689
+ }