kiss-for-react 1.1.0 → 2.0.1

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