kiss-for-react 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +699 -156
  2. package/lib/cjs/ClassPersistor.js +177 -112
  3. package/lib/cjs/Esserializer/DeserializationOptions.js +4 -4
  4. package/lib/cjs/Esserializer/SerializeOptions.js +4 -4
  5. package/lib/cjs/Esserializer/builtins.js +258 -0
  6. package/lib/cjs/Esserializer/constant.js +39 -131
  7. package/lib/cjs/Esserializer/deserializer.js +226 -313
  8. package/lib/cjs/Esserializer/general.js +91 -39
  9. package/lib/cjs/Esserializer/index.js +47 -43
  10. package/lib/cjs/Esserializer/serializer.js +168 -133
  11. package/lib/cjs/Evt.js +132 -0
  12. package/lib/cjs/Hooks.js +1472 -969
  13. package/lib/cjs/KissAction.js +4635 -1333
  14. package/lib/cjs/LoadPages.js +336 -0
  15. package/lib/cjs/Persistor.js +189 -120
  16. package/lib/cjs/ProcessPersistence.js +579 -262
  17. package/lib/cjs/Store.js +4278 -1534
  18. package/lib/cjs/StoreException.js +162 -75
  19. package/lib/cjs/StoreProvider.js +88 -0
  20. package/lib/cjs/UserException.js +212 -218
  21. package/lib/cjs/Wait.js +309 -309
  22. package/lib/cjs/index.js +69 -42
  23. package/lib/cjs/server.js +54 -0
  24. package/lib/cjs/types/ClassPersistor.d.ts +143 -112
  25. package/lib/cjs/types/ClassPersistor.d.ts.map +1 -1
  26. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +13 -6
  27. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  28. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +11 -5
  29. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  30. package/lib/cjs/types/Esserializer/builtins.d.ts +36 -0
  31. package/lib/cjs/types/Esserializer/builtins.d.ts.map +1 -0
  32. package/lib/cjs/types/Esserializer/constant.d.ts +25 -49
  33. package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -1
  34. package/lib/cjs/types/Esserializer/deserializer.d.ts +27 -17
  35. package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
  36. package/lib/cjs/types/Esserializer/general.d.ts +28 -4
  37. package/lib/cjs/types/Esserializer/general.d.ts.map +1 -1
  38. package/lib/cjs/types/Esserializer/index.d.ts +33 -29
  39. package/lib/cjs/types/Esserializer/index.d.ts.map +1 -1
  40. package/lib/cjs/types/Esserializer/serializer.d.ts +14 -3
  41. package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -1
  42. package/lib/cjs/types/Evt.d.ts +124 -0
  43. package/lib/cjs/types/Evt.d.ts.map +1 -0
  44. package/lib/cjs/types/Hooks.d.ts +1174 -837
  45. package/lib/cjs/types/Hooks.d.ts.map +1 -1
  46. package/lib/cjs/types/KissAction.d.ts +5199 -1398
  47. package/lib/cjs/types/KissAction.d.ts.map +1 -1
  48. package/lib/cjs/types/LoadPages.d.ts +287 -0
  49. package/lib/cjs/types/LoadPages.d.ts.map +1 -0
  50. package/lib/cjs/types/Persistor.d.ts +187 -118
  51. package/lib/cjs/types/Persistor.d.ts.map +1 -1
  52. package/lib/cjs/types/ProcessPersistence.d.ts +197 -99
  53. package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -1
  54. package/lib/cjs/types/Store.d.ts +2253 -1042
  55. package/lib/cjs/types/Store.d.ts.map +1 -1
  56. package/lib/cjs/types/StoreException.d.ts +97 -28
  57. package/lib/cjs/types/StoreException.d.ts.map +1 -1
  58. package/lib/cjs/types/StoreProvider.d.ts +80 -0
  59. package/lib/cjs/types/StoreProvider.d.ts.map +1 -0
  60. package/lib/cjs/types/UserException.d.ts +178 -169
  61. package/lib/cjs/types/UserException.d.ts.map +1 -1
  62. package/lib/cjs/types/index.d.ts +12 -9
  63. package/lib/cjs/types/index.d.ts.map +1 -1
  64. package/lib/cjs/types/server.d.ts +12 -0
  65. package/lib/cjs/types/server.d.ts.map +1 -0
  66. package/lib/cjs/types/utils.d.ts +15 -1
  67. package/lib/cjs/types/utils.d.ts.map +1 -1
  68. package/lib/cjs/utils.js +45 -7
  69. package/lib/esm/ClassPersistor.mjs +177 -0
  70. package/lib/esm/Esserializer/{DeserializationOptions.js → DeserializationOptions.mjs} +3 -3
  71. package/lib/esm/Esserializer/{SerializeOptions.js → SerializeOptions.mjs} +3 -3
  72. package/lib/esm/Esserializer/builtins.mjs +254 -0
  73. package/lib/esm/Esserializer/constant.mjs +28 -0
  74. package/lib/esm/Esserializer/deserializer.mjs +221 -0
  75. package/lib/esm/Esserializer/general.mjs +81 -0
  76. package/lib/esm/Esserializer/index.mjs +43 -0
  77. package/lib/esm/Esserializer/serializer.mjs +164 -0
  78. package/lib/esm/Evt.mjs +151 -0
  79. package/lib/esm/Hooks.mjs +1446 -0
  80. package/lib/esm/KissAction.mjs +4689 -0
  81. package/lib/esm/LoadPages.mjs +340 -0
  82. package/lib/esm/Persistor.mjs +180 -0
  83. package/lib/esm/ProcessPersistence.mjs +581 -0
  84. package/lib/esm/Store.mjs +4400 -0
  85. package/lib/esm/StoreException.mjs +153 -0
  86. package/lib/esm/StoreProvider.mjs +80 -0
  87. package/lib/esm/{UserException.js → UserException.mjs} +240 -246
  88. package/lib/esm/{Wait.js → Wait.mjs} +309 -309
  89. package/lib/esm/index.mjs +12 -9
  90. package/lib/esm/server.mjs +23 -0
  91. package/lib/esm/types/ClassPersistor.d.ts +143 -112
  92. package/lib/esm/types/ClassPersistor.d.ts.map +1 -1
  93. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +13 -6
  94. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  95. package/lib/esm/types/Esserializer/SerializeOptions.d.ts +11 -5
  96. package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  97. package/lib/esm/types/Esserializer/builtins.d.ts +36 -0
  98. package/lib/esm/types/Esserializer/builtins.d.ts.map +1 -0
  99. package/lib/esm/types/Esserializer/constant.d.ts +25 -49
  100. package/lib/esm/types/Esserializer/constant.d.ts.map +1 -1
  101. package/lib/esm/types/Esserializer/deserializer.d.ts +27 -17
  102. package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
  103. package/lib/esm/types/Esserializer/general.d.ts +28 -4
  104. package/lib/esm/types/Esserializer/general.d.ts.map +1 -1
  105. package/lib/esm/types/Esserializer/index.d.ts +33 -29
  106. package/lib/esm/types/Esserializer/index.d.ts.map +1 -1
  107. package/lib/esm/types/Esserializer/serializer.d.ts +14 -3
  108. package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -1
  109. package/lib/esm/types/Evt.d.ts +124 -0
  110. package/lib/esm/types/Evt.d.ts.map +1 -0
  111. package/lib/esm/types/Hooks.d.ts +1174 -837
  112. package/lib/esm/types/Hooks.d.ts.map +1 -1
  113. package/lib/esm/types/KissAction.d.ts +5199 -1398
  114. package/lib/esm/types/KissAction.d.ts.map +1 -1
  115. package/lib/esm/types/LoadPages.d.ts +287 -0
  116. package/lib/esm/types/LoadPages.d.ts.map +1 -0
  117. package/lib/esm/types/Persistor.d.ts +187 -118
  118. package/lib/esm/types/Persistor.d.ts.map +1 -1
  119. package/lib/esm/types/ProcessPersistence.d.ts +197 -99
  120. package/lib/esm/types/ProcessPersistence.d.ts.map +1 -1
  121. package/lib/esm/types/Store.d.ts +2253 -1042
  122. package/lib/esm/types/Store.d.ts.map +1 -1
  123. package/lib/esm/types/StoreException.d.ts +97 -28
  124. package/lib/esm/types/StoreException.d.ts.map +1 -1
  125. package/lib/esm/types/StoreProvider.d.ts +80 -0
  126. package/lib/esm/types/StoreProvider.d.ts.map +1 -0
  127. package/lib/esm/types/UserException.d.ts +178 -169
  128. package/lib/esm/types/UserException.d.ts.map +1 -1
  129. package/lib/esm/types/index.d.ts +12 -9
  130. package/lib/esm/types/index.d.ts.map +1 -1
  131. package/lib/esm/types/server.d.ts +12 -0
  132. package/lib/esm/types/server.d.ts.map +1 -0
  133. package/lib/esm/types/utils.d.ts +15 -1
  134. package/lib/esm/types/utils.d.ts.map +1 -1
  135. package/lib/esm/utils.mjs +38 -0
  136. package/package.json +54 -30
  137. package/lib/cjs/UnmodifiableSetView.js +0 -53
  138. package/lib/cjs/types/UnmodifiableSetView.d.ts +0 -24
  139. package/lib/cjs/types/UnmodifiableSetView.d.ts.map +0 -1
  140. package/lib/esm/ClassPersistor.js +0 -112
  141. package/lib/esm/Esserializer/constant.js +0 -81
  142. package/lib/esm/Esserializer/deserializer.js +0 -307
  143. package/lib/esm/Esserializer/general.js +0 -34
  144. package/lib/esm/Esserializer/index.js +0 -39
  145. package/lib/esm/Esserializer/serializer.js +0 -130
  146. package/lib/esm/Hooks.js +0 -955
  147. package/lib/esm/KissAction.js +0 -1459
  148. package/lib/esm/Persistor.js +0 -113
  149. package/lib/esm/ProcessPersistence.js +0 -262
  150. package/lib/esm/Store.js +0 -1606
  151. package/lib/esm/StoreException.js +0 -69
  152. package/lib/esm/UnmodifiableSetView.js +0 -50
  153. package/lib/esm/types/UnmodifiableSetView.d.ts +0 -24
  154. package/lib/esm/types/UnmodifiableSetView.d.ts.map +0 -1
  155. package/lib/esm/utils.js +0 -3
@@ -0,0 +1,4400 @@
1
+ import { UserException } from './UserException.mjs';
2
+ import { PersistAction } from './Persistor.mjs';
3
+ import { ActionStatus, MergeServerStateAction, OptimisticCommand, Poll, UpdateStateAction, _isSameNonReentrantKey, } from './KissAction.mjs';
4
+ import { ProcessPersistence } from './ProcessPersistence.mjs';
5
+ import { AbortDispatchException, isKissAbort, kissAbort, StoreException, TimeoutException } from './StoreException.mjs';
6
+ import { Evt } from './Evt.mjs';
7
+ import { capTimeoutMillis, describeValue, isPlainObject, MAX_TIMEOUT_MILLIS } from "./utils.mjs";
8
+ /**
9
+ * The store holds the state of the application and allows the state to be updated
10
+ * by dispatching actions. The store is also responsible for showing user exceptions
11
+ * to the user, persisting the state to the local device disk, processing wait states
12
+ * to show spinners while async operations are in progress, and more.
13
+ *
14
+ * You can create a store with `const store = createStore()` or `const store = new Store()`.
15
+ */
16
+ export function createStore(params) {
17
+ return new Store(params);
18
+ }
19
+ /**
20
+ * The listeners of one thing the store publishes (its state, the status of its actions, or its
21
+ * readiness). The hooks subscribe through React's `useSyncExternalStore`, which gives the store
22
+ * a plain callback. The store only tells the listeners that something may have changed. It
23
+ * doesn't know what each component selected: React reads the value again and compares it.
24
+ *
25
+ * Notifying iterates over a copy of the listeners taken when the notification starts:
26
+ * - A listener removed during the notification is not called (if it was not called yet).
27
+ * - A listener added during the notification is only called by the next notification.
28
+ * - A listener may dispatch, which notifies again, in a nested way, with the newest values.
29
+ */
30
+ class Listeners {
31
+ batch;
32
+ listeners = new Set();
33
+ constructor(batch) {
34
+ this.batch = batch;
35
+ }
36
+ add(listener) {
37
+ this.listeners.add(listener);
38
+ return () => {
39
+ this.listeners.delete(listener);
40
+ };
41
+ }
42
+ /** Calls the listeners now, or at the end of the current batch (see `NotificationBatch`). */
43
+ notify() {
44
+ if (this.listeners.size === 0)
45
+ return;
46
+ if (this.batch.depth > 0) {
47
+ this.batch.pending.add(this);
48
+ return;
49
+ }
50
+ for (const listener of Array.from(this.listeners)) {
51
+ if (this.listeners.has(listener))
52
+ listener();
53
+ }
54
+ }
55
+ }
56
+ /**
57
+ * Delays the notifications made during a synchronous dispatch until the dispatch finishes, so
58
+ * that they are published once, with the final values. For example, a SYNC action starts and
59
+ * finishes inside the same `dispatch` call: without the batch, the start would make React check
60
+ * the `useIsWaiting` components (and schedule a render for the ones whose action type just
61
+ * started), only to find the action already finished when it renders.
62
+ *
63
+ * The batch only covers the synchronous part of a dispatch. An ASYNC action publishes its start
64
+ * when `dispatch` returns, and its end when it finishes, outside any batch. The batch is never
65
+ * held across an `await`. Nested dispatches (from an observer, or `dispatchWhen`) are published
66
+ * together with the outer one, when it finishes. If anything throws, the batch still ends.
67
+ */
68
+ class NotificationBatch {
69
+ depth = 0;
70
+ pending = new Set();
71
+ run(fn) {
72
+ this.depth++;
73
+ try {
74
+ return fn();
75
+ }
76
+ finally {
77
+ this.depth--;
78
+ if (this.depth === 0 && this.pending.size > 0) {
79
+ const pending = Array.from(this.pending);
80
+ this.pending.clear();
81
+ for (const listeners of pending)
82
+ listeners.notify();
83
+ }
84
+ }
85
+ }
86
+ /**
87
+ * Like `run`, but instead of publishing the notifications when `fn` finishes, returns a
88
+ * function that publishes them, for the caller to call when it's safe. Used by `StoreSlice`,
89
+ * which changes the state while React renders it (where a notification would make React warn
90
+ * about updating other components during a render), and publishes after the commit. Inside
91
+ * another batch, the notifications are left to that batch, and the returned function does
92
+ * nothing.
93
+ */
94
+ suspend(fn) {
95
+ this.depth++;
96
+ try {
97
+ fn();
98
+ }
99
+ finally {
100
+ this.depth--;
101
+ }
102
+ if (this.depth > 0 || this.pending.size === 0)
103
+ return () => { };
104
+ const pending = Array.from(this.pending);
105
+ this.pending.clear();
106
+ return () => {
107
+ for (const listeners of pending)
108
+ listeners.notify();
109
+ };
110
+ }
111
+ }
112
+ /**
113
+ * One of the signals of the app the store publishes: whether the app is focused, or online
114
+ * (see `focusSource` and `onlineSource` in `ConstructorParams`). The value comes from a source,
115
+ * started lazily the first time the value is read or subscribed to, so that a store that never
116
+ * needs the signal (a server store, most tests) never listens to anything. The value is `true`
117
+ * until the source says otherwise.
118
+ *
119
+ * Tests set the value by hand with `set(boolean)`, which disconnects the source (otherwise a
120
+ * late start of the source could overwrite the value the test set). `set(null)` connects the
121
+ * source again. After `dispose()`, the source is stopped and never started again.
122
+ */
123
+ class AppSignal {
124
+ source;
125
+ listeners;
126
+ onStopError;
127
+ _value = true;
128
+ _isStarted = false;
129
+ _isManual = false;
130
+ _isDisposed = false;
131
+ _stopSource = undefined;
132
+ constructor(source, listeners, onStopError) {
133
+ this.source = source;
134
+ this.listeners = listeners;
135
+ this.onStopError = onStopError;
136
+ }
137
+ get value() {
138
+ this._start();
139
+ return this._value;
140
+ }
141
+ subscribe(listener) {
142
+ this._start();
143
+ return this.listeners.add(listener);
144
+ }
145
+ set(value) {
146
+ if (value === null) {
147
+ if (!this._isManual)
148
+ return;
149
+ this._isManual = false;
150
+ // Starts the source again, from the default value, and notifies once if the value
151
+ // changed, whether the source set it or not (where there is no source, it's `true` again).
152
+ const old = this._value;
153
+ this._value = true;
154
+ this._isSilent = true;
155
+ try {
156
+ this._start();
157
+ }
158
+ finally {
159
+ this._isSilent = false;
160
+ }
161
+ if (this._value !== old)
162
+ this.listeners.notify();
163
+ return;
164
+ }
165
+ this._isManual = true;
166
+ this._stop();
167
+ this._update(value);
168
+ }
169
+ // True while the source is started again by `set(null)`, so that `_update` doesn't notify.
170
+ _isSilent = false;
171
+ dispose() {
172
+ this._isDisposed = true;
173
+ this._stop();
174
+ }
175
+ _start() {
176
+ if (this._isStarted || this._isManual || this._isDisposed)
177
+ return;
178
+ this._isStarted = true;
179
+ this._stopSource = this.source((value) => {
180
+ if (this._isStarted)
181
+ this._update(value === true);
182
+ });
183
+ }
184
+ _stop() {
185
+ if (!this._isStarted)
186
+ return;
187
+ this._isStarted = false;
188
+ const stop = this._stopSource;
189
+ this._stopSource = undefined;
190
+ try {
191
+ stop?.();
192
+ }
193
+ catch (error) {
194
+ this.onStopError(error);
195
+ }
196
+ }
197
+ _update(value) {
198
+ if (value === this._value)
199
+ return;
200
+ this._value = value;
201
+ if (!this._isSilent)
202
+ this.listeners.notify();
203
+ }
204
+ }
205
+ // The default sources only touch the browser globals when they exist, so that the same code
206
+ // runs on the server, in Node and in React Native (which has `window` and `navigator`, but no
207
+ // `document` and no `navigator.onLine`).
208
+ /** The default `focusSource`: the document is visible. See `ConstructorParams.focusSource`. */
209
+ const defaultFocusSource = (setFocused) => {
210
+ const doc = (typeof document === 'undefined') ? undefined : document;
211
+ if (doc === undefined || typeof doc.addEventListener !== 'function')
212
+ return;
213
+ const update = () => setFocused(doc.visibilityState !== 'hidden');
214
+ update();
215
+ doc.addEventListener('visibilitychange', update);
216
+ return () => doc.removeEventListener('visibilitychange', update);
217
+ };
218
+ /** The default `onlineSource`: `navigator.onLine`. See `ConstructorParams.onlineSource`. */
219
+ const defaultOnlineSource = (setOnline) => {
220
+ const nav = (typeof navigator === 'undefined') ? undefined : navigator;
221
+ if (nav === undefined || typeof nav.onLine !== 'boolean')
222
+ return;
223
+ setOnline(nav.onLine);
224
+ const win = (typeof window === 'undefined') ? undefined : window;
225
+ if (win === undefined || typeof win.addEventListener !== 'function')
226
+ return;
227
+ const online = () => setOnline(true);
228
+ const offline = () => setOnline(false);
229
+ win.addEventListener('online', online);
230
+ win.addEventListener('offline', offline);
231
+ return () => {
232
+ win.removeEventListener('online', online);
233
+ win.removeEventListener('offline', offline);
234
+ };
235
+ };
236
+ // The source of a server store (see the `server` option): it never sets a value, so the app
237
+ // counts as focused and online.
238
+ const _noSource = () => { };
239
+ /**
240
+ * The store holds the state of the application and allows the state to be updated
241
+ * by dispatching actions. The store is also responsible for showing user exceptions
242
+ * to the user, persisting the state to the local device disk, processing wait states
243
+ * to show spinners while async operations are in progress, and more.
244
+ *
245
+ * You can create a store with `const store = createStore()` or `const store = new Store()`.
246
+ */
247
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
248
+ export class Store {
249
+ // Note: The lifecycle methods of the actions (like `before`, `reduce` and `after`) are
250
+ // protected, so that only the store calls them, when the action is dispatched. The store
251
+ // calls them as `action['before']()`, which TypeScript allows for protected members.
252
+ // The store publishes three separate things to React, each with its own listeners, so that a
253
+ // change in one of them doesn't make React check the components that use another:
254
+ // - The state: changed by `_registerState`.
255
+ // - The status of the actions (`isWaiting`, `isFailed`, `exceptionFor`): changed when an
256
+ // action starts, finishes or fails, and by `clearExceptionFor`.
257
+ // - The readiness (`_isReady`): changed once, when the persisted state finishes loading.
258
+ //
259
+ // The hooks give these to React's `useSyncExternalStore`: `_subscribeState` with `_getState`,
260
+ // `_subscribeStatus` with `isWaiting`/`isFailed`/`exceptionFor`, and `_subscribeReady` with
261
+ // `_getIsReady`. The store notifies the listeners AFTER all the values of a change are in
262
+ // place, so that a render sees them together (for example, the new state and the end of the
263
+ // waiting of the action that produced it). React decides when to render.
264
+ _notificationBatch = new NotificationBatch();
265
+ _stateListeners = new Listeners(this._notificationBatch);
266
+ _statusListeners = new Listeners(this._notificationBatch);
267
+ _readyListeners = new Listeners(this._notificationBatch);
268
+ /**
269
+ * Internal: subscribes to state changes. Used by `useSelect`, `useObject` and `useAllState`.
270
+ * The function is stable for the store, so React doesn't resubscribe on every render.
271
+ * @internal
272
+ */
273
+ _subscribeState = (listener) => this._stateListeners.add(listener);
274
+ /**
275
+ * Internal: subscribes to changes in the status of the actions. Used by `useIsWaiting`,
276
+ * `useIsFailed` and `useExceptionFor`.
277
+ * @internal
278
+ */
279
+ _subscribeStatus = (listener) => this._statusListeners.add(listener);
280
+ /** Internal: subscribes to the store becoming ready. Used by `useIsStoreReady`. @internal */
281
+ _subscribeReady = (listener) => this._readyListeners.add(listener);
282
+ /** Internal: returns the current state. The same as `store.state`, as a stable function. @internal */
283
+ _getState = () => this._state;
284
+ /** Internal: returns `_isReady`, as a stable function. @internal */
285
+ _getIsReady = () => this._isReady;
286
+ // The focus and online signals of the app (see `focusSource` and `onlineSource` in
287
+ // `ConstructorParams`). Each has its own listeners, like the state, the status and the
288
+ // readiness, so that a change in one doesn't make React check the components using the other.
289
+ _focusListeners = new Listeners(this._notificationBatch);
290
+ _onlineListeners = new Listeners(this._notificationBatch);
291
+ _focus;
292
+ _online;
293
+ /** Internal: subscribes to the focus signal. Used by `useIsFocused` and `useStoreEffect`. @internal */
294
+ _subscribeFocus = (listener) => this._focus.subscribe(listener);
295
+ /** Internal: subscribes to the online signal. Used by `useIsOnline` and `useStoreEffect`. @internal */
296
+ _subscribeOnline = (listener) => this._online.subscribe(listener);
297
+ /** Internal: returns `isFocused`, as a stable function. @internal */
298
+ _getIsFocused = () => this._focus.value;
299
+ /** Internal: returns `isOnline`, as a stable function. @internal */
300
+ _getIsOnline = () => this._online.value;
301
+ /**
302
+ * Whether the app is focused. In the browser, by default, this means the document is visible:
303
+ * the user is on the tab that shows the app, and the window is not minimized. Where the store
304
+ * can't know (the server, Node, React Native without a `focusSource`), it's always `true`.
305
+ * See `focusSource` in `createStore` to change where it comes from.
306
+ *
307
+ * In components, use `useIsFocused()`, or `useStoreEffect` with `onFocus` and `onBlur` to
308
+ * dispatch actions when the app is focused again (for example, to reload the data on screen).
309
+ *
310
+ * The first read starts listening to the source. In tests, set it with `setFocused`.
311
+ */
312
+ get isFocused() {
313
+ return this._focus.value;
314
+ }
315
+ /**
316
+ * Whether the app is online. In the browser, by default, it's `navigator.onLine`, which only
317
+ * says if there is a local network connection, not if the internet is reachable. Where the
318
+ * store can't know (the server, Node, React Native without an `onlineSource`), it's always
319
+ * `true`. See `onlineSource` in `createStore` to change where it comes from (for example,
320
+ * `NetInfo` in React Native, or a ping to your server).
321
+ *
322
+ * It's what the `checkInternet` and `unlimitedRetryCheckInternet` action features check by
323
+ * default (through the default `hasInternet()` of the actions). In components, use
324
+ * `useIsOnline()`, or `useStoreEffect` with `onOnline` and `onOffline` to dispatch actions
325
+ * when the internet comes back.
326
+ *
327
+ * The first read starts listening to the source. In tests, set it with `setOnline`.
328
+ */
329
+ get isOnline() {
330
+ return this._online.value;
331
+ }
332
+ /**
333
+ * Sets `isFocused` by hand, for tests. The store then stops listening to its `focusSource`,
334
+ * and only changes when you call this again. Pass `null` to listen to the source again:
335
+ *
336
+ * ```ts
337
+ * store.setFocused(false); // The user went to another tab.
338
+ * store.setFocused(true); // The user came back: `onFocus` callbacks run.
339
+ * ```
340
+ */
341
+ setFocused(isFocused) {
342
+ this._focus.set(isFocused);
343
+ }
344
+ /**
345
+ * Sets `isOnline` by hand, for tests. The store then stops listening to its `onlineSource`,
346
+ * and only changes when you call this again. Pass `null` to listen to the source again:
347
+ *
348
+ * ```ts
349
+ * store.setOnline(false); // The internet went down: `checkInternet` actions fail.
350
+ * store.setOnline(true); // It's back: `onOnline` callbacks run.
351
+ * ```
352
+ *
353
+ * See also `forceInternetOnOffSimulation`, which only affects the action features, and takes
354
+ * precedence over this for them.
355
+ */
356
+ setOnline(isOnline) {
357
+ this._online.set(isOnline);
358
+ }
359
+ /**
360
+ * Internal: the `initialState` passed to the constructor. It's the state the server rendered,
361
+ * and the state a client store hydrates with, unless `StoreProvider` is given a `serverState`.
362
+ * @internal
363
+ */
364
+ _initialState;
365
+ /**
366
+ * The `Store.log()` is a static function that Kiss uses internally to log information.
367
+ * If you want, you can also use it yourself, like this:
368
+ *
369
+ * ```ts
370
+ * Store.log('Some information: ' + someVariable);
371
+ * ```
372
+ *
373
+ * The log function is set during the creation of the store,
374
+ * using the `logger` constructor parameter. For example:
375
+ *
376
+ * ```ts
377
+ * const store = new Store<State>({
378
+ * initialState: new State(),
379
+ * logger: (obj) => process.stdout.write(obj + '\n'),
380
+ * });
381
+ * ```
382
+ *
383
+ * Or using a logger library:
384
+ *
385
+ * ```ts
386
+ * import { Logger } from 'my-logger-library';
387
+ *
388
+ * const store = new Store<State>({
389
+ * initialState: new State(),
390
+ * logger: (obj) => Logger.log(obj),
391
+ * });
392
+ * ```
393
+ *
394
+ * Note, if you don't define a logger yourself, the default is to print
395
+ * the log messages to the console with `console.log()`.
396
+ *
397
+ * This is how you may completely turn logging off:
398
+ *
399
+ * ```ts
400
+ * const store = new Store<State>({
401
+ * initialState: new State(),
402
+ * logger: null,
403
+ * });
404
+ * ```
405
+ *
406
+ * Setting the logger to `null` is better than using an empty function, because Kiss then
407
+ * skips building its log messages (for example, the description of each dispatched action).
408
+ */
409
+ static log;
410
+ // The logger used when the `logger` constructor parameter is `null`.
411
+ static _noLogger = (_obj) => { };
412
+ /**
413
+ * For Kiss internal use only. Logs the message returned by `buildMessage`, but only calls it
414
+ * when logging is turned on, so that no work is done to build messages that are discarded.
415
+ * @internal
416
+ */
417
+ static _logLazy(buildMessage) {
418
+ if (Store._isLogging())
419
+ Store.log(buildMessage());
420
+ }
421
+ // Returns false when the logger was set to `null`.
422
+ static _isLogging() {
423
+ return Store.log !== Store._noLogger;
424
+ }
425
+ _state;
426
+ // When true, no actions can be dispatched.
427
+ _shutDown = false;
428
+ /**
429
+ * Set this to `true` when you want to abort any new actions that are dispatched.
430
+ * Note this will not stop async actions already running, but you can wait for them to finish:
431
+ *
432
+ * ```ts
433
+ * await store.waitAllActions(null, {
434
+ * timeoutMillis: 5000,
435
+ * completeImmediately: true
436
+ * }).catch((error) => { });
437
+ * ```
438
+ *
439
+ * Set this back to `false` to restart the store accepting new action dispatches.
440
+ *
441
+ * Shutting down the store also calls `clearInternalActionProps()`, which, for example, stops
442
+ * all polling (see `KissAction.poll`), and stops the actions that retry. The polling and the
443
+ * retries are not restarted when you set this back to `false`.
444
+ */
445
+ setShutDown(shutDown) {
446
+ this._shutDown = shutDown;
447
+ if (shutDown)
448
+ this.clearInternalActionProps();
449
+ }
450
+ // How many `logOut` calls are running. While a logOut is running, no actions can be
451
+ // dispatched, but this is kept apart from `_shutDown`, so that a store shut down by the app,
452
+ // before or during logOut, stays shut down after it.
453
+ _logOutsRunning = 0;
454
+ // True only while `logOut` dispatches the action that changes the store state to the
455
+ // initial-state. That's the only dispatch allowed while a logOut is running, or while the
456
+ // store is shut down. It's set back to false as soon as that action starts (see
457
+ // `_processDispatch`), so that the actions dispatched while it runs (by the `stateObserver`,
458
+ // the `actionObserver`, or `dispatchWhen`) are not accepted.
459
+ _isApplyingLogOutState = false;
460
+ _isShutDown() {
461
+ if (this._isApplyingLogOutState)
462
+ return false;
463
+ return this._shutDown || this._disposed || (this._logOutsRunning > 0);
464
+ }
465
+ // How many times `clearInternalActionProps()` was called. An action dispatched before the last
466
+ // call stops retrying. See `KissAction._clearCountAtDispatch`.
467
+ _clearCount = 0;
468
+ // How many times `logOut()` was called. The result of an action dispatched before the last call
469
+ // is discarded, and so are the actions it dispatches. See `KissAction._logOutCountAtDispatch`.
470
+ _logOutCount = 0;
471
+ // True if a `logOut()` was called after the action was dispatched.
472
+ _wasDispatchedBeforeLogOut(action) {
473
+ return action._logOutCountAtDispatch !== this._logOutCount;
474
+ }
475
+ // The error of an action dispatched before a `logOut()`, when it finishes.
476
+ static _logOutDiscardError() {
477
+ return kissAbort('The action was dispatched before logOut, so its result was discarded.');
478
+ }
479
+ // Called when the reducer of the action finishes. If a `logOut()` was called after the action
480
+ // was dispatched, throws, so that the action is aborted, instead of changing the state of the
481
+ // next user.
482
+ _throwIfDispatchedBeforeLogOut(action) {
483
+ if (this._wasDispatchedBeforeLogOut(action))
484
+ throw Store._logOutDiscardError();
485
+ }
486
+ // Returns true (and logs it) if the action is being dispatched, with `this.dispatch` and
487
+ // similar, by an action that was dispatched before a `logOut()`. In this case the store
488
+ // doesn't accept it, since it belongs to the previous user.
489
+ _isDispatchedByActionBeforeLogOut(action) {
490
+ const parentCount = action._parentLogOutCount;
491
+ if (parentCount === null || parentCount === this._logOutCount)
492
+ return false;
493
+ Store._logLazy(() => `Can't dispatch action ${action} because it was dispatched by an action that was dispatched before logOut.`);
494
+ return true;
495
+ }
496
+ // The functions that end the waits of the actions waiting to retry. See `_waitRetryDelay`.
497
+ _retryWaitEnders = new Set();
498
+ // Ends the waits of all actions waiting to retry, which then abort.
499
+ _stopAllRetries() {
500
+ const enders = [...this._retryWaitEnders];
501
+ this._retryWaitEnders.clear();
502
+ for (const end of enders)
503
+ end();
504
+ }
505
+ // The error of an action that stopped retrying because `clearInternalActionProps()` was called.
506
+ static _clearedRetryError() {
507
+ return kissAbort('The internal action props were cleared, so the action stopped retrying.');
508
+ }
509
+ /**
510
+ * For Kiss internal use only.
511
+ * Returns true if `clearInternalActionProps()` was called (for example, by shutting down the
512
+ * store) after the action was dispatched, so that the action must stop retrying.
513
+ * @internal
514
+ */
515
+ _wereInternalActionPropsCleared(action) {
516
+ return action._clearCountAtDispatch !== this._clearCount;
517
+ }
518
+ /**
519
+ * For Kiss internal use only.
520
+ * Waits for the delay before the action retries. Throws an `AbortDispatchException` if
521
+ * `clearInternalActionProps()` was called (for example, by shutting down the store) after
522
+ * the action was dispatched, either before or during the wait, so that it stops retrying.
523
+ * Also throws it if the action uses `ignoreOld`, and became old, since the result of the
524
+ * retry would be ignored anyway.
525
+ * @internal
526
+ */
527
+ async _waitRetryDelay(action, delay) {
528
+ const throwIfMustStop = () => {
529
+ if (this._wereInternalActionPropsCleared(action))
530
+ throw Store._clearedRetryError();
531
+ if (action.isAborted)
532
+ throw this._abortError(action);
533
+ };
534
+ throwIfMustStop();
535
+ // The action stops waiting as soon as it's aborted.
536
+ const signal = action.abortSignal;
537
+ await new Promise(resolve => {
538
+ const end = () => {
539
+ clearTimeout(timer);
540
+ this._retryWaitEnders.delete(end);
541
+ signal.removeEventListener('abort', end);
542
+ resolve();
543
+ };
544
+ const timer = setTimeout(end, capTimeoutMillis(delay));
545
+ this._retryWaitEnders.add(end);
546
+ signal.addEventListener('abort', end);
547
+ });
548
+ throwIfMustStop();
549
+ }
550
+ /**
551
+ * Clears the information the store keeps for the action features, so that actions dispatched
552
+ * from now on behave as if no action had been dispatched before. This is useful during logout,
553
+ * to stop the effects of the actions of the previous user, and to make sure they don't
554
+ * affect the next user. It's also called when the store is shut down (see `setShutDown`).
555
+ *
556
+ * It does the following:
557
+ * - Removes all `fresh` keys, so the next dispatches run even if the data was still fresh.
558
+ * Otherwise, after logging in again, loading the new user's data could be aborted.
559
+ * - Removes all `throttle` locks, for the same reason.
560
+ * - Removes all `debounce` locks. Actions still waiting for their debounce period finish right
561
+ * away, without running their reducer.
562
+ * - Stops all polling (see `KissAction.poll`).
563
+ * - Discards the actions waiting in all `sequential` queues. They are aborted without running,
564
+ * like when a failed action discards its queue (see `discardQueueOnError()`). Actions
565
+ * dispatched from now on start new queues, and don't wait for the actions still running.
566
+ * - Stops the actions that retry, with `retry` or `unlimitedRetryCheckInternet`, so that they
567
+ * don't keep retrying for the previous user. An action waiting to retry is aborted right
568
+ * away, and an action running an attempt is aborted if that attempt fails (if it succeeds,
569
+ * it changes the state as usual). They are aborted with an `AbortDispatchException`, so they
570
+ * don't fail, and don't show errors. This also releases their non-reentrant keys. The same
571
+ * goes for an `OptimisticCommand` with `retry`, which then doesn't roll back its optimistic
572
+ * value, and doesn't reload.
573
+ * - Releases all `OptimisticSync` and `OptimisticSyncWithPush` keys, so the next dispatches
574
+ * send their own requests. An action whose request is in flight stops when that request
575
+ * finishes, without sending follow-up requests, and is aborted with an
576
+ * `AbortDispatchException`.
577
+ * - Removes the revisions that `OptimisticSyncWithPush` and `ServerPush` keep for each key.
578
+ * The server revisions you saved in the state are kept, and still used.
579
+ * - Forgets the `ignoreOld` keys. The actions dispatched from now on don't make the ones
580
+ * dispatched before old.
581
+ * - Clears the failures of all actions (see `clearAllExceptions()`), so that `isFailed` is
582
+ * `false` and `exceptionFor` is `null` for all action types. The new user doesn't see the
583
+ * errors of the previous one.
584
+ *
585
+ * Note:
586
+ * - Actions that are already running keep running, and still change the state when they
587
+ * finish. For example, an action that started loading the data of the previous user before
588
+ * the logout can still put that data into the state after the logout. To avoid that, use
589
+ * `logOut()`, which also discards the result of the actions dispatched before it.
590
+ * - It doesn't affect `nonReentrant` actions or `OptimisticCommand`s, since their keys belong to
591
+ * the actions that are running, and are released when those actions finish.
592
+ *
593
+ * Usage:
594
+ *
595
+ * ```ts
596
+ * class Logout extends KissAction<State> {
597
+ * reduce() {
598
+ * this.store.clearInternalActionProps();
599
+ * return State.initialState();
600
+ * }
601
+ * }
602
+ * ```
603
+ */
604
+ clearInternalActionProps() {
605
+ this._removeAllFreshKeys();
606
+ this._removeAllThrottleLocks();
607
+ this._removeAllDebounceLocks();
608
+ this._stopAllPolling();
609
+ this._discardAllSequentialQueues();
610
+ this._removeAllOptimisticSyncKeys();
611
+ this._clearCount++;
612
+ this._stopAllRetries();
613
+ this.clearAllExceptions();
614
+ }
615
+ /**
616
+ * If you are running tests, you can change `forceInternetOnOffSimulation` to simulate the
617
+ * internet connection as ON or OFF for all actions that use `checkInternet` or
618
+ * `unlimitedRetryCheckInternet`.
619
+ *
620
+ * - Return `true` if there IS internet.
621
+ * - Return `false` if there is NO internet.
622
+ * - Return `null` to use the real internet connection status (default).
623
+ *
624
+ * Example:
625
+ *
626
+ * ```ts
627
+ * store.forceInternetOnOffSimulation = () => false;
628
+ * ```
629
+ *
630
+ * This is specially useful during tests, for testing what happens when you have no internet
631
+ * connection. And since it's tied to the store, it automatically resets when the store is
632
+ * recreated.
633
+ *
634
+ * Note the simulation takes precedence over the action's `hasInternet()` method, even if you
635
+ * override it. To simulate the connection for a single action, override its
636
+ * `internetOnOffSimulation` getter instead.
637
+ */
638
+ forceInternetOnOffSimulation = () => null;
639
+ /**
640
+ * A queue of errors of type UserException, thrown by actions.
641
+ * They are shown to the user using the function `showUserException`.
642
+ * This is public if you need it for advanced stuff, but you should probably not touch it.
643
+ */
644
+ userExceptionsQueue;
645
+ /**
646
+ * If `true`, will use Store.log() to log all state changes.
647
+ * It uses `Store.describeStateChange()` to create the description of those changes.
648
+ *
649
+ * Note this is true (turned on) by default, as it may be useful for development, testing and
650
+ * debugging. Be sure to turn it off in production, as it may slow down your application:
651
+ *
652
+ * ```ts
653
+ * // In production
654
+ * const store = new Store<State>({
655
+ * initialState: new State(),
656
+ * logStateChanges: false,
657
+ * });
658
+ * ```
659
+ */
660
+ _logStateChanges;
661
+ /**
662
+ * The async actions that are currently being processed.
663
+ * Use `isWaiting` to know if an action is currently being processed.
664
+ */
665
+ _actionsInProgress;
666
+ /**
667
+ * The non-reentrant actions that are running, which hold their non-reentrant keys.
668
+ * Unlike `_actionsInProgress`, an action only leaves this set after its `after()` method
669
+ * runs, even if its state was already applied.
670
+ */
671
+ _nonReentrantActionsRunning;
672
+ /**
673
+ * The promises given to `useSuspense`, one per action type and `statusKey` that a suspended
674
+ * component waits for. The list is only filled when `useSuspense` is called while the action
675
+ * is in progress, and emptied as the actions finish, so a store whose components never call
676
+ * `useSuspense` keeps it empty, and only checks its size when an action finishes.
677
+ */
678
+ _suspenseWaits = [];
679
+ /**
680
+ * The failures of the actions that failed recently.
681
+ * When an action fails with any error (that was not swallowed, and is not an
682
+ * `AbortDispatchException`), its error is added here, indexed by the action type, together
683
+ * with the action's `statusKey`. Only the type, the key and the error are kept, not the action.
684
+ * A failure is removed when an action of the same type and `statusKey` is dispatched again,
685
+ * by `clearExceptionFor`, or by `clearAllExceptions` (which `clearInternalActionProps` calls).
686
+ *
687
+ * Use `isFailed`, `exceptionFor` and `clearExceptionFor` to know if you should display
688
+ * some error message due to an action failure.
689
+ *
690
+ * Note: Throwing an `UserException` can show a modal dialog to the user, and also show the error
691
+ * as a message in the UI. If you don't want to show the dialog you can use the `noDialog`
692
+ * getter in the error message: `throw new UserException('Invalid input').noDialog`.
693
+ */
694
+ _failedActions;
695
+ /**
696
+ * Helps implement the waitCondition method.
697
+ */
698
+ _waitConditions = [];
699
+ /**
700
+ * Helps implement the `dispatchWhen` method. One function for each `dispatchWhen` whose
701
+ * condition was met by the current state change, called when `_registerState` finishes.
702
+ * It checks the condition again, and dispatches the action if it's still met.
703
+ */
704
+ _dispatchWhenQueue = [];
705
+ /**
706
+ * Helps implement the `dispatchWhen` method. The functions that cancel the `dispatchWhen`s
707
+ * that are still waiting for their condition. See `_cancelAllDispatchWhen`.
708
+ */
709
+ _dispatchWhenCancels = new Set();
710
+ // Cancels all `dispatchWhen`s that are still waiting for their condition, or queued to be
711
+ // dispatched. Their actions are not dispatched, and their `onTimeout` is not called.
712
+ _cancelAllDispatchWhen() {
713
+ const cancels = [...this._dispatchWhenCancels];
714
+ this._dispatchWhenCancels.clear();
715
+ for (const cancel of cancels)
716
+ cancel();
717
+ this._dispatchWhenQueue = [];
718
+ }
719
+ // Rejects the `waitCondition`s and `waitActionCondition`s (which also serve `waitAllActions`,
720
+ // `waitActionType` etc.) that are still waiting, with an `AbortDispatchException`, and cancels
721
+ // their timeouts. Called by `dispose()`, after `_cancelAllDispatchWhen()` removed the
722
+ // `dispatchWhen` entries from `_waitConditions`, so that only real waits are left.
723
+ _abortAllWaits() {
724
+ const waits = [...this._waitConditions, ...this._waitActionConditions];
725
+ this._waitConditions = [];
726
+ this._waitActionConditions = [];
727
+ for (const wait of waits)
728
+ wait.reject(kissAbort('The store was disposed, so the wait was aborted.'));
729
+ }
730
+ /**
731
+ * Helps implement the `waitActionCondition` method.
732
+ */
733
+ _waitActionConditions = [];
734
+ // The `debounce` actions waiting for their debounce period, at most one per lock.
735
+ // Calling `cancel` makes the action finish without running its reducer.
736
+ _debounceLocks = [];
737
+ // The `throttle` locks, at most one per lock, with the instant their throttle period ends,
738
+ // and the action that took them. Expired locks are removed when checking or releasing locks.
739
+ _throttleLocks = [];
740
+ // The `fresh` keys, at most one per key, with the instant their fresh period ends, and the
741
+ // action that made them fresh. Expired keys are removed when checking or releasing keys.
742
+ _freshKeys = [];
743
+ // The `OptimisticSync` and `OptimisticSyncWithPush` keys with a request in flight, at most one
744
+ // per key, with the action that sends the requests for that key.
745
+ _optimisticSyncKeys = [];
746
+ // The revisions of the `OptimisticSyncWithPush` and `ServerPush` keys, at most one per key.
747
+ _optimisticSyncRevisions = [];
748
+ // The `sequential` queues, at most one per key, each with its actions in the order they will
749
+ // run. The first action of each queue is the one running. Each waiting action is released by
750
+ // the action that runs before it (with `false`), or by a failed action that discards the queue
751
+ // (with `true`). Empty queues are removed.
752
+ _sequentialQueues = [];
753
+ // The active polling cycles, at most one per polling key. A new cycle is created each time
754
+ // polling starts or restarts for a key, so that the ticks of a stopped or restarted cycle can
755
+ // tell they must not continue. While a tick is running (when `pollWaitsForRun` is true) the
756
+ // cycle has no timer, but polling is still active.
757
+ _pollingCycles = [];
758
+ // The errors thrown by `dispatchSync` when the action is ASYNC. See `_notSyncError`.
759
+ _notSyncErrors = new WeakSet();
760
+ /**
761
+ * Internal: the events (`Evt`) that `useEvent` or `useLayoutEvent` already handled (spent).
762
+ * They are kept here, and not in the events, so that the events, and the state, stay
763
+ * immutable. A `WeakSet`, so that events nobody references anymore are garbage collected.
764
+ * Use `isEventSpent` instead.
765
+ * @internal
766
+ */
767
+ _spentEvents = new WeakSet();
768
+ // The store props (see `setProp`), in the order they were set, and the `dispose` option of
769
+ // the ones that have one.
770
+ _props = new Map();
771
+ _propDisposers = new Map();
772
+ // True after `dispose()` was called. A disposed store doesn't accept actions or props.
773
+ _disposed = false;
774
+ // The environment, the configuration and the dependencies (see `ConstructorParams`). The
775
+ // last two are created by factories, in the constructor.
776
+ _environment;
777
+ _configuration;
778
+ _dependencies;
779
+ _processPersistence;
780
+ _dispatchCount = 0;
781
+ // A function that shows `UserExceptions` to the user, using some UI like a dialog or a toast.
782
+ // This function is passed to the constructor. If not passed, the `UserException` is ignored.
783
+ _showUserException;
784
+ // The `mergeServerState` option of the constructor. See `_mergeSlice`.
785
+ _mergeServerStateFn;
786
+ // The slices merged before the store was ready (the persistor still reading). The persisted
787
+ // state replaces the state when it arrives, and these are merged into it again, so that the
788
+ // server data of the route is not lost. Cleared when the store is ready.
789
+ _pendingServerSlices = [];
790
+ // True while `_mergeServerState` dispatches, so that the dispatch is allowed before the
791
+ // store is ready (like the persistor's own `UpdateStateAction`).
792
+ _applyingServerSlice = false;
793
+ _errorObserver;
794
+ _actionObserver;
795
+ _stateObserver;
796
+ /**
797
+ * You can use `store.mocks` to mock actions. You should use this for testing purposes, only.
798
+ *
799
+ * To mock actions and their reducers, use `store.mocks.add(actionType, mockFunction)`
800
+ * multiple times, one for each **action type** you want to mock.
801
+ *
802
+ * By adding mocks to the store, the `mockFunction` will be called
803
+ * to return a mocked action that will be used instead of the original actions, when dispatching.
804
+ * You can mock an action to return a specific state, to throw an error,
805
+ * or even to abort the action.
806
+ *
807
+ * Usage:
808
+ *
809
+ * - `store.mocks.add(actionType, (actionType) => mockAction)`:
810
+ * Adds a mock action to the store. Whenever an action of type `actionType` is
811
+ * dispatched, `mockAction` will be dispatched instead. If you pass `mockAction` as null,
812
+ * actions of type `actionType` will be ignored when dispatched.
813
+ *
814
+ * - `remove(actionType)`:
815
+ * Removes a mock action from the store. Note you should pass the
816
+ * type of the action that was mocked, and NOT the type of the mock.
817
+ *
818
+ * - `clear()`:
819
+ * Removes all mock actions from the store.
820
+ *
821
+ * Examples:
822
+ *
823
+ * ```ts
824
+ * // When an IncrementAction is dispatched, AddAction(1) will be dispatched instead.
825
+ * store.mocks.add(IncrementAction, (action) => new AddAction(1));
826
+ *
827
+ * // When an IncrementAction is dispatched, it will be ignored.
828
+ * store.mocks.add(IncrementAction, null);
829
+ *
830
+ * // Removes the mock for Increment.
831
+ * store.mocks.remove(IncrementAction);
832
+ *
833
+ * // Removes all mocks.
834
+ * store.mocks.clear();
835
+ *
836
+ * // When an AddAction is dispatched, the value will be subtracted instead.
837
+ * store.mocks.add(AddAction, (action) => new AddAction(-action.value));
838
+ * ```
839
+ */
840
+ mocks = new Mocks();
841
+ record = {
842
+ isRecording: false,
843
+ changes: [],
844
+ start: () => {
845
+ this.record.isRecording = true;
846
+ this.record.changes = [];
847
+ },
848
+ stop: () => {
849
+ this.record.isRecording = false;
850
+ },
851
+ result: () => {
852
+ return this.record.changes;
853
+ },
854
+ toString: () => {
855
+ let count = 0;
856
+ return '[\n' + this.record.changes.map(change => `${count++}. ` +
857
+ `${change.action.constructor.name} ${change.ini ? 'ini(' + change.dispatchCount + ')' : 'end'}: ` +
858
+ ((change.ini) ? change.prevState : `${change.prevState} → ${change.newState}`) +
859
+ `${change.error ? `, error: ${change.error}` : ''}`).join('\n') + '\n]';
860
+ }
861
+ };
862
+ // The default logger prints messages to the console.
863
+ // An alternative is: `const logger = (obj: any) => process.stdout.write(obj + '\n');`
864
+ _defaultLogger(obj) {
865
+ console.log(obj);
866
+ }
867
+ ;
868
+ // The default Ui just logs all user-exceptions and removes them from the queue.
869
+ _defaultShowUserException(exception, _count, next) {
870
+ Store._logLazy(() => `User got an exception: ${exception}`);
871
+ next();
872
+ }
873
+ ;
874
+ constructor({ initialState, environment, configuration, dependencies, showUserException, persistor, mergeServerState, errorObserver, actionObserver, stateObserver, logger, logStateChanges, focusSource, onlineSource, server, }) {
875
+ this._isServer = (server === true);
876
+ if (this._isServer && persistor !== undefined)
877
+ throw new StoreException('A server store must not have a persistor. The `server` option is for the store that ' +
878
+ 'loads the data of a request on the server, which has no local device to persist to. ' +
879
+ 'Give the persistor to the store the components use, in the browser.');
880
+ this._state = initialState;
881
+ // A server store never listens to the focus and online sources: the app counts as focused
882
+ // and online there.
883
+ this._focus = new AppSignal(this._isServer ? _noSource : (focusSource ?? defaultFocusSource), this._focusListeners, (error) => this._reportDisposeError(error, 'Stopping the focus source threw an error'));
884
+ this._online = new AppSignal(this._isServer ? _noSource : (onlineSource ?? defaultOnlineSource), this._onlineListeners, (error) => this._reportDisposeError(error, 'Stopping the online source threw an error'));
885
+ this._initialState = initialState;
886
+ this._environment = environment;
887
+ this._showUserException = showUserException || this._defaultShowUserException;
888
+ this._mergeServerStateFn = mergeServerState;
889
+ this._processPersistence = (persistor === undefined) ? null : new ProcessPersistence(persistor, initialState);
890
+ this._errorObserver = errorObserver;
891
+ this._actionObserver = actionObserver;
892
+ this._stateObserver = stateObserver;
893
+ this.userExceptionsQueue = [];
894
+ this._actionsInProgress = new Set();
895
+ this._nonReentrantActionsRunning = new Set();
896
+ this._failedActions = new Map();
897
+ Store.log = (logger === null) ? Store._noLogger : (logger || this._defaultLogger);
898
+ this._logStateChanges = logStateChanges ?? true;
899
+ // The configuration is created first, so that the dependencies factory can read it. Both
900
+ // are created before the persisted state is read, since the `errorObserver` may read them.
901
+ // If a factory throws, the store creation fails.
902
+ this._configuration = configuration?.(this);
903
+ this._dependencies = dependencies?.(this);
904
+ if (this._processPersistence != null) {
905
+ this._processPersistence.onError =
906
+ (error, originalError, observeOnly) => this._processPersistorError(error, originalError, observeOnly);
907
+ // Publishes the readiness as soon as it changes (the persisted state was read and applied,
908
+ // or the initial state was saved, or that failed and the store keeps the initial state).
909
+ this._processPersistence.onReady = () => {
910
+ this._pendingServerSlices = [];
911
+ this._readyListeners.notify();
912
+ };
913
+ this._processPersistence.readInitialState(this, initialState).catch(() => { });
914
+ }
915
+ this._ready = this._processPersistence?.ready() ?? Promise.resolve();
916
+ }
917
+ _ready;
918
+ /**
919
+ * Returns a promise that resolves when the store has finished everything it needs to do at
920
+ * startup. Currently, this means reading the persisted state (if there is a persistor) and
921
+ * putting it into the store. In the future, other startup work may be added here.
922
+ *
923
+ * While the store is not ready, its state is the `initialState` passed to the constructor.
924
+ * Your UI can show that state normally (for example, showing loading indicators where data
925
+ * is missing). However, you can't change the state before the store is ready, since it
926
+ * would be overwritten when the persisted state is loaded. Dispatching an action before the
927
+ * store is ready is a developer error, and throws a `StoreException`. So, you must wait for
928
+ * the store to be ready before dispatching any actions:
929
+ *
930
+ * ```ts
931
+ * const store = createStore<AppState>({
932
+ * initialState: AppState.initialState(),
933
+ * persistor: new MyPersistor(),
934
+ * });
935
+ *
936
+ * await store.ready();
937
+ * store.dispatch(new InitAppAction());
938
+ * ```
939
+ *
940
+ * The promise never rejects. If reading the persisted state fails, the error is reported
941
+ * (see `errorObserver`) and the store keeps the initial state. It always returns the same
942
+ * promise, so it can be called many times, and does not read the persisted state again.
943
+ * A store without a persistor is ready right away.
944
+ *
945
+ * In components, use `useIsStoreReady()` to know if the store is ready, for example to show
946
+ * a loading state, or to disable buttons that dispatch actions.
947
+ */
948
+ ready() {
949
+ return this._ready;
950
+ }
951
+ /**
952
+ * Internal: true if the store is ready (see `ready`). Used by `useIsStoreReady`.
953
+ * Don't use it in your code; use `useIsStoreReady` or `await store.ready()` instead.
954
+ * @internal
955
+ */
956
+ get _isReady() {
957
+ return this._processPersistence?.isReady ?? true;
958
+ }
959
+ get state() {
960
+ return this._state;
961
+ }
962
+ get dispatchCount() {
963
+ return this._dispatchCount;
964
+ }
965
+ /**
966
+ * Dispatches the action to the Redux store, to potentially change the state.
967
+ *
968
+ * If the action fails with an error that is not swallowed (see `dispatchAndWait`), a SYNC
969
+ * action throws the error from `dispatch`. An ASYNC action can't throw it, since `dispatch`
970
+ * already returned, so it becomes an unhandled promise rejection. To catch errors of async
971
+ * actions, use `dispatchAndWait` instead.
972
+ *
973
+ * An action can only be dispatched once. Dispatching an action that was already dispatched
974
+ * (running or finished) is a developer error, and throws a `StoreException`. Create a new
975
+ * action each time instead.
976
+ *
977
+ * Dispatching an action before the store is ready (see `ready`) also throws a `StoreException`.
978
+ *
979
+ * See also:
980
+ * - `dispatchAll` which dispatches all given actions in parallel.
981
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
982
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
983
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
984
+ */
985
+ dispatch(action) {
986
+ this._throwIfAlreadyDispatched(action);
987
+ this._throwIfNotReady(action);
988
+ if (this._isShutDown()) {
989
+ Store._logLazy(() => `Can't dispatch action ${action} because the store is shut down.`);
990
+ return;
991
+ }
992
+ if (this._isDispatchedByActionBeforeLogOut(action))
993
+ return;
994
+ const mockedActionOrAction = this._mockActionOrNot(action);
995
+ // 1) If mocked as `null`, the action is ignored.
996
+ if (mockedActionOrAction === null)
997
+ return; // If mocked as null, the action is ignored.
998
+ if (mockedActionOrAction !== action)
999
+ this._throwIfAlreadyDispatched(mockedActionOrAction);
1000
+ // 2) If the action wants to abort the dispatch, or is non-reentrant and already running, aborts.
1001
+ if (this._mustAbortDispatch(mockedActionOrAction))
1002
+ return;
1003
+ // 3) If the action is mocked to return another action, we dispatch the mock.
1004
+ this._processDispatch(mockedActionOrAction, false);
1005
+ }
1006
+ /**
1007
+ * Dispatches an action and returns a promise that resolves when the action finishes.
1008
+ * While the state change from the action's reducer will have been applied when the promise
1009
+ * resolves, other independent processes that the action may have started may still be in
1010
+ * progress.
1011
+ *
1012
+ * Usage: `await store.dispatchAndWait(new MyAction())`.
1013
+ *
1014
+ * If the action fails, the error is processed as usual (`wrapError`, `after`,
1015
+ * `errorObserver`, etc). If the error is swallowed (a `UserException`, or when
1016
+ * `wrapError` or the `errorObserver` returns `null`), the promise resolves
1017
+ * with the action status. Otherwise, the promise REJECTS with the error, for both sync and
1018
+ * async actions. So you can use `try { await dispatchAndWait(...) } catch` or `.catch()`.
1019
+ *
1020
+ * An action can only be dispatched once. Dispatching an action that was already dispatched
1021
+ * (running or finished) is a developer error: `dispatchAndWait` throws a `StoreException`
1022
+ * synchronously, instead of returning a rejected promise. A previous `dispatchAndWait` of
1023
+ * that same action is not affected.
1024
+ *
1025
+ * See also:
1026
+ * - `dispatch` which dispatches both sync and async actions.
1027
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
1028
+ * - `dispatchAll` which dispatches all given actions in parallel.
1029
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
1030
+ */
1031
+ dispatchAndWait(action) {
1032
+ this._throwIfAlreadyDispatched(action);
1033
+ this._throwIfNotReady(action);
1034
+ if (this._isShutDown()) {
1035
+ Store._logLazy(() => `Can't dispatch action ${action} because the store is shut down.`);
1036
+ return Promise.resolve(new ActionStatus({ isDispatchAborted: true }));
1037
+ }
1038
+ if (this._isDispatchedByActionBeforeLogOut(action))
1039
+ return Promise.resolve(new ActionStatus({ isDispatchAborted: true }));
1040
+ const mockedActionOrAction = this._mockActionOrNot(action);
1041
+ // 1) If mocked as `null`, the action is ignored.
1042
+ if (mockedActionOrAction === null)
1043
+ return Promise.resolve(new ActionStatus({ isDispatchAborted: true }));
1044
+ if (mockedActionOrAction !== action)
1045
+ this._throwIfAlreadyDispatched(mockedActionOrAction);
1046
+ // 2) If the action wants to abort the dispatch, or is non-reentrant and already running, aborts.
1047
+ // If the action is misconfigured, we return a rejected promise (instead of throwing).
1048
+ let mustAbort;
1049
+ try {
1050
+ mustAbort = this._mustAbortDispatch(mockedActionOrAction);
1051
+ }
1052
+ catch (error) {
1053
+ return Promise.reject(error);
1054
+ }
1055
+ if (mustAbort)
1056
+ return Promise.resolve(new ActionStatus({ isDispatchAborted: true }));
1057
+ // 3) If the action is mocked to return another action, we dispatch the mock.
1058
+ const promise = mockedActionOrAction._createPromise();
1059
+ try {
1060
+ this._processDispatch(mockedActionOrAction, false);
1061
+ }
1062
+ catch (error) {
1063
+ // A sync action failed with an error that was not swallowed. We return a rejected
1064
+ // promise (instead of throwing), so that both `await` and `.catch()` can handle it.
1065
+ return Promise.reject(error);
1066
+ }
1067
+ return promise;
1068
+ }
1069
+ /**
1070
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
1071
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
1072
+ * ALL actions finish.
1073
+ *
1074
+ * ```ts
1075
+ * let actions = await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
1076
+ * ```
1077
+ *
1078
+ * Note this is exactly the same as doing:
1079
+ *
1080
+ * ```ts
1081
+ * let action1 = new BuyAction('IBM');
1082
+ * let action2 = new SellAction('TSLA');
1083
+ * store.dispatch(action1);
1084
+ * store.dispatch(action2);
1085
+ * await store.waitAllActions([action1, action2], { completeImmediately: true });
1086
+ * let actions = [action1, action2];
1087
+ * ```
1088
+ *
1089
+ * Note: While the state change from the action's reducers will have been applied when the
1090
+ * Promise resolves, other independent processes that the action may have started may still
1091
+ * be in progress.
1092
+ *
1093
+ * If some actions fail with an error that is not swallowed (see `dispatchAndWait`), all
1094
+ * actions are still dispatched and allowed to finish. Only then the Promise rejects, with
1095
+ * the error of the first failed action in the list.
1096
+ *
1097
+ * This is also true when the dispatch of an action throws right away (for example, when the
1098
+ * action was already dispatched, or the store is not ready): the other actions are still
1099
+ * dispatched and allowed to finish, and that error counts as the error of that action.
1100
+ * Note `dispatchAndWaitAll` itself never throws, but returns a Promise that rejects.
1101
+ *
1102
+ * See also:
1103
+ * - `dispatch` which dispatches both sync and async actions.
1104
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
1105
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
1106
+ * - `dispatchAll` which dispatches all given actions in parallel.
1107
+ */
1108
+ async dispatchAndWaitAll(actions) {
1109
+ const promises = [];
1110
+ for (const action of actions) {
1111
+ // If the dispatch throws right away (for example, the action was already dispatched,
1112
+ // or the store is not ready), we keep its error as a rejected promise, in the action's
1113
+ // position, so that the other actions are still dispatched and awaited.
1114
+ try {
1115
+ promises.push(this.dispatchAndWait(action));
1116
+ }
1117
+ catch (error) {
1118
+ promises.push(Promise.reject(error));
1119
+ }
1120
+ }
1121
+ // All actions are dispatched and finish, even if some of them fail.
1122
+ // Then, if any failed with an error that was not swallowed, we throw the first one.
1123
+ const results = await Promise.allSettled(promises);
1124
+ for (const result of results) {
1125
+ if (result.status === 'rejected')
1126
+ throw result.reason;
1127
+ }
1128
+ return actions;
1129
+ }
1130
+ /**
1131
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
1132
+ * the store state. It returns the same list of actions, so that you can instantiate them
1133
+ * inline, but still get a list of them.
1134
+ *
1135
+ * ```ts
1136
+ * let actions = store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
1137
+ * ```
1138
+ *
1139
+ * See also:
1140
+ * - `dispatch` which dispatches both sync and async actions.
1141
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
1142
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
1143
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async. */
1144
+ dispatchAll(actions) {
1145
+ for (const action of actions) {
1146
+ this.dispatch(action);
1147
+ }
1148
+ return actions;
1149
+ }
1150
+ /**
1151
+ * Dispatches the given action to the Redux store, to potentially change the state.
1152
+ *
1153
+ * This is exactly the same as the regular `dispatch`, except for the fact it
1154
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
1155
+ * if any of its `reduce()` or `before()` methods return a Promise.
1156
+ *
1157
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
1158
+ * action is SYNC, which means the state gets changed right after the dispatch call.
1159
+ *
1160
+ * Like `dispatch`, it throws a `StoreException` if the action was already dispatched.
1161
+ *
1162
+ * The `StoreException` for an ASYNC action is always thrown. It's not given to the action's
1163
+ * `wrapError` or to the `errorObserver`, so they can't swallow it or convert it (for example,
1164
+ * into a `UserException`), and the action doesn't count as failed for `isFailed` and
1165
+ * `exceptionFor`. The action still finishes: its `after()` runs, and its status is
1166
+ * `isCompletedFailed`, with that `StoreException` as its error.
1167
+ *
1168
+ * Note Kiss can only know `before()` or `reduce()` is async after calling it. So, when
1169
+ * `dispatchSync` throws because of an async action, the async method has already started,
1170
+ * and any side effects it has will still happen. Its result is ignored (it never changes the
1171
+ * state), and its errors are only logged. If the action uses `retry`, it's not retried. With
1172
+ * `unlimitedRetryCheckInternet`, the reducer doesn't run at all, since `dispatchSync` throws
1173
+ * while the internet is being checked.
1174
+ *
1175
+ * See also:
1176
+ * - `dispatch` which dispatches both sync and async actions.
1177
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
1178
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
1179
+ * - `dispatchAll` which dispatches all given actions in parallel.
1180
+ */
1181
+ dispatchSync(action) {
1182
+ this._throwIfAlreadyDispatched(action);
1183
+ this._throwIfNotReady(action);
1184
+ if (this._isShutDown()) {
1185
+ Store._logLazy(() => `Can't dispatch action ${action} because the store is shut down.`);
1186
+ return;
1187
+ }
1188
+ if (this._isDispatchedByActionBeforeLogOut(action))
1189
+ return;
1190
+ const mockedActionOrAction = this._mockActionOrNot(action);
1191
+ // 1) If mocked as `null`, the action is ignored.
1192
+ if (mockedActionOrAction === null)
1193
+ return; // If mocked as null, the action is ignored.
1194
+ if (mockedActionOrAction !== action)
1195
+ this._throwIfAlreadyDispatched(mockedActionOrAction);
1196
+ // 2) If the action wants to abort the dispatch, or is non-reentrant and already running, aborts.
1197
+ if (this._mustAbortDispatch(mockedActionOrAction))
1198
+ return;
1199
+ // 3) If the action is mocked to return another action, we dispatch the mock.
1200
+ this._processDispatch(mockedActionOrAction, true);
1201
+ }
1202
+ // Dispatching an action before the store is ready is a developer error: the persisted state
1203
+ // is still being read, and when it's loaded it would overwrite (or race with) the action's
1204
+ // changes. The only exception is the store itself, applying the state it read.
1205
+ _throwIfNotReady(action) {
1206
+ const pp = this._processPersistence;
1207
+ if (pp !== null && !pp.isReady && !pp.isApplyingReadState && !this._applyingServerSlice)
1208
+ throw new StoreException(`Dispatched ${action} before the store is ready. ` +
1209
+ 'Wait for store.ready() before dispatching actions.');
1210
+ }
1211
+ // An action can only be dispatched once. Dispatching an action that was already dispatched
1212
+ // is a developer error, not an action failure: it counts as a dispatch, and throws a
1213
+ // `StoreException` right away (not a rejected promise). This is checked before anything
1214
+ // else, so it throws even if the action would now be aborted, or the store is shut down.
1215
+ // If the action is mocked, the mock is checked too. Note a mocked action is never marked
1216
+ // as dispatched (its mock is), so dispatching it again doesn't throw.
1217
+ _throwIfAlreadyDispatched(action) {
1218
+ if (!action.status.isDispatched)
1219
+ return;
1220
+ this._dispatchCount++;
1221
+ Store._logLazy(() => `${this._dispatchCount}) ${action}`);
1222
+ throw new StoreException('The action was already dispatched. Please, create a new action each time.');
1223
+ }
1224
+ // Returns true if the dispatch must be aborted: either `abortDispatch()` returns true, or the
1225
+ // action is non-reentrant and another action with the same non-reentrant key is already running,
1226
+ // or the action is inside the throttle period of another action with the same throttle lock,
1227
+ // or the data of another action with the same fresh-key is still fresh. A debounced action only
1228
+ // checks these keys when its debounce period ends (see `_mustAbortAfterDebounce`), since
1229
+ // otherwise the first dispatch would take the key, and abort the later ones that should replace it.
1230
+ // Note: It's up to the developer to make sure `abortDispatch`, `computeNonReentrantKey`,
1231
+ // `throttleLockBuilder`, `ignoreThrottle`, `computeFreshKey` and `ignoreFresh` don't throw
1232
+ // any errors. If they do, the error is logged and swallowed, and the dispatch is aborted.
1233
+ //
1234
+ // Before that, it injects the store into the action (so that the action may access the store
1235
+ // and the state in `abortDispatch()`), which throws a `StoreException` if the action is
1236
+ // misconfigured. This throws even if the dispatch would be aborted, so that the developer
1237
+ // error doesn't show up only sometimes.
1238
+ _mustAbortDispatch(action) {
1239
+ action._injectStore(this);
1240
+ // Set before `abortDispatch()` runs, since it may already dispatch other actions.
1241
+ action._logOutCountAtDispatch = this._logOutCount;
1242
+ try {
1243
+ if (action.isAborted)
1244
+ return true;
1245
+ if (action['abortDispatch']())
1246
+ return true;
1247
+ if (action._debounceMillis !== null)
1248
+ return false;
1249
+ return this._isBlockedByKey(action);
1250
+ }
1251
+ catch (error) {
1252
+ Store._logLazy(() => `Checking if '${action}' must abort its dispatch has thrown an error: ${error}.`);
1253
+ return true;
1254
+ }
1255
+ }
1256
+ // Called when the debounce period of the action ends, right before its reducer runs. Returns
1257
+ // true if the action must be aborted, because its non-reentrant key, throttle lock or fresh-key
1258
+ // is taken (see `_mustAbortDispatch`). Otherwise, the action takes its key. If computing the key
1259
+ // throws, the error is logged and swallowed, and the action is aborted.
1260
+ _mustAbortAfterDebounce(action) {
1261
+ try {
1262
+ if (this._isBlockedByKey(action))
1263
+ return true;
1264
+ }
1265
+ catch (error) {
1266
+ Store._logLazy(() => `Checking if '${action}' must abort after its debounce period has thrown an error: ${error}.`);
1267
+ return true;
1268
+ }
1269
+ if (Store._isNonReentrant(action))
1270
+ this._nonReentrantActionsRunning.add(action);
1271
+ return false;
1272
+ }
1273
+ // Returns true if the action is non-reentrant and its key is running, or if it's throttled, or
1274
+ // if its fresh-key is fresh. Otherwise, the throttled or fresh action takes its lock or key.
1275
+ // Note the non-reentrant key is only taken when the action starts running.
1276
+ _isBlockedByKey(action) {
1277
+ // Non-reentrant, throttle and fresh can't be combined (it throws when dispatched), so
1278
+ // an action only takes one of these keys.
1279
+ if (Store._isNonReentrant(action))
1280
+ return this._isNonReentrantKeyRunning(action);
1281
+ const throttleMillis = action._throttleMillis;
1282
+ if (throttleMillis !== null)
1283
+ return this._isThrottled(action, throttleMillis);
1284
+ const freshMillis = action._freshMillis;
1285
+ return (freshMillis !== null) && this._isFresh(action, freshMillis);
1286
+ }
1287
+ // `nonReentrant` actions, `OptimisticCommand`s and `unlimitedRetryCheckInternet` actions are
1288
+ // non-reentrant, and share the same keys.
1289
+ static _isNonReentrant(action) {
1290
+ return action.nonReentrant || action instanceof OptimisticCommand || action._isUnlimitedRetryCheckInternet;
1291
+ }
1292
+ // Returns true if a non-reentrant action with the same non-reentrant key as the given one is
1293
+ // in progress. Saves the key in the action, so that later dispatches can compare against it.
1294
+ // The key is released when the action finishes, after its `after()` method runs.
1295
+ _isNonReentrantKeyRunning(action) {
1296
+ const key = action['computeNonReentrantKey']();
1297
+ action._nonReentrantKey = key;
1298
+ for (const other of this._nonReentrantActionsRunning) {
1299
+ if (_isSameNonReentrantKey(other._nonReentrantKey, key))
1300
+ return true;
1301
+ }
1302
+ return false;
1303
+ }
1304
+ // Returns true if another action with the same throttle lock as the given one took the lock
1305
+ // less than its throttle period ago (unless the action wants to `ignoreThrottle`). Otherwise,
1306
+ // the given action takes the lock, starting a new throttle period.
1307
+ _isThrottled(action, throttleMillis) {
1308
+ const now = Date.now();
1309
+ this._removeExpiredThrottleLocks(now);
1310
+ const lock = action['throttleLockBuilder']();
1311
+ const index = this._throttleLocks.findIndex(entry => _isSameNonReentrantKey(entry.lock, lock));
1312
+ if (index !== -1) {
1313
+ if (!action.ignoreThrottle)
1314
+ return true;
1315
+ this._throttleLocks.splice(index, 1);
1316
+ }
1317
+ this._throttleLocks.push({ lock, expiresAt: now + throttleMillis, action });
1318
+ return false;
1319
+ }
1320
+ _removeExpiredThrottleLocks(now) {
1321
+ this._throttleLocks = this._throttleLocks.filter(entry => entry.expiresAt > now);
1322
+ }
1323
+ // Called when a throttled action finishes. If it failed and `removeThrottleLockOnError` is
1324
+ // true, removes the throttle lock it took (but not a newer one, taken by another action).
1325
+ _releaseThrottleLock(action) {
1326
+ if (action.removeThrottleLockOnError && (action.status.originalError !== null))
1327
+ this._throttleLocks = this._throttleLocks.filter(entry => entry.action !== action);
1328
+ this._removeExpiredThrottleLocks(Date.now());
1329
+ }
1330
+ /**
1331
+ * For Kiss internal use only. Use `removeThrottleLock()` in the action instead.
1332
+ * Removes the throttle lock with the given value, if any.
1333
+ * @internal
1334
+ */
1335
+ _removeThrottleLock(lock) {
1336
+ this._throttleLocks = this._throttleLocks.filter(entry => !_isSameNonReentrantKey(entry.lock, lock));
1337
+ }
1338
+ /**
1339
+ * For Kiss internal use only. Use `removeAllThrottleLocks()` in the action instead.
1340
+ * Removes all throttle locks.
1341
+ * @internal
1342
+ */
1343
+ _removeAllThrottleLocks() {
1344
+ this._throttleLocks = [];
1345
+ }
1346
+ // Returns true if another action with the same fresh-key made it fresh less than its fresh
1347
+ // period ago (unless the action wants to `ignoreFresh`). Otherwise, the given action makes
1348
+ // the key fresh, starting a new fresh period.
1349
+ _isFresh(action, freshMillis) {
1350
+ const now = Date.now();
1351
+ this._removeExpiredFreshKeys(now);
1352
+ const key = action['computeFreshKey']();
1353
+ const index = this._freshKeys.findIndex(entry => _isSameNonReentrantKey(entry.key, key));
1354
+ if (index !== -1) {
1355
+ if (!action.ignoreFresh)
1356
+ return true;
1357
+ this._freshKeys.splice(index, 1);
1358
+ }
1359
+ this._freshKeys.push({ key, expiresAt: now + freshMillis, action });
1360
+ return false;
1361
+ }
1362
+ _removeExpiredFreshKeys(now) {
1363
+ this._freshKeys = this._freshKeys.filter(entry => entry.expiresAt > now);
1364
+ }
1365
+ // Called when a fresh action finishes. If it failed (or was aborted), removes the fresh-key it
1366
+ // made fresh, so that the failure doesn't keep the key fresh. A newer fresh period, started by
1367
+ // another action with the same key, is kept. Note an action that ran had no fresh period to
1368
+ // restore: either the key was stale, or the action ignored it with `ignoreFresh`.
1369
+ _releaseFreshKey(action) {
1370
+ if (action.status.originalError !== null)
1371
+ this._freshKeys = this._freshKeys.filter(entry => entry.action !== action);
1372
+ this._removeExpiredFreshKeys(Date.now());
1373
+ }
1374
+ /**
1375
+ * For Kiss internal use only. Use `removeFreshKey()` in the action instead.
1376
+ * Removes the fresh-key with the given value, if any.
1377
+ * @internal
1378
+ */
1379
+ _removeFreshKey(key) {
1380
+ this._freshKeys = this._freshKeys.filter(entry => !_isSameNonReentrantKey(entry.key, key));
1381
+ }
1382
+ /**
1383
+ * For Kiss internal use only. Use `removeAllFreshKeys()` in the action instead.
1384
+ * Removes all fresh-keys.
1385
+ * @internal
1386
+ */
1387
+ _removeAllFreshKeys() {
1388
+ this._freshKeys = [];
1389
+ }
1390
+ /**
1391
+ * For Kiss internal use only.
1392
+ * If no other `OptimisticSync` or `OptimisticSyncWithPush` action has the given key, the given
1393
+ * action takes it, and this returns true. Otherwise, returns false.
1394
+ * @internal
1395
+ */
1396
+ _takeOptimisticSyncKey(key, action) {
1397
+ if (this._optimisticSyncKeys.some(entry => _isSameNonReentrantKey(entry.key, key)))
1398
+ return false;
1399
+ this._optimisticSyncKeys.push({ key, action });
1400
+ return true;
1401
+ }
1402
+ /**
1403
+ * For Kiss internal use only.
1404
+ * Returns true if the given `OptimisticSync` action has a key. It doesn't, after it released
1405
+ * it, or after `clearInternalActionProps()` removed all keys.
1406
+ * @internal
1407
+ */
1408
+ _hasOptimisticSyncKey(action) {
1409
+ return this._optimisticSyncKeys.some(entry => entry.action === action);
1410
+ }
1411
+ /**
1412
+ * For Kiss internal use only.
1413
+ * Releases the key of the given `OptimisticSync` action, if it has one. A key taken by
1414
+ * another action is kept.
1415
+ * @internal
1416
+ */
1417
+ _releaseOptimisticSyncKey(action) {
1418
+ this._optimisticSyncKeys = this._optimisticSyncKeys.filter(entry => entry.action !== action);
1419
+ }
1420
+ _removeAllOptimisticSyncKeys() {
1421
+ this._optimisticSyncKeys = [];
1422
+ this._optimisticSyncRevisions = [];
1423
+ }
1424
+ /**
1425
+ * For Kiss internal use only.
1426
+ * Returns the revision that `OptimisticSyncWithPush` and `ServerPush` keep for the given key,
1427
+ * or `undefined` if there is none.
1428
+ * @internal
1429
+ */
1430
+ _getOptimisticSyncRevision(key) {
1431
+ return this._optimisticSyncRevisions.find(entry => _isSameNonReentrantKey(entry.key, key))?.revision;
1432
+ }
1433
+ /**
1434
+ * For Kiss internal use only.
1435
+ * Sets the revision that `OptimisticSyncWithPush` and `ServerPush` keep for the given key.
1436
+ * @internal
1437
+ */
1438
+ _setOptimisticSyncRevision(key, revision) {
1439
+ const entry = this._optimisticSyncRevisions.find(entry => _isSameNonReentrantKey(entry.key, key));
1440
+ if (entry)
1441
+ entry.revision = revision;
1442
+ else
1443
+ this._optimisticSyncRevisions.push({ key, revision });
1444
+ }
1445
+ // Puts the sequential action at the end of the queue with its key. This runs synchronously
1446
+ // when the action is dispatched, which is what preserves the dispatch order. Returns a Promise
1447
+ // that resolves with `false` when it's the action's turn to run, or with `true` if the action
1448
+ // is discarded before that.
1449
+ _enterSequentialQueue(action) {
1450
+ const key = action['sequentialKeyParams']();
1451
+ let queue = this._sequentialQueues.find(entry => _isSameNonReentrantKey(entry.key, key));
1452
+ if (queue === undefined) {
1453
+ queue = { key, entries: [] };
1454
+ this._sequentialQueues.push(queue);
1455
+ }
1456
+ let release;
1457
+ const turn = new Promise(resolve => release = resolve);
1458
+ // If the queue is empty, it's already the action's turn.
1459
+ if (queue.entries.length === 0)
1460
+ release(false);
1461
+ else
1462
+ action._isWaitingInSequentialQueue = true;
1463
+ queue.entries.push({ action, release });
1464
+ return turn;
1465
+ }
1466
+ // When it's the turn of the sequential action, runs it from its `before` method. If the
1467
+ // action was discarded instead, it's aborted with an `AbortDispatchException`, without running
1468
+ // `before` and `reduce`.
1469
+ _runOnSequentialTurn(action, turn) {
1470
+ turn.then(discarded => {
1471
+ action._isWaitingInSequentialQueue = false;
1472
+ action._wasDiscardedFromSequentialQueue = discarded;
1473
+ const beforeResult = (async () => {
1474
+ if (discarded)
1475
+ throw kissAbort('Discarded from the sequential queue.');
1476
+ return action['before']();
1477
+ })();
1478
+ this._runAsyncBeforeOnwards(action, beforeResult).then();
1479
+ });
1480
+ }
1481
+ // Called when a sequential action finishes. Removes it from its queue, and lets the next
1482
+ // action in the queue run. Or, if the action failed and `discardQueueOnError()` returns true,
1483
+ // discards all the actions waiting behind it. Note a discarded action (or one that failed
1484
+ // before entering the queue) is not in any queue, so it doesn't release anything.
1485
+ _releaseSequentialQueue(action) {
1486
+ const index = this._sequentialQueues.findIndex(queue => queue.entries[0].action === action);
1487
+ if (index === -1)
1488
+ return;
1489
+ const queue = this._sequentialQueues[index];
1490
+ queue.entries.shift();
1491
+ let discard = false;
1492
+ const error = action.status.originalError;
1493
+ if (error !== null) {
1494
+ try {
1495
+ discard = action['discardQueueOnError'](error);
1496
+ }
1497
+ catch (thrownError) {
1498
+ Store._logLazy(() => `The discardQueueOnError() method of the action ${action} threw an error: ${thrownError}.`);
1499
+ }
1500
+ }
1501
+ if (discard) {
1502
+ for (const entry of queue.entries.splice(0))
1503
+ entry.release(true);
1504
+ }
1505
+ else if (queue.entries.length !== 0)
1506
+ queue.entries[0].release(false);
1507
+ // If the queue is now empty, remove its key, to prevent memory leaks.
1508
+ if (queue.entries.length === 0)
1509
+ this._sequentialQueues.splice(index, 1);
1510
+ }
1511
+ // Discards the actions waiting in all sequential queues, and removes the queues. The first
1512
+ // action of each queue is running, and keeps running. Since it's no longer in any queue, it
1513
+ // doesn't release anything when it finishes, and actions dispatched later don't wait for it.
1514
+ _discardAllSequentialQueues() {
1515
+ const queues = this._sequentialQueues;
1516
+ this._sequentialQueues = [];
1517
+ for (const queue of queues) {
1518
+ for (const entry of queue.entries.slice(1))
1519
+ entry.release(true);
1520
+ }
1521
+ }
1522
+ // Mocks an action to return another action.
1523
+ // If it returns null, the action should be ignored by the caller.
1524
+ // If no mock is defined, the original action is returned unchanged.
1525
+ _mockActionOrNot(action) {
1526
+ const mockActionFunction = this.mocks.get(action.constructor);
1527
+ // If no mock is defined, the original action is returned unchanged.
1528
+ if (mockActionFunction === undefined) {
1529
+ return action;
1530
+ }
1531
+ // If a mock is defined, we use it.
1532
+ else {
1533
+ const mockAction = mockActionFunction(action);
1534
+ // If the mock returns null, the action is ignored.
1535
+ if (mockAction === null) {
1536
+ Store._logLazy(() => `Dispatch of ${action} aborted by mock.`);
1537
+ return null;
1538
+ }
1539
+ // Otherwise, the mock is used.
1540
+ else {
1541
+ Store._logLazy(() => `Dispatch of ${action} mocked by ${mockAction}.`);
1542
+ return mockAction;
1543
+ }
1544
+ }
1545
+ }
1546
+ // Dispatches the action (or the already mocked action).
1547
+ // If `mustBeSync` is true, will throw a `StoreException` if the action is ASYNC.
1548
+ _processDispatch(action, mustBeSync) {
1549
+ if (this._isShutDown()) {
1550
+ Store._logLazy(() => `Can't dispatch action ${action} because the store is shut down.`);
1551
+ return;
1552
+ }
1553
+ // If this is the action of `logOut` that applies the initial-state, it's the only one allowed.
1554
+ this._isApplyingLogOutState = false;
1555
+ this._throwIfAlreadyDispatched(action);
1556
+ this._dispatchCount++;
1557
+ Store._logLazy(() => `${this._dispatchCount}) ${action}`);
1558
+ action._changeStatus({ isDispatched: true });
1559
+ action._clearCountAtDispatch = this._clearCount;
1560
+ // Note the store was already injected into the action by `_mustAbortDispatch`.
1561
+ // The action is dispatched twice. This is the 1st: when the action starts (ini true).
1562
+ this._observeAction(action, true);
1563
+ // If `record.isRecording`, record the INI state. That's for testing only.
1564
+ this._record(action, true, this._state, this._state, null);
1565
+ // The state and status changes made until `dispatch` returns are published together, when
1566
+ // it returns (see `NotificationBatch`). An ASYNC action publishes the rest when it finishes.
1567
+ this._notificationBatch.run(() => {
1568
+ this._calculateIsWaitingIsFailed(action);
1569
+ this._wraps(action, () => this._runFromStart(action, mustBeSync));
1570
+ });
1571
+ }
1572
+ /** @internal */
1573
+ _calculateIsWaitingIsFailed(action) {
1574
+ // Dispatch is starting, so we remove the failure of this action type and `statusKey`.
1575
+ // Otherwise, checking it later would show a stale error.
1576
+ this._removeFailure(action.constructor, action.statusKey);
1577
+ // Add the action to the list of actions in progress.
1578
+ // Note: We do this BEFORE notifying the UI, so that a single render sees both changes.
1579
+ // Otherwise, `isWaiting` would still see the action as not in progress.
1580
+ this._actionsInProgress.add(action);
1581
+ // A debounced action only takes its non-reentrant key when its debounce period ends.
1582
+ if (Store._isNonReentrant(action) && (action._debounceMillis === null))
1583
+ this._nonReentrantActionsRunning.add(action);
1584
+ // The action just entered the set of actions in progress, so we check the wait conditions.
1585
+ this._checkAllActionConditions(action);
1586
+ // Then we publish the status change. React checks only the components that use `isWaiting`,
1587
+ // `isFailed` or `exceptionFor`, and renders only those whose value changed. So a component
1588
+ // waiting for another action type, or a `useIsWaiting(Base)` that is already true, doesn't
1589
+ // render. Note a SYNC action also starts and finishes here, before `dispatch` returns, so
1590
+ // React never sees it as in progress.
1591
+ this._statusListeners.notify();
1592
+ }
1593
+ // Wraps SYNC actions.
1594
+ // - Runs the before are reduce methods.
1595
+ // - Runs the state observer.
1596
+ // - Catches and processes errors.
1597
+ // - Shows some UI if there are user exceptions.
1598
+ // - Makes sure the after method runs, always.
1599
+ // - Removes the wait state for the action in progress, always.
1600
+ // - Runs the action observer.
1601
+ _wraps(action, functionToRun) {
1602
+ let ifWentAsync = false;
1603
+ try {
1604
+ ifWentAsync = functionToRun();
1605
+ }
1606
+ catch (error) {
1607
+ this._processWrapsError(error, action);
1608
+ }
1609
+ finally {
1610
+ if (!ifWentAsync) {
1611
+ this._processWrapsFinally(action);
1612
+ }
1613
+ }
1614
+ }
1615
+ // Wraps ASYNC actions.
1616
+ // - Runs the before are reduce methods.
1617
+ // - Runs the state observer.
1618
+ // - Catches and processes errors.
1619
+ // - Shows some UI if there are user exceptions.
1620
+ // - Makes sure the after method runs, always.
1621
+ // - Removes the wait state for the action in progress, always.
1622
+ // - Runs the action observer.
1623
+ async _wrapsAsync(action, functionToRun) {
1624
+ let failure = null;
1625
+ try {
1626
+ await functionToRun();
1627
+ }
1628
+ catch (error) {
1629
+ try {
1630
+ this._processWrapsError(error, action);
1631
+ }
1632
+ catch (processedError) {
1633
+ // The error was not swallowed.
1634
+ failure = { error: processedError };
1635
+ }
1636
+ }
1637
+ finally {
1638
+ this._processWrapsFinally(action, failure);
1639
+ }
1640
+ // If the action was dispatched with `dispatchAndWait()`, its promise was rejected with the
1641
+ // error. Otherwise, nobody is waiting for the action, so the error becomes an unhandled
1642
+ // rejection (the same as an error thrown by any async code that is not awaited).
1643
+ if (failure !== null && !action._isAwaited()) {
1644
+ throw failure.error;
1645
+ }
1646
+ }
1647
+ _processWrapsError(error, action) {
1648
+ //
1649
+ // Throwing `null` or `undefined` (or rejecting with no reason) still means the action
1650
+ // failed. We turn it into an `Error`, since a `null` error means "no error" in the action's
1651
+ // status and in the `stateObserver`, and returning `null` from `wrapError` swallows it.
1652
+ if (error == null)
1653
+ error = Store._nullThrownError(action, error);
1654
+ //
1655
+ // The errors of an aborted action are ignored (by `ignoreOld`, when a newer action was
1656
+ // dispatched, or by `abort()`). This includes the error `fetch` rejects with when the
1657
+ // action's `abortSignal` is aborted, and an `AbortDispatchException` thrown by the action.
1658
+ // Errors that point to a bug (`StoreException`) are still thrown.
1659
+ if (action.isAborted && !isKissAbort(error) && !(error instanceof StoreException)) {
1660
+ Store._logLazy(() => `Ignored the error of ${action}, since it was aborted (${this._abortError(action).message}): ${error}`);
1661
+ error = this._abortError(action);
1662
+ }
1663
+ // The errors of an action dispatched before a `logOut()` are ignored, since they belong to
1664
+ // the previous user. Errors that point to a bug (`StoreException`) are still thrown.
1665
+ if (this._wasDispatchedBeforeLogOut(action) && !isKissAbort(error) && !(error instanceof StoreException)) {
1666
+ Store._logLazy(() => `Ignored the error of ${action}, since it was dispatched before logOut: ${error}`);
1667
+ error = Store._logOutDiscardError();
1668
+ }
1669
+ action._changeStatus({ originalError: error });
1670
+ // Observe the state with an error here. We use the current state; no new state was applied.
1671
+ // This is before the action's `after()` and `wrapError()` and the `errorObserver`.
1672
+ this._observeState(action, this._state, this._state, error);
1673
+ this._record(action, false, this._state, this._state, error);
1674
+ // When `dispatchSync` finds the action is ASYNC, that's a developer error, so `dispatchSync`
1675
+ // always throws it, like it throws when the action was already dispatched. It's not given to
1676
+ // `wrapError` or the `errorObserver`, since these could swallow it or turn it into a
1677
+ // `UserException`. And the action doesn't count as failed for `isFailed`/`exceptionFor`.
1678
+ if (this._notSyncErrors.has(error)) {
1679
+ action._changeStatus({ wrappedError: error });
1680
+ throw error;
1681
+ }
1682
+ // An `AbortDispatchException` created by Kiss itself (for example, for an `ignoreOld` action
1683
+ // that became old, or a `sequential` action discarded from its queue) aborts the action
1684
+ // silently. It's not processed by `wrapError` or the `errorObserver`, since it didn't come
1685
+ // from the user's code, and they could turn it into an error. See `_abortSilently`.
1686
+ if (isKissAbort(error)) {
1687
+ this._abortSilently(action);
1688
+ return;
1689
+ }
1690
+ // Any error may optionally be processed by the `wrapError` method of the action.
1691
+ // Usually this is used to wrap the error inside another that better describes the failed
1692
+ // action. It's recommended RETURNING the new error, but if `wrapError` throws an error,
1693
+ // that will be used too.
1694
+ try {
1695
+ error = action['wrapError'](error);
1696
+ }
1697
+ catch (thrownError) {
1698
+ error = thrownError;
1699
+ }
1700
+ // Returning `undefined` (or nothing) swallows the error, just like returning `null`.
1701
+ // The type of `wrapError` doesn't allow it, but it can still happen, for example in
1702
+ // JavaScript, or if the `wrapError` override is typed `any`.
1703
+ if (error === undefined)
1704
+ error = null;
1705
+ // Any error may optionally be processed by the `errorObserver` passed to the Store
1706
+ // constructor. It may log the error, change it, or swallow it by returning `null`. It's
1707
+ // recommended RETURNING the error, but if it throws an error, that will be used too.
1708
+ if (error !== null && this._errorObserver) {
1709
+ error = this._observeError(error, action.status.originalError, action);
1710
+ }
1711
+ // To completely disable the error, `wrapError` or `errorObserver` may return `null`.
1712
+ // But if we got an error, we deal with it here.
1713
+ if (error !== null) {
1714
+ // An `AbortDispatchException` thrown by the action (that `wrapError` and the
1715
+ // `errorObserver` didn't change), or returned by them, aborts the action silently.
1716
+ if (error instanceof AbortDispatchException) {
1717
+ this._abortSilently(action);
1718
+ return;
1719
+ }
1720
+ action._changeStatus({ wrappedError: error });
1721
+ // Memorizes the failure (type, `statusKey` and error). It's removed when an action of the
1722
+ // same type and key is dispatched again.
1723
+ this._addFailure(action.constructor, action.statusKey, error);
1724
+ // Memorizes errors of type `UserException` (in the error queue).
1725
+ // These errors are usually shown to the user in a modal dialog, and are not thrown.
1726
+ if (error instanceof UserException) {
1727
+ if (error.ifOpenDialog) {
1728
+ this._addUserException(error);
1729
+ this._openSomeUiToShowUserException();
1730
+ }
1731
+ }
1732
+ // Throws all other errors. This means the `dispatch()` method will throw this error.
1733
+ else
1734
+ throw error;
1735
+ }
1736
+ }
1737
+ /**
1738
+ * Aborts the action silently, because of an `AbortDispatchException`: the action doesn't
1739
+ * count as failed, nothing is thrown, and its status has no `wrappedError`.
1740
+ */
1741
+ _abortSilently(action) {
1742
+ action._changeStatus({ isDispatchAborted: true });
1743
+ }
1744
+ /**
1745
+ * Gives the error to the `errorObserver`, and returns the error it returns, or the error
1746
+ * it throws. Returns `null` if the error is meant to be swallowed. The `action` is `null` for
1747
+ * the errors of the `Persistor`.
1748
+ */
1749
+ _observeError(error, originalError, action) {
1750
+ let result;
1751
+ try {
1752
+ result = this._errorObserver({ error, originalError, action, store: this });
1753
+ }
1754
+ catch (thrownError) {
1755
+ result = thrownError;
1756
+ }
1757
+ // Returning `undefined` (or nothing) swallows the error, just like returning `null`.
1758
+ return (result === undefined) ? null : result;
1759
+ }
1760
+ _processWrapsFinally(action, failure = null) {
1761
+ // We run the `after` method of the action.
1762
+ const logAfterError = (error) => Store._logLazy(() => `The after() method of the action ${action} threw an error: ${error}.
1763
+ This error will be ignored, but you should fix this, as after() methods should not throw errors.`);
1764
+ try {
1765
+ // The `after()` method should be sync, but TypeScript lets it be overridden as `async`.
1766
+ // In that case, we catch its rejection, so that it doesn't become an unhandled rejection.
1767
+ const result = action['after']();
1768
+ if (result && typeof result.then === 'function') {
1769
+ result.then(undefined, logAfterError);
1770
+ }
1771
+ }
1772
+ catch (error) {
1773
+ logAfterError(error);
1774
+ }
1775
+ finally {
1776
+ action._changeStatus({ hasFinishedMethodAfter: true });
1777
+ }
1778
+ if (action._throttleMillis !== null)
1779
+ this._releaseThrottleLock(action);
1780
+ if (action._freshMillis !== null)
1781
+ this._releaseFreshKey(action);
1782
+ if (action.sequential)
1783
+ this._releaseSequentialQueue(action);
1784
+ // Releases the non-reentrant key. This is only done here, after `after()`, and not when the
1785
+ // state is applied (which removes the action from `_actionsInProgress` before `after()`).
1786
+ this._nonReentrantActionsRunning.delete(action);
1787
+ // Remove the wait state for the action in progress.
1788
+ // Note: If the state was applied, this was already removed and the UI updated.
1789
+ // If the action failed, `_processWrapsError` already recorded the failure (so `isFailed` and
1790
+ // `exceptionFor` see it), and this same notification publishes it together with the end of
1791
+ // the waiting.
1792
+ const removed = this._actionsInProgress.delete(action);
1793
+ if (removed) {
1794
+ this._resolveSuspenseWaits();
1795
+ this._statusListeners.notify();
1796
+ // Check the wait-conditions after state change. We pass it the trigger-action.
1797
+ this._checkAllActionConditions(action);
1798
+ }
1799
+ // The action is dispatched twice. This is the 2nd: when the action ends (ini false).
1800
+ this._observeAction(action, false);
1801
+ // This allows us to `let status = await dispatchAndWait(new MyAction())`.
1802
+ // If the action failed with an error that was not swallowed, the promise is rejected.
1803
+ action._resolvePromise(failure);
1804
+ }
1805
+ // Calls the `actionObserver`, if any. If it throws, the error is ignored, so that it doesn't
1806
+ // stop the action from running, or from finishing (which would leave `dispatchAndWait` pending).
1807
+ _observeAction(action, ini) {
1808
+ try {
1809
+ this._actionObserver?.(action, this._dispatchCount, ini);
1810
+ }
1811
+ catch (error) {
1812
+ Store._logLazy(() => `The actionObserver threw an error: ${error}.
1813
+ This error will be ignored, but you should fix this, as the actionObserver should not throw errors.`);
1814
+ }
1815
+ }
1816
+ // Calls the `stateObserver`, if any. If it throws, the error is ignored. Otherwise, it would
1817
+ // leave the store inconsistent: the state is already applied, but the action would fail, and
1818
+ // the state would not be persisted, nor checked by the wait-conditions and `dispatchWhen`.
1819
+ _observeState(action, prevState, newState, error) {
1820
+ try {
1821
+ this._stateObserver?.(action, prevState, newState, error, this._dispatchCount);
1822
+ }
1823
+ catch (observerError) {
1824
+ Store._logLazy(() => `The stateObserver threw an error: ${observerError}.
1825
+ This error will be ignored, but you should fix this, as the stateObserver should not throw errors.`);
1826
+ }
1827
+ }
1828
+ // This method checks and resolves conditions related to actions in progress.
1829
+ // It iterates over the `_waitActionConditions` array and checks each condition.
1830
+ // If a condition is met, it resolves the condition and later removes it.
1831
+ // The `triggerAction` is the action that was just added or removed in the list
1832
+ // of `_actionsInProgress` that triggered the check.
1833
+ _checkAllActionConditions(triggerAction) {
1834
+ const toRemove = [];
1835
+ // Iterate over the conditions, resolve the ones that check, and add the ones to be removed to the separate array.
1836
+ for (const condition of this._waitActionConditions) {
1837
+ let checked;
1838
+ try {
1839
+ checked = condition.check(this._actionsInProgress, triggerAction);
1840
+ }
1841
+ catch (error) {
1842
+ // A throwing condition only fails its own wait. It doesn't affect the trigger action.
1843
+ condition.reject(error);
1844
+ toRemove.push(condition);
1845
+ continue;
1846
+ }
1847
+ if (checked) {
1848
+ condition.resolve(this.actionsInProgress(), triggerAction);
1849
+ toRemove.push(condition);
1850
+ }
1851
+ }
1852
+ // Remove the checked conditions from the original array.
1853
+ if (toRemove.length !== 0)
1854
+ this._waitActionConditions = this._waitActionConditions.filter(condition => !toRemove.includes(condition));
1855
+ }
1856
+ // When `dispatchSync` finds that `before` or `reduce` returned a Promise, the async work has
1857
+ // already started and can't be stopped. Its result is ignored (the state is never changed by it),
1858
+ // and its error is logged, so that it doesn't become an unhandled rejection.
1859
+ // The retry loops check `_isDiscardedByDispatchSync`, so that they stop retrying.
1860
+ _discardAsyncResultOfDispatchSync(action, promise, method) {
1861
+ action._isDiscardedByDispatchSync = true;
1862
+ promise.catch((error) => {
1863
+ Store._logLazy(() => `The async '${method}' of ${action.constructor.name}, dispatched with dispatchSync, failed: ${error}`);
1864
+ });
1865
+ }
1866
+ // Returns the error `dispatchSync` throws when the action is ASYNC. It's thrown inside the
1867
+ // action's run, so that the action still finishes (`after()` runs, and so on), but it's
1868
+ // marked, so that `_processWrapsError` always throws it.
1869
+ _notSyncError(message) {
1870
+ const error = new StoreException(message);
1871
+ this._notSyncErrors.add(error);
1872
+ return error;
1873
+ }
1874
+ _runFromStart(action, mustBeSync) {
1875
+ // A debounced action always waits for its debounce period, so it can't be SYNC.
1876
+ if (mustBeSync && action._debounceMillis !== null)
1877
+ throw this._notSyncError(`You called dispatchSync(${action.constructor.name}), but the action uses debounce, which makes it ASYNC.`);
1878
+ // A sequential action always waits for its turn in the queue, so it can't be SYNC.
1879
+ if (action.sequential) {
1880
+ if (mustBeSync)
1881
+ throw this._notSyncError(`You called dispatchSync(${action.constructor.name}), but the action is sequential, which makes it ASYNC.`);
1882
+ this._runOnSequentialTurn(action, this._enterSequentialQueue(action));
1883
+ return true; // Went ASYNC.
1884
+ }
1885
+ // Numbers the action before `before()` runs, since an ASYNC `before` may make an older
1886
+ // action reach its reducer after a newer one. A dispatch that doesn't run the reducer
1887
+ // doesn't make the other actions old.
1888
+ if (action.ignoreOld && !this._pollSkipsReduce(action))
1889
+ this._abortOlderIgnoreOld(action);
1890
+ // BEFORE
1891
+ // 1) Runs the `before` method.
1892
+ // It may be sync or async, but it doesn't return anything.
1893
+ const beforeResult = action['before']();
1894
+ // 2) If it's async, wait for the `before` method to finish.
1895
+ if (beforeResult instanceof Promise) {
1896
+ if (mustBeSync) {
1897
+ this._discardAsyncResultOfDispatchSync(action, beforeResult, 'before');
1898
+ throw this._notSyncError(`You called dispatchSync(${action.constructor.name}), but the action's 'before' method returned a Promise.`);
1899
+ }
1900
+ this._runAsyncBeforeOnwards(action, beforeResult).then();
1901
+ return true; // Get out of here. Went ASYNC.
1902
+ }
1903
+ action._changeStatus({ hasFinishedMethodBefore: true });
1904
+ // REDUCE
1905
+ const wrapReduce = this._getWrapReduce(action);
1906
+ // 3)
1907
+ // - Runs the SYNC `reduce` method; OR
1908
+ // - Runs the initial sync part of the ASYNC `reduce` method.
1909
+ const reduceResult = wrapReduce(action['reduce'].bind(action))();
1910
+ // 4) If the reducer returned null, or if it returned the unaltered state, we simply do nothing.
1911
+ if (reduceResult == null || reduceResult === this.state) {
1912
+ action._changeStatus({ hasFinishedMethodReduce: true });
1913
+ this._throwIfDispatchedBeforeLogOut(action);
1914
+ this._registerUnchangedState(action);
1915
+ return false; // Kept SYNC.
1916
+ }
1917
+ //
1918
+ // 5) If the reducer is ASYNC, we still process the rest of the reducer to generate the new state.
1919
+ else if (reduceResult instanceof Promise) {
1920
+ if (mustBeSync) {
1921
+ this._discardAsyncResultOfDispatchSync(action, reduceResult, 'reduce');
1922
+ throw this._notSyncError(`You called dispatchSync(${action.constructor.name}), but the action's 'reduce' method returned a Promise.`);
1923
+ }
1924
+ this._runAsyncReduceOnwards(action, reduceResult);
1925
+ return true; // Get out of here. Went ASYNC.
1926
+ }
1927
+ //
1928
+ // 6) If the reducer is SYNC, we already have the new state, and we simply must apply it.
1929
+ else {
1930
+ action._changeStatus({ hasFinishedMethodReduce: true });
1931
+ this._throwIfDispatchedBeforeLogOut(action);
1932
+ if (action['abortReduce'](reduceResult)) {
1933
+ action._changeStatus({ hasFinishedMethodReduce: true });
1934
+ this._registerUnchangedState(action);
1935
+ return false; // Kept SYNC.
1936
+ }
1937
+ this._registerState(action, reduceResult);
1938
+ return false; // Kept SYNC.
1939
+ }
1940
+ }
1941
+ /**
1942
+ * Returns the action's own `wrapReduce`, or, when polling, debounce, retry or
1943
+ * unlimitedRetryCheckInternet is on, a wrapper that calls the action's own `wrapReduce`.
1944
+ * With `ignoreOld`, the result is then checked by `_ignoreOldResult`.
1945
+ * Never replaces `action.wrapReduce`.
1946
+ *
1947
+ * Note: An `OptimisticCommand` handles its own retry, by retrying only `sendCommandToServer`,
1948
+ * so that the optimistic state is not applied and rolled back on each attempt.
1949
+ * Debounce can't be combined with retry, nor used in an `OptimisticCommand`.
1950
+ * Polling can't be combined with debounce or retry, nor used in an `OptimisticCommand`.
1951
+ * unlimitedRetryCheckInternet can't be combined with any of these.
1952
+ */
1953
+ _getWrapReduce(action) {
1954
+ const wrapReduce = this._getFeaturesWrapReduce(action);
1955
+ return (reduce) => {
1956
+ const wrapped = wrapReduce(reduce);
1957
+ return () => {
1958
+ // An action aborted before its reducer runs (during an ASYNC `before`, for example)
1959
+ // doesn't run it.
1960
+ if (action.isAborted)
1961
+ throw this._abortError(action);
1962
+ return this._discardIfAborted(action, wrapped());
1963
+ };
1964
+ };
1965
+ }
1966
+ // The `AbortDispatchException` to throw to finish an aborted action silently. Its message
1967
+ // is the one of the `AbortError` that is the reason of the action's `abortSignal` (see
1968
+ // `KissAction._abort()`).
1969
+ _abortError(action) {
1970
+ const reason = action.abortSignal.reason;
1971
+ return kissAbort((typeof reason?.message === 'string') ? reason.message : 'The action was aborted.');
1972
+ }
1973
+ // The `wrapReduce` of `_getWrapReduce`, without the `ignoreOld` check.
1974
+ _getFeaturesWrapReduce(action) {
1975
+ const userWrapReduce = action['wrapReduce'].bind(action);
1976
+ if (action.poll !== undefined)
1977
+ return this._pollingWrapReduce(action, userWrapReduce);
1978
+ const debounceMillis = action._debounceMillis;
1979
+ if (debounceMillis !== null)
1980
+ return this._debounceWrapReduce(action, userWrapReduce, debounceMillis);
1981
+ return ((action.ifRetryIsOn && !(action instanceof OptimisticCommand)) || action._isUnlimitedRetryCheckInternet)
1982
+ ? this._retryWrapReduce(action, userWrapReduce)
1983
+ : userWrapReduce;
1984
+ }
1985
+ // The error for an action that retries its reducer, but whose reducer is SYNC.
1986
+ static _syncRetryError(action) {
1987
+ const feature = action._isUnlimitedRetryCheckInternet ? 'unlimitedRetryCheckInternet' : 'retry';
1988
+ return new StoreException(`Action '${action}' uses ${feature}, but its reducer is SYNC. Retry needs an ASYNC reducer, that returns a Promise<(St) => St>, because a SYNC reducer does not fail in a way that retrying can fix.`);
1989
+ }
1990
+ static _nullThrownError(action, thrown) {
1991
+ return new Error(`Action '${action}' failed with \`${thrown}\` (it threw \`${thrown}\`, or a Promise was rejected with no reason). Throw an Error instead.`);
1992
+ }
1993
+ // Aborts the `ignoreOld` actions in progress with the same key as the given action, which is
1994
+ // starting to run. Actions dispatched before `clearInternalActionProps()` are not aborted:
1995
+ // the actions dispatched after it behave as if no action had been dispatched before.
1996
+ _abortOlderIgnoreOld(action) {
1997
+ const key = action['computeIgnoreOldKey']();
1998
+ for (const other of this._actionsInProgress) {
1999
+ if (other === action || !other.ignoreOld || this._wereInternalActionPropsCleared(other))
2000
+ continue;
2001
+ if (_isSameNonReentrantKey(other['computeIgnoreOldKey'](), key))
2002
+ other._abort('A newer action was dispatched (ignoreOld).');
2003
+ }
2004
+ }
2005
+ // True if the action uses polling, and its `poll` value means it won't run the reducer:
2006
+ // `Poll.stop`, or `Poll.start` while polling is already active.
2007
+ _pollSkipsReduce(action) {
2008
+ if (action.poll === Poll.stop)
2009
+ return true;
2010
+ // In a server store, `Poll.start` always runs the reducer, since no polling cycle exists.
2011
+ if (action.poll !== Poll.start || this._isServer)
2012
+ return false;
2013
+ const key = action['computePollingKey']();
2014
+ return this._pollingCycles.some(cycle => _isSameNonReentrantKey(cycle.key, key));
2015
+ }
2016
+ /**
2017
+ * Checks the result of the reducer, so that if the action was aborted, it doesn't change the
2018
+ * state. The check is done right when the state is applied: now, for the state returned by
2019
+ * a SYNC reducer, or, for the function `(state) => newState` returned by an ASYNC reducer,
2020
+ * when the store calls it.
2021
+ */
2022
+ _discardIfAborted(action, result) {
2023
+ const throwIfAborted = () => {
2024
+ if (action.isAborted)
2025
+ throw this._abortError(action);
2026
+ };
2027
+ const checked = (fn) => (state) => {
2028
+ throwIfAborted();
2029
+ return fn(state);
2030
+ };
2031
+ if (result instanceof Promise)
2032
+ return result.then(fn => {
2033
+ if (typeof fn === 'function')
2034
+ return checked(fn);
2035
+ throwIfAborted();
2036
+ return fn;
2037
+ });
2038
+ throwIfAborted();
2039
+ return result;
2040
+ }
2041
+ /**
2042
+ * Waits for the debounce period, and then calls the action's own `wrapReduce`. If another
2043
+ * action with the same lock is dispatched meanwhile, returns `null` right away instead, so
2044
+ * that the action finishes without running its reducer. When the debounce period ends, the
2045
+ * action is aborted if its non-reentrant key, throttle lock or fresh-key is taken.
2046
+ *
2047
+ * The result is always ASYNC. A SYNC reducer's new state is returned as `() => newState`.
2048
+ */
2049
+ _debounceWrapReduce(action, userWrapReduce, debounceMillis) {
2050
+ const store = this;
2051
+ function _wrapReduceDebounce(reduce) {
2052
+ async function _wrapReduceDebounceAsync() {
2053
+ // In a server store, the debounce period is not waited: there is no user input to
2054
+ // merge on the server. The action is still ASYNC, as any debounced action.
2055
+ const isLast = store._isServer || await store._waitDebounce(action['debounceLockBuilder'](), debounceMillis);
2056
+ if (!isLast)
2057
+ return null;
2058
+ if (store._mustAbortAfterDebounce(action))
2059
+ throw kissAbort('The non-reentrant key, throttle lock or fresh-key was taken when the debounce period ended.');
2060
+ const newState = userWrapReduce(reduce)();
2061
+ if (newState instanceof Promise)
2062
+ return newState;
2063
+ if (newState == null || newState === store.state)
2064
+ return null;
2065
+ return () => newState;
2066
+ }
2067
+ return () => _wrapReduceDebounceAsync();
2068
+ }
2069
+ return _wrapReduceDebounce;
2070
+ }
2071
+ /**
2072
+ * Resolves with `true` after the debounce period, if no other action with the same lock was
2073
+ * dispatched meanwhile. Otherwise, resolves with `false` as soon as the other action is
2074
+ * dispatched (or the locks are removed).
2075
+ */
2076
+ _waitDebounce(lock, debounceMillis) {
2077
+ const index = this._debounceLocks.findIndex(entry => _isSameNonReentrantKey(entry.lock, lock));
2078
+ if (index !== -1)
2079
+ this._debounceLocks.splice(index, 1)[0].cancel();
2080
+ return new Promise(resolve => {
2081
+ const timer = setTimeout(() => {
2082
+ this._debounceLocks = this._debounceLocks.filter(other => other !== entry);
2083
+ resolve(true);
2084
+ }, capTimeoutMillis(debounceMillis));
2085
+ const entry = {
2086
+ lock,
2087
+ cancel: () => {
2088
+ clearTimeout(timer);
2089
+ resolve(false);
2090
+ },
2091
+ };
2092
+ this._debounceLocks.push(entry);
2093
+ });
2094
+ }
2095
+ /**
2096
+ * For Kiss internal use only. Use `removeAllDebounceLocks()` in the action instead.
2097
+ * Removes all debounce locks. The actions waiting for their debounce period finish right
2098
+ * away, without running their reducer.
2099
+ * @internal
2100
+ */
2101
+ _removeAllDebounceLocks() {
2102
+ const entries = this._debounceLocks;
2103
+ this._debounceLocks = [];
2104
+ for (const entry of entries)
2105
+ entry.cancel();
2106
+ }
2107
+ /**
2108
+ * Starts, stops or restarts the polling of the action's polling key, according to its `poll`
2109
+ * value, and runs the action's own `wrapReduce` when the `poll` value says the reducer runs.
2110
+ * Otherwise, returns `null` synchronously, so that the action finishes without changing the
2111
+ * state.
2112
+ */
2113
+ _pollingWrapReduce(action, userWrapReduce) {
2114
+ const store = this;
2115
+ function _wrapReducePolling(reduce) {
2116
+ function _reducePolling() {
2117
+ // If all polling was stopped (by `clearInternalActionProps()`, `setShutDown(true)` or
2118
+ // `logOut()`) after the action was dispatched, for example while it was in an async
2119
+ // `before()`, it must not start polling again. It's aborted, like retry is.
2120
+ if ((action.poll === Poll.start || action.poll === Poll.runNowAndRestart)
2121
+ && store._wereInternalActionPropsCleared(action))
2122
+ throw kissAbort('The internal action props were cleared, so the action did not start polling.');
2123
+ // In a server store, `Poll.start` and `Poll.runNowAndRestart` run the action once, like
2124
+ // `Poll.once`, and start no polling cycle: the server renders once, and nothing would
2125
+ // use the next tick. The polling validations (`createPollingAction()` is overridden,
2126
+ // the options are valid) already ran at dispatch, as in any store.
2127
+ if (store._isServer && (action.poll === Poll.start || action.poll === Poll.runNowAndRestart))
2128
+ return userWrapReduce(reduce)();
2129
+ const key = action['computePollingKey']();
2130
+ const cycle = store._pollingCycles.find(entry => _isSameNonReentrantKey(entry.key, key));
2131
+ switch (action.poll) {
2132
+ case Poll.start:
2133
+ // If polling is already active, don't do anything.
2134
+ if (cycle !== undefined)
2135
+ return null;
2136
+ return store._runNowAndStartPollingCycle(action, key, userWrapReduce(reduce));
2137
+ case Poll.stop:
2138
+ if (cycle !== undefined)
2139
+ store._stopPollingCycle(cycle);
2140
+ return null;
2141
+ case Poll.runNowAndRestart:
2142
+ if (cycle !== undefined)
2143
+ store._stopPollingCycle(cycle);
2144
+ return store._runNowAndStartPollingCycle(action, key, userWrapReduce(reduce));
2145
+ default: // Poll.once
2146
+ return userWrapReduce(reduce)();
2147
+ }
2148
+ }
2149
+ return _reducePolling;
2150
+ }
2151
+ return _wrapReducePolling;
2152
+ }
2153
+ /**
2154
+ * Starts a new polling cycle for the given `key`, and runs the `reduce` once, immediately.
2155
+ *
2156
+ * When `pollWaitsForRun` is true, the first tick is only scheduled after that immediate run
2157
+ * finishes (even if it fails). When it's false, the first tick is scheduled right away.
2158
+ */
2159
+ _runNowAndStartPollingCycle(action, key, reduce) {
2160
+ const cycle = { key, timer: null, cancelWait: null };
2161
+ this._pollingCycles.push(cycle);
2162
+ if (action.pollWaitsForRun === false) {
2163
+ this._scheduleNextPollingTick(action, cycle);
2164
+ return reduce();
2165
+ }
2166
+ let result;
2167
+ try {
2168
+ result = reduce();
2169
+ }
2170
+ catch (error) {
2171
+ this._scheduleNextPollingTick(action, cycle);
2172
+ throw error;
2173
+ }
2174
+ if (result instanceof Promise)
2175
+ return result.finally(() => this._scheduleNextPollingTick(action, cycle));
2176
+ this._scheduleNextPollingTick(action, cycle);
2177
+ return result;
2178
+ }
2179
+ /**
2180
+ * Schedules a one-shot timer that dispatches the action returned by `createPollingAction()`,
2181
+ * and then schedules the next tick. If `pollWaitsForRun` is true, the next tick is only
2182
+ * scheduled when the dispatched action finishes. Otherwise, it's scheduled as soon as the
2183
+ * action is dispatched.
2184
+ *
2185
+ * If the `cycle` is no longer active (because polling was stopped or restarted in the
2186
+ * meantime), the tick is abandoned.
2187
+ */
2188
+ _scheduleNextPollingTick(action, cycle) {
2189
+ if (!this._pollingCycles.includes(cycle))
2190
+ return;
2191
+ const runTick = () => {
2192
+ if (!this._pollingCycles.includes(cycle))
2193
+ return;
2194
+ const waitsForRun = action.pollWaitsForRun !== false;
2195
+ const tick = (async () => {
2196
+ const tickAction = action['createPollingAction']();
2197
+ if (waitsForRun)
2198
+ await this.dispatchAndWait(tickAction);
2199
+ else
2200
+ this.dispatch(tickAction);
2201
+ })();
2202
+ if (!waitsForRun)
2203
+ this._scheduleNextPollingTick(action, cycle);
2204
+ // Errors don't stop the polling. An error that was not swallowed is still thrown, as an
2205
+ // unhandled rejection, like the error of any dispatch nobody waits for.
2206
+ tick.finally(() => {
2207
+ if (waitsForRun)
2208
+ this._scheduleNextPollingTick(action, cycle);
2209
+ });
2210
+ };
2211
+ cycle.timer = setTimeout(() => {
2212
+ if (!this._pollingCycles.includes(cycle))
2213
+ return;
2214
+ // While the tick runs (or waits for the app to be focused or online) there is no timer,
2215
+ // but the cycle is still active.
2216
+ cycle.timer = null;
2217
+ if (this._pollingCanTick(action))
2218
+ runTick();
2219
+ else
2220
+ this._waitToTick(action, cycle, runTick);
2221
+ }, capTimeoutMillis(action._pollIntervalMillis));
2222
+ }
2223
+ // True if the app is focused and online, as far as the action's `pollOnlyWhenFocused` and
2224
+ // `pollOnlyWhenOnline` require. Only reads the signals the action requires, so that an action
2225
+ // that requires none doesn't make the store listen to the sources.
2226
+ _pollingCanTick(action) {
2227
+ if (action.pollOnlyWhenFocused !== false && !this.isFocused)
2228
+ return false;
2229
+ if (action.pollOnlyWhenOnline !== false && !this.isOnline)
2230
+ return false;
2231
+ return true;
2232
+ }
2233
+ // A tick came due while the app is not focused or not online (see `_pollingCanTick`). Waits
2234
+ // for the signals the action requires, and then runs the tick right away. Stopping the cycle
2235
+ // meanwhile (`Poll.stop`, `Poll.runNowAndRestart`, `clearInternalActionProps()`) drops the tick.
2236
+ _waitToTick(action, cycle, runTick) {
2237
+ const unsubscribes = [];
2238
+ const cancelWait = () => {
2239
+ cycle.cancelWait = null;
2240
+ for (const unsubscribe of unsubscribes)
2241
+ unsubscribe();
2242
+ };
2243
+ cycle.cancelWait = cancelWait;
2244
+ const onChange = () => {
2245
+ if (!this._pollingCanTick(action))
2246
+ return;
2247
+ cancelWait();
2248
+ runTick();
2249
+ };
2250
+ if (action.pollOnlyWhenFocused !== false)
2251
+ unsubscribes.push(this._focus.subscribe(onChange));
2252
+ if (action.pollOnlyWhenOnline !== false)
2253
+ unsubscribes.push(this._online.subscribe(onChange));
2254
+ }
2255
+ // Cancels the timer of the polling cycle, and removes the cycle, so that its ticks stop.
2256
+ _stopPollingCycle(cycle) {
2257
+ if (cycle.timer !== null)
2258
+ clearTimeout(cycle.timer);
2259
+ cycle.timer = null;
2260
+ cycle.cancelWait?.();
2261
+ this._pollingCycles = this._pollingCycles.filter(entry => entry !== cycle);
2262
+ }
2263
+ /**
2264
+ * For Kiss internal use only. Use `stopAllPolling()` in the action instead.
2265
+ * Stops all polling cycles. Runs that are in progress still finish, but no new ticks start.
2266
+ * @internal
2267
+ */
2268
+ _stopAllPolling() {
2269
+ const cycles = this._pollingCycles;
2270
+ this._pollingCycles = [];
2271
+ for (const cycle of cycles) {
2272
+ if (cycle.timer !== null)
2273
+ clearTimeout(cycle.timer);
2274
+ cycle.timer = null;
2275
+ cycle.cancelWait?.();
2276
+ }
2277
+ }
2278
+ _retryWrapReduce(action, userWrapReduce) {
2279
+ const store = this;
2280
+ const retry = action._retry;
2281
+ // With unlimitedRetryCheckInternet, the internet is checked before each attempt. If there is
2282
+ // no internet, the reducer doesn't run, and it's retried later. Note this retries unlimited
2283
+ // times, and the waits between attempts are capped by `maxDelayNoInternet`. A server store
2284
+ // doesn't check the internet (it counts as online), and doesn't retry (see `_waitToRetry`).
2285
+ const checkInternet = action._isUnlimitedRetryCheckInternet && !this._isServer;
2286
+ const _syncRetryError = () => Store._syncRetryError(action);
2287
+ const _discardedError = () => kissAbort('dispatchSync threw because the action is ASYNC, so the action stopped retrying.');
2288
+ // Counts the failed attempt, and waits before the next one. Throws the error instead, if
2289
+ // there are no retries left, or an `AbortDispatchException` if the internal action props
2290
+ // were cleared (for example, because the store was shut down).
2291
+ async function _waitToRetry(error, maxDelay) {
2292
+ // When `dispatchSync` threw because the action is ASYNC, its result is ignored, so there's
2293
+ // no point retrying. Note the error is `null` when there is no internet.
2294
+ if (action._isDiscardedByDispatchSync)
2295
+ throw error ?? _discardedError();
2296
+ // When `clearInternalActionProps()` was called (for example, on logout), stops retrying.
2297
+ // This is checked before checking the retries left, so that a last attempt that fails
2298
+ // is aborted too, instead of failing.
2299
+ if (store._wereInternalActionPropsCleared(action))
2300
+ throw Store._clearedRetryError();
2301
+ // A server store doesn't retry: the action fails right away with the reducer's error.
2302
+ // (The error is never `null` here, since a server store doesn't check the internet.)
2303
+ if (store._isServer)
2304
+ throw error;
2305
+ retry.attempts++;
2306
+ if (!retry.unlimitedRetries && (retry.maxRetries >= 0) && (retry.attempts > retry.maxRetries))
2307
+ throw error;
2308
+ // The action can give up on some errors (`shouldRetry`). Not when there is no internet.
2309
+ if ((error !== null) && !action._shouldRetry(error, retry.attempts))
2310
+ throw error;
2311
+ await store._waitRetryDelay(action, action._nextRetryDelay(maxDelay));
2312
+ }
2313
+ function _wrapReduceRetry(reduce) {
2314
+ async function _wrapReduceRetryAsync() {
2315
+ while (true) {
2316
+ if (checkInternet) {
2317
+ let hasInternet;
2318
+ try {
2319
+ hasInternet = await action._hasInternet();
2320
+ }
2321
+ catch (error) {
2322
+ // If checking the internet fails, this counts as a failed attempt with internet.
2323
+ Store._logLazy(() => `Checking the internet for ${action} has thrown an error: ${error}.`);
2324
+ await _waitToRetry(error, retry.maxDelay);
2325
+ continue;
2326
+ }
2327
+ const attempt = (retry.attempts === 0) ? 'Trying' : 'Retrying';
2328
+ const attemptNumber = (retry.attempts === 0) ? '' : ` (attempt ${retry.attempts})`;
2329
+ if (!hasInternet) {
2330
+ Store._logLazy(() => `${attempt} ${action}; aborted because of no internet${attemptNumber}.`);
2331
+ await _waitToRetry(null, action._maxDelayNoInternet);
2332
+ continue;
2333
+ }
2334
+ Store._logLazy(() => `${attempt} ${action}${attemptNumber}.`);
2335
+ }
2336
+ // With unlimitedRetryCheckInternet, `dispatchSync` throws before the reducer runs for
2337
+ // the first time (when the internet is checked). Since its result would be ignored,
2338
+ // the reducer doesn't run.
2339
+ if (action._isDiscardedByDispatchSync)
2340
+ throw _discardedError();
2341
+ // A SYNC reducer can't be retried. If the reducer throws synchronously, or returns
2342
+ // without a Promise (even null, or the unchanged state), fail right away with a
2343
+ // StoreException, without retrying. Note we check the reducer itself, and not the
2344
+ // result of `wrapReduce`, since a custom `wrapReduce` may discard the result of an
2345
+ // ASYNC reducer by returning null synchronously.
2346
+ let isSyncReducer = false;
2347
+ const reduceAndCheck = () => {
2348
+ let result;
2349
+ try {
2350
+ result = reduce();
2351
+ }
2352
+ catch (error) {
2353
+ isSyncReducer = true;
2354
+ throw error;
2355
+ }
2356
+ if (!(result instanceof Promise))
2357
+ isSyncReducer = true;
2358
+ return result;
2359
+ };
2360
+ let newState;
2361
+ try {
2362
+ newState = userWrapReduce(reduceAndCheck)();
2363
+ }
2364
+ catch (error) {
2365
+ throw isSyncReducer ? _syncRetryError() : error;
2366
+ }
2367
+ if (isSyncReducer)
2368
+ throw _syncRetryError();
2369
+ try {
2370
+ newState = await newState;
2371
+ }
2372
+ //
2373
+ catch (error) {
2374
+ if (isSyncReducer)
2375
+ throw _syncRetryError();
2376
+ // An aborted action is not retried.
2377
+ if (error instanceof AbortDispatchException)
2378
+ throw error;
2379
+ await _waitToRetry(error, retry.maxDelay);
2380
+ continue;
2381
+ }
2382
+ // The custom `wrapReduce` may have called a SYNC reducer only after some `await`.
2383
+ if (isSyncReducer)
2384
+ throw _syncRetryError();
2385
+ return newState;
2386
+ }
2387
+ }
2388
+ return () => _wrapReduceRetryAsync();
2389
+ }
2390
+ return _wrapReduceRetry;
2391
+ }
2392
+ _record(action, ini, prevState, newState, error) {
2393
+ if (this.record.isRecording) {
2394
+ this.record.changes.push({
2395
+ action,
2396
+ ini,
2397
+ prevState: prevState,
2398
+ newState: newState,
2399
+ error: error,
2400
+ dispatchCount: this._dispatchCount
2401
+ });
2402
+ }
2403
+ }
2404
+ async _runAsyncBeforeOnwards(action, beforeResult) {
2405
+ this._wrapsAsync(action, async () => {
2406
+ // 2.1) Method `before` is ASYNC, so we wait for it to finish.
2407
+ await beforeResult;
2408
+ action._changeStatus({ hasFinishedMethodBefore: true });
2409
+ // REDUCE
2410
+ const wrapReduce = this._getWrapReduce(action);
2411
+ // 2.2)
2412
+ // - Runs the SYNC `reduce` method; OR
2413
+ // - Runs the initial sync part of the ASYNC `reduce` method.
2414
+ let reduceResult = wrapReduce(action['reduce'].bind(action))();
2415
+ // 2.3) If the reducer returned null, or if it returned the unaltered state, we simply do nothing.
2416
+ if (reduceResult == null || reduceResult === this.state) {
2417
+ action._changeStatus({ hasFinishedMethodReduce: true });
2418
+ this._throwIfDispatchedBeforeLogOut(action);
2419
+ this._registerUnchangedState(action);
2420
+ return; // Get out of here.
2421
+ }
2422
+ //
2423
+ // 2.4) If the reducer is ASYNC, we still process the rest of the reducer to generate the new state.
2424
+ else if (reduceResult instanceof Promise) {
2425
+ reduceResult = await reduceResult;
2426
+ action._changeStatus({ hasFinishedMethodReduce: true });
2427
+ this._throwIfDispatchedBeforeLogOut(action);
2428
+ if (reduceResult == null || reduceResult === this.state) {
2429
+ this._registerUnchangedState(action);
2430
+ }
2431
+ //
2432
+ else {
2433
+ if ((action.ifRetryIsOn || action._isUnlimitedRetryCheckInternet) && !this._isFunction(reduceResult))
2434
+ throw Store._syncRetryError(action);
2435
+ const newAsyncState = reduceResult(this.state);
2436
+ if (newAsyncState != null && newAsyncState !== this.state) {
2437
+ if (action['abortReduce'](newAsyncState)) {
2438
+ this._registerUnchangedState(action);
2439
+ }
2440
+ else
2441
+ this._registerState(action, newAsyncState);
2442
+ }
2443
+ else
2444
+ this._registerUnchangedState(action);
2445
+ }
2446
+ return; // Get out of here.
2447
+ }
2448
+ //
2449
+ // 2.5) If the reducer is SYNC, we already have the new state, and we simply must apply it.
2450
+ else {
2451
+ action._changeStatus({ hasFinishedMethodReduce: true });
2452
+ this._throwIfDispatchedBeforeLogOut(action);
2453
+ if (action['abortReduce'](reduceResult)) {
2454
+ action._changeStatus({ hasFinishedMethodReduce: true });
2455
+ this._registerUnchangedState(action);
2456
+ }
2457
+ else
2458
+ this._registerState(action, reduceResult);
2459
+ return; // Get out of here.
2460
+ }
2461
+ }).then();
2462
+ }
2463
+ _runAsyncReduceOnwards(action, reduceResult) {
2464
+ this._wrapsAsync(action, async () => {
2465
+ // 5.1) Method `reduce` is ASYNC, so we wait for it to finish.
2466
+ const functionalReduceResult = await reduceResult;
2467
+ action._changeStatus({ hasFinishedMethodReduce: true });
2468
+ this._throwIfDispatchedBeforeLogOut(action);
2469
+ // 5.2) If the reducer returned null, we simply do nothing.
2470
+ if (functionalReduceResult == null) {
2471
+ this._registerUnchangedState(action);
2472
+ return; // Get out of here.
2473
+ }
2474
+ //
2475
+ // 5.3) If the reducer returned a function `(state: St) => (St | null)`,
2476
+ // we still need to run this function to generate the new state.
2477
+ else {
2478
+ if ((action.ifRetryIsOn || action._isUnlimitedRetryCheckInternet) && !this._isFunction(functionalReduceResult))
2479
+ throw Store._syncRetryError(action);
2480
+ const finalReduceState = functionalReduceResult(this.state);
2481
+ if (finalReduceState != null && finalReduceState !== this.state) {
2482
+ if (action['abortReduce'](finalReduceState)) {
2483
+ this._registerUnchangedState(action);
2484
+ }
2485
+ else
2486
+ this._registerState(action, finalReduceState);
2487
+ }
2488
+ else
2489
+ this._registerUnchangedState(action);
2490
+ return; // Get out of here.
2491
+ }
2492
+ }).then();
2493
+ }
2494
+ _isFunction(obj) {
2495
+ return typeof obj === 'function';
2496
+ }
2497
+ /**
2498
+ * Called when the action finished with no error, but did not change the state: the reducer
2499
+ * returned null or the unchanged state, or `abortReduce()` returned true. The state-observer
2500
+ * is still called, with the same `prevState` and `newState`. And if the action is a
2501
+ * `PersistAction`, the state is persisted right away.
2502
+ */
2503
+ _registerUnchangedState(action) {
2504
+ this._observeState(action, this._state, this._state, null);
2505
+ this._record(action, false, this._state, this._state, null);
2506
+ if (action instanceof PersistAction && this._processPersistence != null)
2507
+ this._processPersistence.process(action, this._state);
2508
+ }
2509
+ _registerState(action, newState) {
2510
+ if (this._logStateChanges && Store._isLogging()) {
2511
+ try {
2512
+ const stateChangeDescription = Store.describeStateChange(this.state, newState);
2513
+ if (stateChangeDescription !== '')
2514
+ Store.log(stateChangeDescription);
2515
+ }
2516
+ catch {
2517
+ // Swallow error and do nothing, as this is just a debug print.
2518
+ }
2519
+ }
2520
+ const prevState = this._state;
2521
+ if (newState != null && newState !== this._state) {
2522
+ this._state = newState;
2523
+ // Remove the wait state for the action in progress. This is done BEFORE publishing the
2524
+ // new state, so that a single render sees both the new state and the end of the waiting.
2525
+ // Note: `after()` still runs later, in `_processWrapsFinally`, and a non-reentrant key is
2526
+ // only released there.
2527
+ const removed = this._actionsInProgress.delete(action);
2528
+ if (removed)
2529
+ this._resolveSuspenseWaits();
2530
+ // Publish the new state, and then the status change. React checks the components that
2531
+ // use them, and renders the ones whose selected values changed. Nothing is rendered
2532
+ // synchronously here: React schedules the render, and reads the values again then.
2533
+ this._stateListeners.notify();
2534
+ if (removed)
2535
+ this._statusListeners.notify();
2536
+ // Observe the state with null error, because the reducer completed normally.
2537
+ this._observeState(action, prevState, newState, null);
2538
+ this._record(action, false, prevState, newState, null);
2539
+ // ---
2540
+ // Check the wait-conditions after state change. We pass it the trigger-action.
2541
+ if (removed)
2542
+ this._checkAllActionConditions(action);
2543
+ // Check the wait-conditions after state change.
2544
+ this._waitConditions = this._waitConditions.filter(condition => {
2545
+ let checked;
2546
+ try {
2547
+ checked = condition.check(this.state);
2548
+ }
2549
+ catch (error) {
2550
+ // A throwing condition only fails its own wait. It doesn't affect the trigger action.
2551
+ condition.reject(error);
2552
+ return false; // remove the condition from the array.
2553
+ }
2554
+ if (checked) {
2555
+ // Resolve, returning the action that triggered the condition.
2556
+ condition.resolve(action);
2557
+ return false; // remove the condition from the array.
2558
+ }
2559
+ return true; // keep the condition in the array.
2560
+ });
2561
+ }
2562
+ if (this._processPersistence != null)
2563
+ this._processPersistence.process(action, newState);
2564
+ // Dispatch the `dispatchWhen` actions whose condition was met. This is done only now, so that
2565
+ // all wait-conditions are checked against the state that met them, and the persistor gets
2566
+ // that state before the state changed by these actions. Each condition is checked again
2567
+ // right before its action is dispatched, since an earlier action may have made it false.
2568
+ if (this._dispatchWhenQueue.length > 0) {
2569
+ const dispatchIfStillMetFunctions = this._dispatchWhenQueue;
2570
+ this._dispatchWhenQueue = [];
2571
+ for (const dispatchIfStillMet of dispatchIfStillMetFunctions)
2572
+ dispatchIfStillMet();
2573
+ }
2574
+ }
2575
+ /**
2576
+ * For this to work, we have to pass a function `showUserException` in the constructor
2577
+ * of the Store, that will open some UI to show the error to the user.
2578
+ *
2579
+ * 1) If the UI is still open, don't do anything.
2580
+ * 2) If no UI is open, check to see if any errors are in the queue.
2581
+ * If so, remove the first error from the queue and show it in the UI.
2582
+ * 3) In this case, we mark the UI as open, and count the number of errors still in the queue.
2583
+ * 4) When the UI calls `next()`, we mark the UI as closed, and call the method again, to
2584
+ * process the next error in the queue, if any.
2585
+ *
2586
+ * IMPORTANT: Failing to call `next()` will prevent the UI to ever opening again, because
2587
+ * Kiss will think the previous UI is still open. In contrast, calling `next()` as soon
2588
+ * as the UI opens may result in opening more than one UI on top pf each other.
2589
+ * Also, calling `next()` when there are no more errors in the queue will do nothing.
2590
+ *
2591
+ * An example using React Native:
2592
+ *
2593
+ * ```ts
2594
+ * const showUserException = (exception: UserException, count: number, next: () => void) => {
2595
+ * Alert.alert(
2596
+ * exception.title || exception.message,
2597
+ * exception.title ? exception.message : '',
2598
+ * [{ text: 'OK', onPress: (_value?: string) => next() }]
2599
+ * );
2600
+ * };
2601
+ * ```
2602
+ */
2603
+ _openSomeUiToShowUserException() {
2604
+ // 1) If the UI is still open, don't do anything.
2605
+ if (this._isUserExceptionUiOpen)
2606
+ return;
2607
+ // 2.1) If no UI is open,
2608
+ else {
2609
+ // 2.2) Check to see if any errors are in the queue. If so, remove the first error from the queue.
2610
+ const currentError = this.userExceptionsQueue.shift();
2611
+ if (currentError !== undefined) {
2612
+ // 3.1) In this case, we mark the UI as open,
2613
+ this._isUserExceptionUiOpen = true;
2614
+ // 3.2) and count the number of errors still in the queue.
2615
+ const queued = this.userExceptionsQueue.length;
2616
+ // 2.3) And show it in the UI.
2617
+ try {
2618
+ this._showUserException?.(currentError, queued,
2619
+ // 4.1) When the UI calls `next()`.
2620
+ () => {
2621
+ // 4.2) We mark the UI as closed.
2622
+ this._isUserExceptionUiOpen = false;
2623
+ // 4.3) And call the method again, to process the next error in the queue, if any.
2624
+ this._openSomeUiToShowUserException();
2625
+ });
2626
+ }
2627
+ catch (error) {
2628
+ // A throwing `showUserException` must not block future dialogs, nor replace the
2629
+ // action's error. We log it, mark the UI as closed, and continue with the queue.
2630
+ Store._logLazy(() => `The showUserException function threw an error: ${error}.
2631
+ This error will be ignored, but you should fix this, as showUserException should not throw errors.`);
2632
+ this._isUserExceptionUiOpen = false;
2633
+ this._openSomeUiToShowUserException();
2634
+ }
2635
+ }
2636
+ }
2637
+ }
2638
+ ;
2639
+ _isUserExceptionUiOpen = false;
2640
+ // Processes the errors of the Persistor. The `error` was already processed by the persistor's
2641
+ // `wrapError`, and `originalError` is the error before it. The error is given to the
2642
+ // `errorObserver`, with a `null` action. Then:
2643
+ // - If `observeOnly` is true, nothing else is done, since the error is thrown by `logOut`.
2644
+ // - If it's a `UserException`, it's shown to the user.
2645
+ // - If it's `null`, it's swallowed.
2646
+ // - Otherwise, it's thrown as an unhandled promise rejection, since there is no `dispatch`
2647
+ // call to throw it to.
2648
+ _processPersistorError(error, originalError, observeOnly) {
2649
+ if (this._errorObserver)
2650
+ error = this._observeError(error, originalError, null);
2651
+ if (observeOnly || (error === null))
2652
+ return;
2653
+ if (error instanceof UserException) {
2654
+ if (error.ifOpenDialog) {
2655
+ this._addUserException(error);
2656
+ this._openSomeUiToShowUserException();
2657
+ }
2658
+ }
2659
+ //
2660
+ else
2661
+ void Promise.reject(error);
2662
+ }
2663
+ _addUserException(error) {
2664
+ this.userExceptionsQueue.push(error);
2665
+ }
2666
+ /**
2667
+ * Aborts all the actions of the given `type` (or of a subclass) that are in progress. Each
2668
+ * one finishes silently: its `abortSignal` is aborted, its result is ignored (it doesn't
2669
+ * change the state), and so are its errors (no error dialog, it doesn't count as failed, and
2670
+ * it isn't retried). Its status has `isDispatchAborted: true`, and `dispatchAndWait`
2671
+ * resolves. Inside the action, `isAborted` is `true`.
2672
+ *
2673
+ * For example, to cancel the request a component started, when the component unmounts:
2674
+ *
2675
+ * ```ts
2676
+ * useStoreEffect({
2677
+ * onMount: (store) => store.dispatch(new LoadUser(userId)),
2678
+ * onUnmount: (store) => store.abort(LoadUser),
2679
+ * });
2680
+ * ```
2681
+ *
2682
+ * Or from a "Cancel" button: `onClick={() => store.abort(UploadFile)}`.
2683
+ *
2684
+ * - A request that uses the action's `abortSignal` is cancelled right away. Otherwise, the
2685
+ * action is still in progress (`isWaiting` is `true`) until the request finishes, and
2686
+ * only then its result is ignored.
2687
+ * - An action aborted during its `before` method doesn't run its reducer. One aborted while
2688
+ * waiting to retry stops retrying.
2689
+ * - It does nothing if no action of the type is in progress.
2690
+ *
2691
+ * Pass `{ statusKey }` to abort only the actions with that `statusKey` (see
2692
+ * `KissAction.statusKey`): `store.abort(LoadUser, { statusKey: userId })`.
2693
+ *
2694
+ * To abort a single action instance, use its `abort()` method.
2695
+ */
2696
+ abort(type, options) {
2697
+ const statusKey = options?.statusKey;
2698
+ for (const action of this._actionsInProgress) {
2699
+ if (action instanceof type && (statusKey === undefined || _isSameNonReentrantKey(action.statusKey, statusKey)))
2700
+ action._abort(`The action was aborted by store.abort(${type.name}).`);
2701
+ }
2702
+ }
2703
+ /**
2704
+ * You can use `isWaiting` and pass it an action `type`:
2705
+ * - It returns true if an action of the given type (or of a subclass) is currently being processed.
2706
+ * - It returns false if no action of the given type is currently being processed.
2707
+ * - This is only useful for ASYNC actions. A SYNC action finishes before `dispatch` returns, so
2708
+ * outside of it, `isWaiting` is always `false` for it, and components never see it as `true`.
2709
+ * - Inside an action, `isWaiting` of the action's own type is always `true` (even when the action
2710
+ * is SYNC), since the action itself is being processed.
2711
+ *
2712
+ * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
2713
+ *
2714
+ * ```ts
2715
+ * store.dispatch(new MyAction());
2716
+ * if (store.isWaiting(MyAction)) { ... } // Show a spinner
2717
+ * ```
2718
+ *
2719
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
2720
+ * `KissAction.statusKey`): `store.isWaiting(LoadUser, { statusKey: userId })`.
2721
+ */
2722
+ isWaiting(type, options) {
2723
+ const statusKey = options?.statusKey;
2724
+ for (const action of this._actionsInProgress) {
2725
+ if (action instanceof type && (statusKey === undefined || _isSameNonReentrantKey(action.statusKey, statusKey))) {
2726
+ return true;
2727
+ }
2728
+ }
2729
+ return false;
2730
+ }
2731
+ /**
2732
+ * Returns true if the given action `type` failed, with any error, not only with a
2733
+ * `UserException`. Use `exceptionFor` to get the error, if it was a `UserException`.
2734
+ * An error swallowed by `wrapError` or the `errorObserver` (they returned `null`), and
2735
+ * an `AbortDispatchException`, don't count as failures.
2736
+ * Note: This method uses the EXACT action type. Subtypes are not considered.
2737
+ *
2738
+ * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see
2739
+ * `KissAction.statusKey`): `store.isFailed(LoadUser, { statusKey: userId })`.
2740
+ */
2741
+ isFailed(type, options) {
2742
+ return this._findFailure(type, options) !== null;
2743
+ }
2744
+ /**
2745
+ * Returns the `UserException` of the `type` that failed. Returns `null` if it didn't fail,
2746
+ * or if it failed with an error that is not a `UserException` (in that case, `isFailed` is
2747
+ * still true).
2748
+ * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
2749
+ *
2750
+ * Pass `{ statusKey }` to get the exception of the failure with that `statusKey` (see
2751
+ * `KissAction.statusKey`): `store.exceptionFor(LoadUser, { statusKey: userId })`. Without it,
2752
+ * if actions with different keys failed, you get the `UserException` of the most recent
2753
+ * failure.
2754
+ */
2755
+ exceptionFor(type, options) {
2756
+ const failures = this._failedActions.get(type);
2757
+ if (failures === undefined)
2758
+ return null;
2759
+ const statusKey = options?.statusKey;
2760
+ // The most recent failure is the last one. Without a key, we return the most recent
2761
+ // UserException, skipping the failures with other kinds of errors.
2762
+ for (let i = failures.length - 1; i >= 0; i--) {
2763
+ const failure = failures[i];
2764
+ if (statusKey !== undefined && !_isSameNonReentrantKey(failure.statusKey, statusKey))
2765
+ continue;
2766
+ if (failure.error instanceof UserException)
2767
+ return failure.error;
2768
+ if (statusKey !== undefined)
2769
+ return null;
2770
+ }
2771
+ return null;
2772
+ }
2773
+ /**
2774
+ * Removes the exact given action `type` from the list of action types that failed.
2775
+ * Note it clears the EXACT given type. Subtypes are not considered.
2776
+ *
2777
+ * Even if you never call this method explicitly, just dispatching an action already clears that action type
2778
+ * from the list of failing action types. But you can call this method explicitly if you want to clear the
2779
+ * action type before it's used again.
2780
+ *
2781
+ * Usage:
2782
+ * ```ts
2783
+ * store.clearExceptionFor(MyAction);
2784
+ * ```
2785
+ *
2786
+ * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see
2787
+ * `KissAction.statusKey`): `store.clearExceptionFor(LoadUser, { statusKey: userId })`.
2788
+ * Without it, all the failures of the type are cleared, whatever their keys.
2789
+ */
2790
+ clearExceptionFor(type, options) {
2791
+ const statusKey = options?.statusKey;
2792
+ const removed = (statusKey === undefined)
2793
+ ? this._failedActions.delete(type)
2794
+ : this._removeFailure(type, statusKey);
2795
+ if (removed)
2796
+ this._statusListeners.notify();
2797
+ }
2798
+ /**
2799
+ * Clears the failures of all action types, so that `isFailed` is `false` and `exceptionFor`
2800
+ * is `null` for all of them. The components that use them are updated.
2801
+ *
2802
+ * You rarely need to call this yourself, since `clearInternalActionProps()` already calls it,
2803
+ * and so do `logOut()` and the shutdown of the store (`setShutDown(true)` and `dispose()`).
2804
+ * The failures kept for actions with a `statusKey` (one per key that failed) are also
2805
+ * released here. See `KissAction.statusKey`.
2806
+ */
2807
+ clearAllExceptions() {
2808
+ if (this._failedActions.size === 0)
2809
+ return;
2810
+ this._failedActions.clear();
2811
+ this._statusListeners.notify();
2812
+ }
2813
+ /**
2814
+ * Internal: the value `useSuspense` reads as its snapshot, for the given action `type` and
2815
+ * `statusKey` (`undefined` matches any key):
2816
+ *
2817
+ * - A promise, while an action of the type (or of a subclass) with that key is in progress,
2818
+ * as `isWaiting` sees it. The same promise object is returned until the action finishes, as
2819
+ * React's Suspense needs, and it resolves then (see `_resolveSuspenseWaits`). The promise
2820
+ * is created the first time it's asked for, so a store whose components never call
2821
+ * `useSuspense` creates none.
2822
+ * - Otherwise, when `throwErrors` is true, the failure record of the type with that key, as
2823
+ * `isFailed` sees it (the exact type; without a key, the most recent failure). It's the
2824
+ * same object until the failure is replaced or cleared.
2825
+ * - Otherwise `null`.
2826
+ *
2827
+ * @internal
2828
+ */
2829
+ _suspenseValue(type, statusKey, throwErrors = true) {
2830
+ if (this.isWaiting(type, { statusKey })) {
2831
+ let wait = this._suspenseWaits.find(w => w.type === type && _isSameNonReentrantKey(w.statusKey, statusKey));
2832
+ if (wait === undefined) {
2833
+ let resolve;
2834
+ const promise = new Promise(r => resolve = r);
2835
+ wait = { type, statusKey, promise, resolve };
2836
+ this._suspenseWaits.push(wait);
2837
+ }
2838
+ return wait.promise;
2839
+ }
2840
+ if (!throwErrors)
2841
+ return null;
2842
+ return this._findFailure(type, { statusKey });
2843
+ }
2844
+ /**
2845
+ * Resolves and removes the `useSuspense` promises whose action is not in progress anymore.
2846
+ * Called when an action leaves `_actionsInProgress`. Costs nothing while the list is empty.
2847
+ */
2848
+ _resolveSuspenseWaits() {
2849
+ if (this._suspenseWaits.length === 0)
2850
+ return;
2851
+ for (let i = this._suspenseWaits.length - 1; i >= 0; i--) {
2852
+ const wait = this._suspenseWaits[i];
2853
+ if (!this.isWaiting(wait.type, { statusKey: wait.statusKey })) {
2854
+ this._suspenseWaits.splice(i, 1);
2855
+ wait.resolve();
2856
+ }
2857
+ }
2858
+ }
2859
+ /**
2860
+ * Returns the failure of the given `type` that matches `options.statusKey`, or the most
2861
+ * recent failure of the type when there is no key. Returns `null` if there is none.
2862
+ */
2863
+ _findFailure(type, options) {
2864
+ const failures = this._failedActions.get(type);
2865
+ if (failures === undefined)
2866
+ return null;
2867
+ const statusKey = options?.statusKey;
2868
+ if (statusKey === undefined)
2869
+ return failures[failures.length - 1] ?? null;
2870
+ return failures.find(failure => _isSameNonReentrantKey(failure.statusKey, statusKey)) ?? null;
2871
+ }
2872
+ /** Records a failure, replacing the previous failure of the same type and `statusKey`, if any. */
2873
+ _addFailure(type, statusKey, error) {
2874
+ this._removeFailure(type, statusKey);
2875
+ const failures = this._failedActions.get(type);
2876
+ if (failures === undefined)
2877
+ this._failedActions.set(type, [{ statusKey, error }]);
2878
+ else
2879
+ failures.push({ statusKey, error });
2880
+ }
2881
+ /** Removes the failure of the given type and `statusKey`. Returns true if there was one. */
2882
+ _removeFailure(type, statusKey) {
2883
+ const failures = this._failedActions.get(type);
2884
+ if (failures === undefined)
2885
+ return false;
2886
+ const index = failures.findIndex(failure => _isSameNonReentrantKey(failure.statusKey, statusKey));
2887
+ if (index === -1)
2888
+ return false;
2889
+ failures.splice(index, 1);
2890
+ if (failures.length === 0)
2891
+ this._failedActions.delete(type);
2892
+ return true;
2893
+ }
2894
+ /**
2895
+ * Returns true if the event was already handled (spent) by a component of this store, with
2896
+ * `useEvent` or `useLayoutEvent`. Also true for `Evt.spent()` and `EvtState.spent()`, and
2897
+ * for restored (persisted) events, which are spent in every store.
2898
+ *
2899
+ * Useful in component tests, to check that a component handled the event:
2900
+ *
2901
+ * ```ts
2902
+ * await store.dispatchAndWait(new ScrollFeedToTop());
2903
+ * expect(store.isEventSpent(store.state.scrollToTopEvt)).toBe(true);
2904
+ * ```
2905
+ *
2906
+ * Note an `EvtState` is never spent by components, so for it this only returns true for
2907
+ * `EvtState.spent()` and restored events.
2908
+ */
2909
+ isEventSpent(evt) {
2910
+ return evt._spentAtCreation || (evt instanceof Evt && this._spentEvents.has(evt));
2911
+ }
2912
+ // ----------------------------------------------------------------------------------------------
2913
+ // Environment, dependencies and configuration.
2914
+ // ----------------------------------------------------------------------------------------------
2915
+ /**
2916
+ * The environment the app is running in (production, staging, testing, etc), as given to the
2917
+ * store constructor, or `undefined`. It never changes while the app runs. Typed `unknown`:
2918
+ * declare a typed getter in your base action, like
2919
+ * `get env() { return this.store.environment as Environment; }`. In components, use
2920
+ * `useEnvironment()`.
2921
+ *
2922
+ * See also: `configuration` and `dependencies`. And `setProp`, for the values that may
2923
+ * change while the app runs.
2924
+ */
2925
+ get environment() {
2926
+ return this._environment;
2927
+ }
2928
+ /**
2929
+ * The configuration of the app (feature flags and other configuration values), created by
2930
+ * the `configuration` factory given to the store constructor, or `undefined`. It's meant to
2931
+ * be immutable. Typed `unknown`: declare a typed getter in your base action, like
2932
+ * `get config() { return this.store.configuration as Config; }`. In components, use
2933
+ * `useConfiguration()`.
2934
+ *
2935
+ * `store.dispose()` disposes it, if it has a `[Symbol.asyncDispose]()`, `[Symbol.dispose]()`
2936
+ * or `dispose()` method. `logOut` keeps it.
2937
+ *
2938
+ * See also: `environment` and `dependencies`.
2939
+ */
2940
+ get configuration() {
2941
+ return this._configuration;
2942
+ }
2943
+ /**
2944
+ * The dependencies of the app (services, repositories, API clients, etc), created by the
2945
+ * `dependencies` factory given to the store constructor, or `undefined`. They belong to the
2946
+ * store: each test creates its own store with its own dependencies. Typed `unknown`: declare
2947
+ * a typed getter in your base action, like
2948
+ * `get deps() { return this.store.dependencies as Dependencies; }`. Components should
2949
+ * usually not need them.
2950
+ *
2951
+ * `store.dispose()` disposes them, if they have a `[Symbol.asyncDispose]()`,
2952
+ * `[Symbol.dispose]()` or `dispose()` method. `logOut` keeps them, since they belong to the
2953
+ * app, and not to the user.
2954
+ *
2955
+ * See also: `environment` and `configuration`. And `mocks`, which mocks actions, while the
2956
+ * dependencies mock services.
2957
+ */
2958
+ get dependencies() {
2959
+ return this._dependencies;
2960
+ }
2961
+ /**
2962
+ * Internal: Disposes the dependencies or the configuration, when they have a
2963
+ * `[Symbol.asyncDispose]()`, `[Symbol.dispose]()` or `dispose()` method. Returns a promise
2964
+ * if the disposal is async, or `null`. Neither throws nor rejects: the errors are reported
2965
+ * with `_reportDisposeError`.
2966
+ */
2967
+ _disposeInjected(value, description) {
2968
+ if (value === null || typeof value !== 'object')
2969
+ return null;
2970
+ const v = value;
2971
+ const what = `Disposing ${description} threw an error`;
2972
+ let result;
2973
+ try {
2974
+ const bySymbol = Store._disposeBySymbol(v);
2975
+ if (bySymbol !== null)
2976
+ result = bySymbol.result;
2977
+ else if (typeof v.dispose === 'function')
2978
+ result = v.dispose();
2979
+ else
2980
+ return null;
2981
+ }
2982
+ catch (error) {
2983
+ this._reportDisposeError(error, what);
2984
+ return null;
2985
+ }
2986
+ if (!Store._isPromiseLike(result))
2987
+ return null;
2988
+ return Promise.resolve(result).then(() => undefined, (error) => this._reportDisposeError(error, what));
2989
+ }
2990
+ // ----------------------------------------------------------------------------------------------
2991
+ // Store props.
2992
+ // ----------------------------------------------------------------------------------------------
2993
+ /**
2994
+ * Sets a prop in the store. The props hold the long-lived things of the app that are not
2995
+ * state, and must not go in the state: intervals and timeouts, WebSockets, `EventSource`s,
2996
+ * `AbortController`s, listeners (like Firebase's `onSnapshot`, which returns an unsubscribe
2997
+ * function), RxJS subscriptions. The props belong to the store, so that each test, or each
2998
+ * request in server-side rendering, has its own, and so that they can all be closed at
2999
+ * once, with `store.dispose()` (when the app finishes, or at the end of each test), or
3000
+ * with `disposeProps()` and `logOut({ disposeProps: true })`.
3001
+ *
3002
+ * The `key` can be any value. Keys are compared by identity, like the keys of a `Map`, so
3003
+ * equal strings are the same key, but two different objects are not. Read the prop with
3004
+ * `prop(key)`, and remove it with `disposeProp(key)`, which also disposes its value.
3005
+ *
3006
+ * Setting a prop with a key that already exists replaces its value, and disposes the previous
3007
+ * value (if it's a different one), so that dispatching a "start" action twice doesn't leak the
3008
+ * first timer or listener. Setting the same value again only updates its `dispose` option.
3009
+ *
3010
+ * This is also available in actions, as `this.setProp()`:
3011
+ *
3012
+ * ```ts
3013
+ * class StartClock extends Action {
3014
+ * reduce() {
3015
+ * const interval = setInterval(() => this.dispatch(new Tick()), 1000);
3016
+ * this.setProp('clock', interval, { dispose: clearInterval });
3017
+ * return null;
3018
+ * }
3019
+ * }
3020
+ *
3021
+ * class StopClock extends Action {
3022
+ * reduce() {
3023
+ * this.disposeProp('clock');
3024
+ * return null;
3025
+ * }
3026
+ * }
3027
+ * ```
3028
+ *
3029
+ * How a prop is disposed, in order:
3030
+ *
3031
+ * 1. The `dispose` option given to `setProp`, if any, which gets the value.
3032
+ * 2. The value's `[Symbol.asyncDispose]()` or `[Symbol.dispose]()` method (TC39 explicit
3033
+ * resource management, supported by TypeScript's `using`).
3034
+ * 3. An `AbortController` is aborted.
3035
+ * 4. A `WebSocket`, `EventSource`, `BroadcastChannel` or `MessagePort` is closed, and a
3036
+ * `Worker` is terminated.
3037
+ * 5. An object with an `unsubscribe()` method (like an RxJS subscription) is unsubscribed.
3038
+ * 6. Otherwise, the value can't be disposed, and it's only removed from the props.
3039
+ *
3040
+ * Note:
3041
+ * - Timers need the `dispose` option, since in browsers `setTimeout` and `setInterval` return
3042
+ * numbers, which can't be told apart from other numbers. Use `{ dispose: clearInterval }` or
3043
+ * `{ dispose: clearTimeout }`.
3044
+ * - Functions are not called automatically, since an unsubscribe function looks the same as a
3045
+ * callback kept in a prop. Use `{ dispose: (unsubscribe) => unsubscribe() }`.
3046
+ * - Promises can't be cancelled, so they're only removed. Keep an `AbortController` in a prop
3047
+ * to cancel the work.
3048
+ * - A `dispose` that throws, or returns a promise that rejects, doesn't stop the other props
3049
+ * from being disposed. The error is given to the `errorObserver` (with a `null` action),
3050
+ * and if there is none, or if it returns an error, the error is logged.
3051
+ * - After `store.dispose()`, a prop that is set (for example, by an async action that was
3052
+ * still running) is disposed right away, and not kept.
3053
+ *
3054
+ * See also: `prop`, `props`, `disposeProp`, `disposeProps` and `dispose`.
3055
+ */
3056
+ setProp(key, value, options) {
3057
+ const dispose = options?.dispose;
3058
+ // A disposed store doesn't keep props, so that they don't leak.
3059
+ if (this._disposed) {
3060
+ Store._logLazy(() => `The prop ${Store._describeKey(key)} was set after the store was disposed, ` +
3061
+ `so its value was disposed right away, and not kept.`);
3062
+ void this._disposeValue(key, value, dispose);
3063
+ return;
3064
+ }
3065
+ const hadKey = this._props.has(key);
3066
+ const previous = this._props.get(key);
3067
+ const previousDispose = this._propDisposers.get(key);
3068
+ this._props.set(key, value);
3069
+ if (dispose !== undefined)
3070
+ this._propDisposers.set(key, dispose);
3071
+ else
3072
+ this._propDisposers.delete(key);
3073
+ // Replacing a value disposes the previous one, so that it doesn't leak. This is done after
3074
+ // the new value is in place, in case the disposal reads the props.
3075
+ if (hadKey && !Object.is(previous, value))
3076
+ void this._disposeValue(key, previous, previousDispose);
3077
+ }
3078
+ /**
3079
+ * Returns the prop with the given key, or `undefined` if there is none. See `setProp`.
3080
+ *
3081
+ * Give it the type of the value: `const interval = store.prop<number>('clock')`.
3082
+ *
3083
+ * This is also available in actions, as `this.prop()`.
3084
+ */
3085
+ prop(key) {
3086
+ return this._props.get(key);
3087
+ }
3088
+ /**
3089
+ * All the props of the store (see `setProp`), with their keys and values, in the order they
3090
+ * were set. It's a read-only view: use `setProp`, `disposeProp` and `disposeProps` to change
3091
+ * them. Useful in tests.
3092
+ *
3093
+ * This is also available in actions, as `this.props`.
3094
+ */
3095
+ get props() {
3096
+ return this._props;
3097
+ }
3098
+ /**
3099
+ * Disposes the prop with the given key, and removes it from the props. See `setProp` for
3100
+ * how the value is disposed. Does nothing if there is no prop with that key.
3101
+ *
3102
+ * It doesn't wait for an async disposal (one that returns a promise) to finish. If that
3103
+ * disposal fails, the error is given to the `errorObserver` (with a `null` action), or logged.
3104
+ * Use `store.dispose()` to wait for all the async disposals.
3105
+ *
3106
+ * This is also available in actions, as `this.disposeProp()`.
3107
+ *
3108
+ * ```ts
3109
+ * class StopClock extends Action {
3110
+ * reduce() {
3111
+ * this.disposeProp('clock');
3112
+ * return null;
3113
+ * }
3114
+ * }
3115
+ * ```
3116
+ */
3117
+ disposeProp(key) {
3118
+ if (!this._props.has(key))
3119
+ return;
3120
+ const value = this._props.get(key);
3121
+ const dispose = this._propDisposers.get(key);
3122
+ this._props.delete(key);
3123
+ this._propDisposers.delete(key);
3124
+ void this._disposeValue(key, value, dispose);
3125
+ }
3126
+ /**
3127
+ * Disposes the props, and removes them from the props. See `setProp` for how the values are
3128
+ * disposed. The values that can't be disposed are only removed.
3129
+ *
3130
+ * - Without a `predicate`, all the props are disposed and removed.
3131
+ * - With a `predicate`, it's called with the key and the value of each prop, and only the
3132
+ * props for which it returns `true` are disposed and removed. The others are kept, and not
3133
+ * disposed.
3134
+ *
3135
+ * The props are disposed in the order they were set. A disposal that throws doesn't stop the
3136
+ * others. It doesn't wait for the async disposals (the ones that return a promise) to finish.
3137
+ * Use `store.dispose()` to wait for them.
3138
+ *
3139
+ * A `predicate` that throws for a prop is treated like a disposal that throws: the error is
3140
+ * given to the `errorObserver` (or logged), the prop is kept, and the other props are still
3141
+ * disposed. This method never throws.
3142
+ *
3143
+ * This is also available in actions, as `this.disposeProps()`.
3144
+ *
3145
+ * ```ts
3146
+ * // Disposes all props.
3147
+ * store.disposeProps();
3148
+ *
3149
+ * // Disposes only the props whose key starts with 'user'.
3150
+ * store.disposeProps((key, value) => String(key).startsWith('user'));
3151
+ * ```
3152
+ *
3153
+ * See also: `disposeProp`, to dispose a single prop by its key, and `logOut`, which can
3154
+ * dispose the props with its `disposeProps` option.
3155
+ */
3156
+ disposeProps(predicate) {
3157
+ void this._disposeProps(predicate);
3158
+ }
3159
+ /**
3160
+ * Internal: Disposes the selected props (all of them, without a predicate), and returns a
3161
+ * promise that resolves when their async disposals finish. It never rejects: the errors are
3162
+ * reported with `_reportDisposeError`.
3163
+ */
3164
+ _disposeProps(predicate) {
3165
+ const promises = [];
3166
+ // A snapshot, since a disposal may set or dispose other props.
3167
+ for (const [key, value] of [...this._props.entries()]) {
3168
+ // Skips a prop that was disposed, or replaced, by an earlier disposal.
3169
+ if (!this._props.has(key) || !Object.is(this._props.get(key), value))
3170
+ continue;
3171
+ // A predicate that throws is reported, and the prop is kept, as if it returned false.
3172
+ if (predicate !== undefined) {
3173
+ let selected;
3174
+ try {
3175
+ selected = predicate(key, value);
3176
+ }
3177
+ catch (error) {
3178
+ this._reportDisposeError(error, `The disposeProps predicate threw an error for the prop ${Store._describeKey(key)}, which was kept`);
3179
+ continue;
3180
+ }
3181
+ if (!selected)
3182
+ continue;
3183
+ }
3184
+ const dispose = this._propDisposers.get(key);
3185
+ this._props.delete(key);
3186
+ this._propDisposers.delete(key);
3187
+ const promise = this._disposeValue(key, value, dispose);
3188
+ if (promise !== null)
3189
+ promises.push(promise);
3190
+ }
3191
+ return (promises.length === 0) ? Promise.resolve() : Promise.all(promises).then(() => undefined);
3192
+ }
3193
+ /**
3194
+ * Internal: Disposes the value of a prop, as described in `setProp`. Returns a promise if the
3195
+ * disposal is async, or `null`. Neither throws nor rejects: the errors are reported with
3196
+ * `_reportDisposeError`.
3197
+ */
3198
+ _disposeValue(key, value, dispose) {
3199
+ const what = `Disposing the prop ${Store._describeKey(key)} threw an error`;
3200
+ let result;
3201
+ try {
3202
+ if (dispose !== undefined)
3203
+ result = dispose(value);
3204
+ else
3205
+ result = Store._disposeByType(value);
3206
+ }
3207
+ catch (error) {
3208
+ this._reportDisposeError(error, what);
3209
+ return null;
3210
+ }
3211
+ if (!Store._isPromiseLike(result))
3212
+ return null;
3213
+ return Promise.resolve(result).then(() => undefined, (error) => this._reportDisposeError(error, what));
3214
+ }
3215
+ /**
3216
+ * Internal: Disposes the value with the TC39 explicit resource management protocol, if it
3217
+ * has a `[Symbol.asyncDispose]()` or `[Symbol.dispose]()` method, and returns the result of
3218
+ * the disposal (a promise, if it's async), wrapped. Returns `null` if it has neither method.
3219
+ * The wrapper is needed because a disposal may legitimately return `undefined`.
3220
+ */
3221
+ static _disposeBySymbol(v) {
3222
+ if (typeof Symbol.asyncDispose === 'symbol' && typeof v[Symbol.asyncDispose] === 'function')
3223
+ return { result: v[Symbol.asyncDispose]() };
3224
+ if (typeof Symbol.dispose === 'symbol' && typeof v[Symbol.dispose] === 'function')
3225
+ return { result: v[Symbol.dispose]() };
3226
+ return null;
3227
+ }
3228
+ /**
3229
+ * Internal: Disposes the value by its type (steps 2 to 5 of `setProp`), and returns the
3230
+ * result of the disposal (a promise, if it's async). Returns `undefined` if the value can't
3231
+ * be disposed.
3232
+ */
3233
+ static _disposeByType(value) {
3234
+ if (value === null || typeof value !== 'object')
3235
+ return undefined;
3236
+ const v = value;
3237
+ // TC39 explicit resource management.
3238
+ const bySymbol = Store._disposeBySymbol(v);
3239
+ if (bySymbol !== null)
3240
+ return bySymbol.result;
3241
+ // Browser and Node types. Each global may not exist in the runtime.
3242
+ if (Store._isInstanceOfGlobal(v, 'AbortController'))
3243
+ return v.abort();
3244
+ if (Store._isInstanceOfGlobal(v, 'WebSocket')
3245
+ || Store._isInstanceOfGlobal(v, 'EventSource')
3246
+ || Store._isInstanceOfGlobal(v, 'BroadcastChannel')
3247
+ || Store._isInstanceOfGlobal(v, 'MessagePort'))
3248
+ return v.close();
3249
+ if (Store._isInstanceOfGlobal(v, 'Worker'))
3250
+ return v.terminate();
3251
+ // RxJS subscriptions, and others.
3252
+ if (typeof v.unsubscribe === 'function')
3253
+ return v.unsubscribe();
3254
+ return undefined;
3255
+ }
3256
+ // True if the global class with the given name exists in the runtime, and the value is an
3257
+ // instance of it.
3258
+ static _isInstanceOfGlobal(value, name) {
3259
+ const type = globalThis[name];
3260
+ return typeof type === 'function' && value instanceof type;
3261
+ }
3262
+ static _isPromiseLike(value) {
3263
+ return value !== null && (typeof value === 'object' || typeof value === 'function')
3264
+ && typeof value.then === 'function';
3265
+ }
3266
+ // Reports an error of the disposal of the props (a prop, or the disposeProps predicate), of
3267
+ // the dependencies, or of the configuration: to the `errorObserver` (with a `null` action), if
3268
+ // there is one. If it returns an error (or there is no observer), the error is logged. Never
3269
+ // throws: the error may not be convertible to a string (a Symbol, or an object whose
3270
+ // `toString` throws), so it's described with `_describeValue`. The `what` is the start of the
3271
+ // log message, like `Disposing the prop 'clock' threw an error`.
3272
+ _reportDisposeError(error, what) {
3273
+ if (this._errorObserver) {
3274
+ error = this._observeError(error, error, null);
3275
+ if (error === null)
3276
+ return;
3277
+ }
3278
+ Store._logLazy(() => `${what}: ${Store._describeValue(error)}. ` +
3279
+ `The error was ignored, and the other disposals were still done.`);
3280
+ }
3281
+ // Describes a prop key for log messages. Never throws.
3282
+ static _describeKey(key) {
3283
+ return (typeof key === 'string') ? `'${key}'` : Store._describeValue(key);
3284
+ }
3285
+ // ----------------------------------------------------------------------------------------------
3286
+ // Server-side rendering: merging the server-loaded state of a route.
3287
+ // ----------------------------------------------------------------------------------------------
3288
+ /**
3289
+ * Merges a slice of state, loaded on the server for a route, into the store state,
3290
+ * synchronously, by dispatching a `MergeServerStateAction`. In a server-rendered app with
3291
+ * several routes, each route's server code loads its own data (a server component in the
3292
+ * Next.js app router, `getServerSideProps` in the pages router, a loader in Remix), and the
3293
+ * `StoreSlice` component gives it to the store with this method, on the server and on the
3294
+ * client, so that the HTML shows it, hydration matches, and client-side navigation shows the
3295
+ * new route's data in its first render. See "Server-side rendering" in the README.
3296
+ *
3297
+ * How the slice is merged: the `mergeServerState` option of the constructor, or, without it,
3298
+ * a shallow merge for plain-object states (`{ ...state, ...slice }`). When nothing changes,
3299
+ * the state is kept (same reference), and nothing is published.
3300
+ *
3301
+ * The server data wins: a field in the slice replaces the field in the state, even if the
3302
+ * client changed it. To keep client fields, use the `mergeServerState` option.
3303
+ *
3304
+ * Before the store is ready (a persistor still reading the persisted state), the slice is
3305
+ * merged right away, and merged again into the persisted state when it arrives, so that the
3306
+ * route's server data is not lost. The persistor may persist the merged state.
3307
+ */
3308
+ mergeServerState(slice) {
3309
+ this._mergeServerState(slice);
3310
+ }
3311
+ /**
3312
+ * Internal: like `mergeServerState`, but doesn't publish the state change. Returns a function
3313
+ * that publishes it. For `StoreSlice`, which merges while React renders it (the children
3314
+ * must read the merged state in the same render), and publishes after the commit, since
3315
+ * publishing during a render would make React warn about updating other components.
3316
+ * @internal
3317
+ */
3318
+ _mergeServerStateSilently(slice) {
3319
+ return this._notificationBatch.suspend(() => this._mergeServerState(slice));
3320
+ }
3321
+ _mergeServerState(slice) {
3322
+ const pp = this._processPersistence;
3323
+ if (pp !== null && !pp.isReady)
3324
+ this._pendingServerSlices.push(slice);
3325
+ this._applyingServerSlice = true;
3326
+ try {
3327
+ this.dispatchSync(new MergeServerStateAction(slice));
3328
+ }
3329
+ finally {
3330
+ this._applyingServerSlice = false;
3331
+ }
3332
+ }
3333
+ /**
3334
+ * Internal: merges a slice into a state, with the `mergeServerState` option of the
3335
+ * constructor, or with the default shallow merge. Used by `MergeServerStateAction` (for the
3336
+ * store state) and by `StoreSlice` (for the server state of its subtree).
3337
+ * @internal
3338
+ */
3339
+ _mergeSlice(state, slice) {
3340
+ if (this._mergeServerStateFn !== undefined)
3341
+ return this._mergeServerStateFn(state, slice);
3342
+ if (!isPlainObject(state) || !isPlainObject(slice))
3343
+ throw new StoreException(`Cannot merge the server state slice ${describeValue(slice)} into the state: the default merge is a ` +
3344
+ `shallow merge of plain objects, and the state (or the slice) is not a plain object. Give ` +
3345
+ `createStore the \`mergeServerState\` option, with how to merge a slice into your state.`);
3346
+ const current = state;
3347
+ for (const key of Object.keys(slice)) {
3348
+ if (!Object.is(current[key], slice[key]))
3349
+ return { ...current, ...slice };
3350
+ }
3351
+ return state;
3352
+ }
3353
+ /**
3354
+ * Internal: merges the slices merged before the store was ready into the persisted state,
3355
+ * which replaces the store state. Called by `ProcessPersistence`.
3356
+ * @internal
3357
+ */
3358
+ _applyPendingServerSlices(persistedState) {
3359
+ let state = persistedState;
3360
+ for (const slice of this._pendingServerSlices)
3361
+ state = this._mergeSlice(state, slice);
3362
+ return state;
3363
+ }
3364
+ // ----------------------------------------------------------------------------------------------
3365
+ // Disposing the store.
3366
+ // ----------------------------------------------------------------------------------------------
3367
+ /**
3368
+ * True after `dispose()` was called. A disposed store doesn't accept new actions, and
3369
+ * doesn't keep new props.
3370
+ */
3371
+ // True if the store was created with the `server` option. See `isServer`.
3372
+ _isServer;
3373
+ /**
3374
+ * True if the store was created with `server: true` (see the `server` option in
3375
+ * `createStore`): it's the store that loads the data of a request, in server-side rendering.
3376
+ * In actions, `this.store.isServer` lets you skip client-only work on the server, for example
3377
+ * not opening a WebSocket, or not starting an interval with `setProp`. It's `false` by
3378
+ * default, and in the store the components use.
3379
+ */
3380
+ get isServer() {
3381
+ return this._isServer;
3382
+ }
3383
+ get isDisposed() {
3384
+ return this._disposed;
3385
+ }
3386
+ /**
3387
+ * Ends the store, for tests and app shutdown:
3388
+ *
3389
+ * ```ts
3390
+ * afterEach(() => store.dispose());
3391
+ * ```
3392
+ *
3393
+ * It does the following, in order:
3394
+ *
3395
+ * 1. Shuts down the store (`setShutDown(true)`), so that the actions dispatched from now on
3396
+ * are aborted. This also calls `clearInternalActionProps()`, which stops the polling, the
3397
+ * retries, the debounce timers, the sequential queues, and the other action features.
3398
+ * 2. Cancels the `dispatchWhen`s that are still waiting, so their actions are not dispatched,
3399
+ * and their `onTimeout` is not called. The `waitCondition`s, `waitActionCondition`s,
3400
+ * `waitAllActions`s and the other waits still pending are rejected with an
3401
+ * `AbortDispatchException`, and their timeouts are cancelled, so that no timer is left
3402
+ * behind. Inside an action, this aborts the action. Elsewhere, catch the rejection, or
3403
+ * don't dispose the store while you still wait for it.
3404
+ * 3. Pauses the persistor, and cancels its pending save (a state change waiting for the
3405
+ * throttle). A save that is already running still finishes. If you want the current state
3406
+ * saved first, call `await store.persistAndPause()` before.
3407
+ * 4. Stops listening to the focus and online sources (see `focusSource` and `onlineSource`
3408
+ * in the constructor), if they were started. `isFocused` and `isOnline` keep their last
3409
+ * values.
3410
+ * 5. Disposes all the props (see `setProp`), and removes them.
3411
+ * 6. Disposes the `dependencies`, and then the `configuration` (see the constructor), when
3412
+ * they have a `[Symbol.asyncDispose]()`, `[Symbol.dispose]()` or `dispose()` method. They
3413
+ * can still be read from the store after that.
3414
+ *
3415
+ * The returned promise resolves when the async disposals finish. It never rejects: a
3416
+ * disposal that fails is given to the `errorObserver`, or logged, and the other disposals
3417
+ * are still done.
3418
+ *
3419
+ * The store can't be used again: `setShutDown(false)` doesn't turn it back on, and a prop
3420
+ * set after it is disposed right away. Calling `dispose()` again does nothing. Note the
3421
+ * actions that are already running still finish, and may still change the state.
3422
+ *
3423
+ * The store also implements `[Symbol.dispose]` and `[Symbol.asyncDispose]`, so that tests
3424
+ * can use TypeScript's explicit resource management: `await using store = createStore(...)`.
3425
+ */
3426
+ async dispose() {
3427
+ if (this._disposed)
3428
+ return;
3429
+ this._disposed = true;
3430
+ this.setShutDown(true);
3431
+ this._cancelAllDispatchWhen();
3432
+ this._abortAllWaits();
3433
+ this._processPersistence?.dispose();
3434
+ this._focus.dispose();
3435
+ this._online.dispose();
3436
+ await this._disposeProps();
3437
+ await this._disposeInjected(this._dependencies, 'the dependencies');
3438
+ await this._disposeInjected(this._configuration, 'the configuration');
3439
+ }
3440
+ /**
3441
+ * Function `Store.describeStateChange()` returns a string describing only the differences between
3442
+ * two given objects.
3443
+ *
3444
+ * By default, when `logStateChanges` is set to `true` in the Store constructor, function
3445
+ * `describeStateChange` is used together with `Store.log()` to print all state changes to
3446
+ * the console. Note you should turn this off in production.
3447
+ *
3448
+ * The values can be of any type, including primitives (for a state that is a number or a
3449
+ * string), and objects with `Date`, `Map` and `Set` fields:
3450
+ *
3451
+ * ```ts
3452
+ * Store.describeStateChange(0, 1); // 'State: 0 → 1; '
3453
+ * Store.describeStateChange({ user: { name: 'Ann' } }, { user: { name: 'Bob' } }); // 'State user.name: Ann → Bob; '
3454
+ * Store.describeStateChange({ prices: new Map([['IBM', 1]]) }, { prices: new Map([['IBM', 2]]) }); // 'State prices[IBM]: 1 → 2; '
3455
+ * ```
3456
+ */
3457
+ static describeStateChange(obj1, obj2, path = '') {
3458
+ if (obj1 === obj2)
3459
+ return '';
3460
+ const describeChange = () => `State${path === '' ? '' : ' ' + path}: ${Store._describeValue(obj1)} → ${Store._describeValue(obj2)}; `;
3461
+ // Primitives, null, or an object that replaced a primitive (or the other way around).
3462
+ if (!Store._isObject(obj1) || !Store._isObject(obj2))
3463
+ return Object.is(obj1, obj2) ? '' : describeChange();
3464
+ // Dates and sets have no keys, so they are compared by their contents.
3465
+ if (obj1 instanceof Date || obj2 instanceof Date) {
3466
+ const isSameDate = (obj1 instanceof Date) && (obj2 instanceof Date) && Object.is(obj1.getTime(), obj2.getTime());
3467
+ return isSameDate ? '' : describeChange();
3468
+ }
3469
+ if (obj1 instanceof Set || obj2 instanceof Set) {
3470
+ const isSameSet = (obj1 instanceof Set) && (obj2 instanceof Set) && (obj1.size === obj2.size)
3471
+ && [...obj1].every(value => obj2.has(value));
3472
+ return isSameSet ? '' : describeChange();
3473
+ }
3474
+ // Maps are compared by their entries, like objects are compared by their keys.
3475
+ if (obj1 instanceof Map || obj2 instanceof Map) {
3476
+ if (!(obj1 instanceof Map) || !(obj2 instanceof Map))
3477
+ return describeChange();
3478
+ let differences = '';
3479
+ for (const key of new Set([...obj1.keys(), ...obj2.keys()]))
3480
+ differences += Store.describeStateChange(obj1.get(key), obj2.get(key), `${path}[${Store._describeValue(key)}]`);
3481
+ return differences;
3482
+ }
3483
+ let differences = '';
3484
+ // Combine keys from both objects
3485
+ const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
3486
+ for (const key of allKeys) {
3487
+ const newPath = path === '' ? key : `${path}.${key}`;
3488
+ differences += Store.describeStateChange(obj1[key], obj2[key], newPath);
3489
+ }
3490
+ return differences;
3491
+ }
3492
+ static _isObject(value) {
3493
+ return typeof value === 'object' && value !== null;
3494
+ }
3495
+ // Describes a value for `describeStateChange`. Note this method should not fail.
3496
+ static _describeValue(value) {
3497
+ try {
3498
+ if (value instanceof Date)
3499
+ return isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString();
3500
+ if (value instanceof Set)
3501
+ return `Set{${[...value].map(v => Store._describeValue(v)).join(', ')}}`;
3502
+ if (value instanceof Map)
3503
+ return `Map{${[...value].map(([k, v]) => `${Store._describeValue(k)}: ${Store._describeValue(v)}`).join(', ')}}`;
3504
+ return String(value);
3505
+ }
3506
+ catch {
3507
+ // For example, an object with no prototype has no `toString`.
3508
+ return Object.prototype.toString.call(value);
3509
+ }
3510
+ }
3511
+ /**
3512
+ * Call `logOut()` when you want to delete the persisted state, and return the store
3513
+ * state to the given initial-state. That's usually necessary when the user logs out
3514
+ * of your app, or the user deletes its account, so that another user may log in,
3515
+ * or start a new sign-up process.
3516
+ *
3517
+ * Note: If you know about any timers or async processes that you may have started,
3518
+ * you should stop/cancel them all before calling this method.
3519
+ *
3520
+ * You may opt to:
3521
+ *
3522
+ * - Wait for `throttle` milliseconds to make sure all async processes that the app may
3523
+ * have started have time to finish. The default `throttle` is 3000 milliseconds (3 seconds).
3524
+ *
3525
+ * - Wait for all actions currently running to finish, but wait at most `actionsThrottle`
3526
+ * milliseconds. If the actions are not finished by then, the state will be deleted anyway.
3527
+ * The default `actionsThrottle` is 6000 milliseconds (6 seconds). An `actionsThrottle` of
3528
+ * zero (or negative) doesn't wait for the actions at all. Note: If you call logOut from inside
3529
+ * an action, and wait for it, that action is still running, so logOut waits the full
3530
+ * `actionsThrottle` for it to finish.
3531
+ *
3532
+ * The actions dispatched before logOut belong to the previous user, so they can't change the
3533
+ * state of the next user. When one of them finishes, during or after logOut, it's aborted
3534
+ * (`status.isDispatchAborted`): its reducer's result is discarded, and its errors are ignored
3535
+ * (they don't go to `wrapError` or the `errorObserver`, and are not shown to the user). Errors
3536
+ * that point to a bug (`StoreException`) are still thrown. Also, the store doesn't accept the
3537
+ * actions they dispatch after logOut, with `this.dispatch`, `this.dispatchAndWait`,
3538
+ * `this.dispatchWhen`, and the others. This includes the `UpdateStateAction`s of the
3539
+ * optimistic actions (like `OptimisticCommand`), so they don't apply the server response,
3540
+ * roll back, or reload, after logOut. Note this means an action that calls logOut can't
3541
+ * change the state or dispatch actions after it. If you need that, call logOut from outside
3542
+ * of actions, and then dispatch the actions you need. Also note it can't undo what the
3543
+ * actions do outside the store, like calling the server, or saving to local storage.
3544
+ *
3545
+ * While logOut is running, the store doesn't accept new actions, and the persistor doesn't
3546
+ * persist anything but the initial-state. This includes the actions dispatched by the
3547
+ * `stateObserver` and the `actionObserver` when logOut changes the state to the
3548
+ * initial-state. Also, logOut cancels the `dispatchWhen`s that are still waiting, so their
3549
+ * actions are not dispatched, and their `onTimeout` is not called. If the app pauses the persistor (`pausePersistor`)
3550
+ * or shuts down the store (`setShutDown`), before or during logOut, they stay that way after
3551
+ * it. Note logOut deletes the persisted state, and persists the initial-state, even if the
3552
+ * persistor is paused.
3553
+ *
3554
+ * If the store has no persistor, logOut does the same, except deleting and persisting.
3555
+ *
3556
+ * The store state is always changed to the initial-state, even if deleting the persisted
3557
+ * state fails, and logOut then still tries to persist the initial-state. If deleting or
3558
+ * persisting fails, the error is given to the `errorObserver` (with a `null` action), so it
3559
+ * can be logged, and when logOut finishes, it rejects with the error. If both fail, it rejects
3560
+ * with the delete error. In this case, the old user's data may still be in the persistence,
3561
+ * so you should check if logOut rejected, and if so, tell the user it was not possible to log
3562
+ * out correctly. For example:
3563
+ *
3564
+ * ```ts
3565
+ * try {
3566
+ * await store.logOut({ initialState: AppState.initialState() });
3567
+ * goToLoginScreen();
3568
+ * } catch (error) {
3569
+ * goToLogOutFailedScreen(error);
3570
+ * }
3571
+ * ```
3572
+ *
3573
+ * Note the save errors are processed by `Persistor.wrapError` first, and if it returns `null`,
3574
+ * the save doesn't count as failed. The errors the persistor reports with `Persistor.addError`
3575
+ * are given to the `errorObserver` as usual, and don't make logOut reject.
3576
+ *
3577
+ * Throws a `StoreException` if called while the persisted state is still being read at
3578
+ * startup (before `store.ready()` resolves). In this case, nothing is changed.
3579
+ */
3580
+ async logOut({ initialState, throttle = 3000, actionsThrottle = 6000, disposeProps = false, }) {
3581
+ return this._logOut(this._processPersistence, initialState, throttle, actionsThrottle, disposeProps);
3582
+ }
3583
+ /**
3584
+ * For Kiss internal use only. Does the `logOut`, using the given persistence (if any).
3585
+ * @internal
3586
+ */
3587
+ async _logOut(persistence, initialState, throttle, actionsThrottle, disposeProps = false) {
3588
+ // Throws if the persisted state is still being read. In this case, nothing is changed.
3589
+ // Otherwise, the persistor doesn't start a new persistence process until logOut finishes.
3590
+ persistence?._startLogOut();
3591
+ // The store doesn't start any new actions until logOut finishes.
3592
+ this._logOutsRunning++;
3593
+ this.clearInternalActionProps();
3594
+ // The props of the previous user are disposed right away, so that their timers and
3595
+ // listeners stop. The async disposals are awaited below.
3596
+ const propsDisposal = (disposeProps === true) ? this._disposeProps()
3597
+ : (typeof disposeProps === 'function') ? this._disposeProps(disposeProps)
3598
+ : null;
3599
+ // The actions dispatched before this point belong to the previous user. When they finish,
3600
+ // their result is discarded, and the actions they dispatch are not accepted.
3601
+ this._logOutCount++;
3602
+ // The `dispatchWhen`s called before this point also belong to the previous user.
3603
+ this._cancelAllDispatchWhen();
3604
+ // The error logOut throws when it finishes, if deleting or persisting failed.
3605
+ let failure;
3606
+ try {
3607
+ // Waits for the async disposals of the props. Note it never rejects.
3608
+ if (propsDisposal !== null)
3609
+ await propsDisposal;
3610
+ // If the state is currently being persisted, we can't delete it right now.
3611
+ await persistence?._waitWhilePersisting();
3612
+ // Wait for the throttle period to finish.
3613
+ await new Promise(resolve => setTimeout(resolve, capTimeoutMillis(throttle)));
3614
+ // Wait for all actions currently running to finish,
3615
+ // but wait at most `actionsThrottle` milliseconds. Note that for `waitAllActions`, a
3616
+ // zero or negative timeout means "no timeout", so in this case we don't wait at all.
3617
+ if (actionsThrottle > 0) {
3618
+ await this.waitAllActions(null, {
3619
+ timeoutMillis: actionsThrottle,
3620
+ completeImmediately: true
3621
+ })
3622
+ .catch(() => {
3623
+ });
3624
+ }
3625
+ // Delete the old persisted state. If it fails, the error is given to the `errorObserver`,
3626
+ // and logOut goes on, so that the store state is still reset. It's thrown at the end.
3627
+ const deleteFailure = await persistence?._deleteLogOutState() ?? null;
3628
+ // Synchronously change the store state to the initial-state. This is done even if the
3629
+ // app shut down the store. Since a logOut is running, this doesn't start a persistence process.
3630
+ this._isApplyingLogOutState = true;
3631
+ try {
3632
+ this.dispatchSync(new UpdateStateAction(() => initialState));
3633
+ }
3634
+ finally {
3635
+ this._isApplyingLogOutState = false;
3636
+ }
3637
+ // Persist the new initial-state. Even if deleting failed, since this may overwrite the old
3638
+ // persisted state. If it fails, the error is given to the `errorObserver`.
3639
+ const persistFailure = await persistence?._persistLogOutState(initialState) ?? null;
3640
+ // If both failed, the delete error is thrown, since the old persisted state may be there.
3641
+ failure = deleteFailure ?? persistFailure;
3642
+ }
3643
+ //
3644
+ finally {
3645
+ // The store accepts new actions again, unless the app shut it down.
3646
+ this._logOutsRunning--;
3647
+ // Persistence resumes, unless the app paused the persistor.
3648
+ persistence?._endLogOut();
3649
+ }
3650
+ if (failure !== null)
3651
+ throw failure.error;
3652
+ }
3653
+ /**
3654
+ * Pause the Persistor temporarily.
3655
+ *
3656
+ * When pausePersistor is called, the Persistor will not start a new persistence process, until method
3657
+ * resumePersistor is called. This will not affect the current persistence process, if one is currently
3658
+ * running.
3659
+ *
3660
+ * Note: A persistence process starts when the Persistor.persistDifference method is called,
3661
+ * and finishes when the promise returned by that method completes.
3662
+ */
3663
+ pausePersistor() {
3664
+ this._processPersistence?.pause();
3665
+ }
3666
+ /**
3667
+ * Persists the current state (if it's not yet persisted), then pauses the Persistor temporarily.
3668
+ *
3669
+ * When persistAndPausePersistor is called while the persisted state is still being read,
3670
+ * while a `logOut` is running, or while a persistence process is running, it waits for them
3671
+ * to finish. Note logOut persists its initial-state, and the state of the previous user is
3672
+ * never persisted while logOut is running. Then, if the current
3673
+ * state is not yet persisted, it immediately starts a new persistence process (ignoring
3674
+ * Persistor.throttle). The returned promise completes when the current state is persisted.
3675
+ *
3676
+ * If the save fails, the returned promise still resolves. It never rejects. This is on
3677
+ * purpose, not a bug: this method is usually called when the app is shutting down or going to
3678
+ * the background, and then the app can't recover from a failed save anyway. The error is not
3679
+ * lost: it's given to the `errorObserver` (with a `null` action) before the promise
3680
+ * resolves, so it can be logged.
3681
+ *
3682
+ * Then, the Persistor will not start another persistence process, until method
3683
+ * resumePersistor is called.
3684
+ *
3685
+ * Note: A persistence process starts when the Persistor.persistDifference method is called,
3686
+ * and finishes when the promise returned by that method completes.
3687
+ */
3688
+ persistAndPausePersistor() {
3689
+ return this._processPersistence?.persistAndPause() ?? Promise.resolve();
3690
+ }
3691
+ /**
3692
+ * Resumes persistence by the Persistor,
3693
+ * after calling pausePersistor or persistAndPausePersistor.
3694
+ */
3695
+ resumePersistor() {
3696
+ this._processPersistence?.resume();
3697
+ }
3698
+ /**
3699
+ * Asks the Persistor to save the initialState in the local persistence.
3700
+ * If the save fails, this rejects, and nothing is considered persisted
3701
+ * (`getLastPersistedStateFromPersistor` returns `null`).
3702
+ *
3703
+ * If a save is running, it waits for it to finish first, so that it can't overwrite the
3704
+ * initialState later. State changes made meanwhile are saved after it finishes.
3705
+ */
3706
+ async saveInitialStateInPersistence(initialState) {
3707
+ return this._processPersistence?.saveInitialState(initialState);
3708
+ }
3709
+ /**
3710
+ * Asks the Persistor to read the state from the local persistence.
3711
+ * Important: If you use this, you MUST put this state into the store.
3712
+ * Kiss will assume that's the case, and will not work properly otherwise.
3713
+ *
3714
+ * If a save is running, it waits for it to finish first, so that it reads the saved state.
3715
+ * State changes made meanwhile are saved after the state is read.
3716
+ */
3717
+ async readStateFromPersistence() {
3718
+ return this._processPersistence?.readState() || null;
3719
+ }
3720
+ /**
3721
+ * Asks the Persistor to delete the saved state from the local persistence.
3722
+ *
3723
+ * If a save is running, it waits for it to finish first, so that it can't put the deleted
3724
+ * state back. State changes made meanwhile are saved after the state is deleted.
3725
+ */
3726
+ async deleteStateFromPersistence() {
3727
+ return this._processPersistence?.deleteState();
3728
+ }
3729
+ /**
3730
+ * Gets, from the Persistor, the last state that was saved to the local persistence.
3731
+ */
3732
+ getLastPersistedStateFromPersistor() {
3733
+ return this._processPersistence?.lastPersistedState ?? null;
3734
+ }
3735
+ /**
3736
+ * Returns a promise which will resolve when the given state `condition` is true.
3737
+ * If the condition is already true when the method is called, the promise resolves immediately.
3738
+ *
3739
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
3740
+ * is not met in `timeoutMillis` milliseconds, the promise rejects with a `TimeoutException`,
3741
+ * and the condition stops being checked. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
3742
+ * (or -1, or `Infinity`):
3743
+ *
3744
+ * ```ts
3745
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 }); // 1 second.
3746
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 0 }); // No timeout.
3747
+ * ```
3748
+ *
3749
+ * To handle the timeout, you can catch the `TimeoutException`:
3750
+ *
3751
+ * ```ts
3752
+ * try { await store.waitCondition(condition, { timeoutMillis: 5000 }); }
3753
+ * catch (error) { if (error instanceof TimeoutException) { ... } else throw error; }
3754
+ * ```
3755
+ *
3756
+ * Or, you can pass an `onTimeout` callback. If the timeout expires, `onTimeout` is called,
3757
+ * and the promise resolves with `null` instead of rejecting. If `onTimeout` throws, the
3758
+ * promise rejects with that error:
3759
+ *
3760
+ * ```ts
3761
+ * await store.waitCondition(condition, { timeoutMillis: 5000, onTimeout: () => { ... } });
3762
+ * ```
3763
+ *
3764
+ * This method is useful in tests, and it returns the action which changed
3765
+ * the store state into the condition, in case you need it:
3766
+ *
3767
+ * ```typescript
3768
+ * let action = await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
3769
+ * expect(action instanceof ChangeNameAction).toBe(true);
3770
+ * ```
3771
+ *
3772
+ * This method is also eventually useful in production code, but note that while it waits,
3773
+ * the condition runs on EVERY state change. A few short-lived waits are fine. But many waits,
3774
+ * or waits that may never complete (especially with no timeout), add a cost to every state
3775
+ * change, for as long as the store lives, since there is no way to cancel a wait. In
3776
+ * production, it's often better to put the logic in an action, or to react to the selected
3777
+ * state in your components.
3778
+ *
3779
+ * Examples:
3780
+ *
3781
+ * ```ts
3782
+ * // Dispatch actions and wait for the state change:
3783
+ * expect(store.state.user.isLoggedIn).toBe(false);
3784
+ * dispatch(new LogInUser("Mary"));
3785
+ * await store.waitCondition((state) => state.user.isLoggedIn, { timeoutMillis: 1000 });
3786
+ * expect(store.state.user.name).toBe("Mary");
3787
+ * ```
3788
+ *
3789
+ * If the condition throws, the returned promise rejects with that error, and the wait ends.
3790
+ * The action whose state change ran the condition is not affected: it still completes
3791
+ * normally, and `dispatch` doesn't throw.
3792
+ *
3793
+ * See also:
3794
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
3795
+ * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
3796
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
3797
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
3798
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
3799
+ */
3800
+ async waitCondition(condition, { timeoutMillis, onTimeout, }) {
3801
+ // If the condition is already met, return immediately.
3802
+ // Return `null` because there was no trigger action that changed the state into the condition.
3803
+ if (condition(this._state))
3804
+ return null;
3805
+ // Otherwise, create a Promise that resolves when the condition is met.
3806
+ else {
3807
+ return new Promise((resolve, reject) => {
3808
+ let cancelTimer = () => { };
3809
+ const entry = {
3810
+ check: condition,
3811
+ resolve: (triggerAction) => {
3812
+ // The condition was met, so the timeout is no longer needed.
3813
+ cancelTimer();
3814
+ resolve(triggerAction);
3815
+ },
3816
+ reject: (error) => {
3817
+ cancelTimer();
3818
+ reject(error);
3819
+ },
3820
+ };
3821
+ this._waitConditions.push(entry);
3822
+ if (timeoutMillis > 0) {
3823
+ cancelTimer = _setLongTimeout(() => {
3824
+ // Stop checking the condition, since nobody is waiting for it anymore.
3825
+ this._waitConditions = this._waitConditions.filter(c => c !== entry);
3826
+ _settleTimeout(timeoutMillis, onTimeout, () => resolve(null), reject);
3827
+ }, timeoutMillis);
3828
+ }
3829
+ });
3830
+ }
3831
+ }
3832
+ /**
3833
+ * Returns a Promise that resolves when some actions meet the given `condition`.
3834
+ *
3835
+ * If `completeImmediately` is false (the default), this method will throw an error if the
3836
+ * condition was already true when the method was called. Otherwise, the promise will complete
3837
+ * immediately and throw no error.
3838
+ *
3839
+ * The `condition` is a function that takes the set of actions "in progress", as well as an
3840
+ * action that just entered the set (by being dispatched) or left the set (by finishing
3841
+ * dispatching). The function should return `true` when the condition is met, and `false`
3842
+ * otherwise. For example:
3843
+ *
3844
+ * ```ts
3845
+ * let action = await store.waitActionCondition((actionsInProgress, triggerAction) => { ... });
3846
+ * ```
3847
+ *
3848
+ * Note: Each time the condition is checked, it gets a new copy of the actions in progress.
3849
+ * Changing that set doesn't affect the store, and the set doesn't change when other actions
3850
+ * are later dispatched or finish.
3851
+ *
3852
+ * You get back the set of the actions being dispatched that met the condition, as well as
3853
+ * the action that triggered the condition by being added or removed from the set.
3854
+ * The returned set is a copy, taken when the condition was met (or when it timed out),
3855
+ * so it doesn't change when other actions are later dispatched or finish. Changing it
3856
+ * doesn't affect the store.
3857
+ *
3858
+ * Note: The condition is only checked when some action is dispatched or finishes dispatching.
3859
+ * It's not checked every time action statuses change.
3860
+ *
3861
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
3862
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
3863
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
3864
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
3865
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
3866
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
3867
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
3868
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
3869
+ *
3870
+ * If the condition throws, the promise rejects with that error, and the wait ends.
3871
+ * The action that triggered the check is not affected.
3872
+ *
3873
+ * See also:
3874
+ * `waitCondition` - Waits until the state is in a given condition.
3875
+ * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
3876
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
3877
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
3878
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
3879
+ *
3880
+ * You should only use this method in tests.
3881
+ */
3882
+ async waitActionCondition(
3883
+ //
3884
+ /// The condition receives the current actions in progress, and the action that triggered the condition.
3885
+ condition, {
3886
+ // If `completeImmediately` is `false` (the default), this method will throw an error if the
3887
+ // condition is already true when the method is called. Otherwise, the promise will complete
3888
+ // immediately and throw no error.
3889
+ completeImmediately = false,
3890
+ //
3891
+ // Error message in case the condition was already true when the method was called,
3892
+ // and `completeImmediately` is false.
3893
+ completedErrorMessage = "Awaited action condition was already true",
3894
+ //
3895
+ // The maximum time to wait for the condition to be met. The default is 3 seconds.
3896
+ // To disable the timeout, make it 0 or -1.
3897
+ timeoutMillis = null,
3898
+ //
3899
+ // Called if the timeout expires. When given, the promise resolves (with no trigger
3900
+ // action) instead of rejecting with a `TimeoutException`.
3901
+ onTimeout, } = {}) {
3902
+ // The condition gets a new copy each time, so changing it doesn't affect the store.
3903
+ return this._waitActionCondition((actions, triggerAction) => condition(new PrintableSet(actions), triggerAction), { completeImmediately, completedErrorMessage, timeoutMillis, onTimeout });
3904
+ }
3905
+ // Same as `waitActionCondition`, but the condition gets the store's own set of actions in
3906
+ // progress, instead of a copy. Only for conditions written in Kiss, which don't change the set.
3907
+ async _waitActionCondition(condition, { completeImmediately = false, completedErrorMessage = "Awaited action condition was already true", timeoutMillis = null, onTimeout, } = {}) {
3908
+ // If the condition is already true when `waitActionCondition` is called,
3909
+ if (condition(this._actionsInProgress, null)) {
3910
+ // Complete and return the actions in progress and the trigger action.
3911
+ if (completeImmediately)
3912
+ return Promise.resolve({ actions: this.actionsInProgress(), triggerAction: null });
3913
+ // else throw an error.
3914
+ else
3915
+ throw new StoreException(completedErrorMessage + ", and the promise completed immediately.");
3916
+ }
3917
+ //
3918
+ else {
3919
+ return new Promise((resolve, reject) => {
3920
+ let cancelTimer = () => { };
3921
+ const entry = {
3922
+ check: (actions, triggerAction) => condition(actions, triggerAction),
3923
+ resolve: (actions, triggerAction) => {
3924
+ // The condition was met, so the timeout is no longer needed.
3925
+ cancelTimer();
3926
+ resolve({ actions, triggerAction: triggerAction });
3927
+ },
3928
+ reject: (error) => {
3929
+ cancelTimer();
3930
+ reject(error);
3931
+ },
3932
+ };
3933
+ this._waitActionConditions.push(entry);
3934
+ timeoutMillis ??= TimeoutException.defaultTimeoutMillis;
3935
+ if (timeoutMillis > 0) {
3936
+ cancelTimer = _setLongTimeout(() => {
3937
+ // Stop checking the condition, since nobody is waiting for it anymore.
3938
+ this._waitActionConditions = this._waitActionConditions.filter(c => c !== entry);
3939
+ _settleTimeout(timeoutMillis, onTimeout, () => resolve({ actions: this.actionsInProgress(), triggerAction: null }), reject);
3940
+ }, timeoutMillis);
3941
+ }
3942
+ });
3943
+ }
3944
+ }
3945
+ /**
3946
+ * Returns a promise that resolves when ALL given actions finished dispatching.
3947
+ *
3948
+ * If `completeImmediately` is false (the default), this method will throw an error if none
3949
+ * of the given actions are in progress when the method is called. Otherwise, the promise will
3950
+ * complete immediately and throw no error.
3951
+ *
3952
+ * However, if you don't provide any actions (empty list or `null`), the promise will complete
3953
+ * when ALL current actions in progress finish dispatching. In other words, when no actions are
3954
+ * currently in progress. In this case, if [completeImmediately] is `false`, the method will
3955
+ * throw an error if no actions are in progress when the method is called.
3956
+ *
3957
+ * Note: Waiting until no actions are in progress should only be done in test, never in
3958
+ * production, as it's very easy to create a deadlock. However, waiting for specific actions to
3959
+ * finish is safe in production, as long as you're waiting for actions you just dispatched.
3960
+ *
3961
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
3962
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
3963
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
3964
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
3965
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
3966
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
3967
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
3968
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
3969
+ *
3970
+ * Examples:
3971
+ *
3972
+ * ```ts
3973
+ * // Dispatch actions in PARALLEL and wait until no actions are in progress.
3974
+ * expect(state.stocks).toEqual(['TSLA']);
3975
+ * dispatch(new BuyAction('IBM'));
3976
+ * dispatch(new SellAction('TSLA'));
3977
+ * await store.waitAllActions([]);
3978
+ * expect(state.stocks).toEqual(['IBM']);
3979
+ *
3980
+ * // Dispatch two actions in PARALLEL and wait for them to finish:
3981
+ * expect(state.stocks).toEqual(['TSLA']);
3982
+ * let action1 = new BuyAction('IBM');
3983
+ * let action2 = new SellAction('TSLA');
3984
+ * dispatch(action1);
3985
+ * dispatch(action2);
3986
+ * await store.waitAllActions([action1, action2]);
3987
+ * expect(state.stocks).toEqual(['IBM']);
3988
+ *
3989
+ * // This could also have been achieved by dispatching two actions in PARALLEL
3990
+ * // by using with `dispatchAndWaitAll` to wait for them:
3991
+ * expect(state.stocks).toEqual(['TSLA']);
3992
+ * await dispatchAndWaitAll([
3993
+ * new BuyAction('IBM'),
3994
+ * new SellAction('TSLA')
3995
+ * ]);
3996
+ * expect(state.stocks).toEqual(['IBM']);
3997
+ *
3998
+ * // This could also have been achieved by dispatching two actions in SERIES
3999
+ * // by using `dispatchAndWait` to wait for them:
4000
+ * expect(state.stocks).toEqual(['TSLA']);
4001
+ * await dispatchAndWait(new BuyAction('IBM'));
4002
+ * await dispatchAndWait(new SellAction('TSLA'));
4003
+ * expect(state.stocks).toEqual(['IBM']);
4004
+ * ```
4005
+ *
4006
+ * See also:
4007
+ * `waitCondition` - Waits until the state is in a given condition.
4008
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
4009
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
4010
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
4011
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
4012
+ *
4013
+ * You should only use this method in tests.
4014
+ */
4015
+ async waitAllActions(actions, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
4016
+ if (!actions || (actions.length === 0)) {
4017
+ return this._waitActionCondition((actions) => actions.size === 0, {
4018
+ completeImmediately: completeImmediately,
4019
+ completedErrorMessage: "No actions were in progress",
4020
+ timeoutMillis: timeoutMillis,
4021
+ onTimeout: onTimeout,
4022
+ });
4023
+ }
4024
+ else {
4025
+ return this._waitActionCondition((actionsInProgress) => {
4026
+ for (const action of actions) {
4027
+ if (actionsInProgress.has(action)) {
4028
+ return false;
4029
+ }
4030
+ }
4031
+ return true;
4032
+ }, {
4033
+ completeImmediately: completeImmediately,
4034
+ completedErrorMessage: "None of the given actions were in progress",
4035
+ timeoutMillis: timeoutMillis,
4036
+ onTimeout: onTimeout,
4037
+ });
4038
+ }
4039
+ }
4040
+ /**
4041
+ * Returns a promise that completes when an action of the given type in NOT in progress
4042
+ * (it's not being dispatched):
4043
+ *
4044
+ * - If NO action of the given type is currently in progress when the method is called,
4045
+ * and `completeImmediately` is false (the default), this method will throw an error.
4046
+ *
4047
+ * - If NO action of the given type is currently in progress when the method is called,
4048
+ * and `completeImmediately` is true, the promise completes immediately, returns `null`,
4049
+ * and throws no error.
4050
+ *
4051
+ * - If an action of the given type is in progress, the promise completes when the action
4052
+ * finishes, and returns the action. You can use the returned action to check its `status`:
4053
+ *
4054
+ * ```ts
4055
+ * let action = await store.waitActionType(MyAction);
4056
+ * expect(action?.status.originalError).toBeInstanceOf(UserException);
4057
+ * ```
4058
+ *
4059
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
4060
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
4061
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
4062
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
4063
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
4064
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
4065
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
4066
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
4067
+ *
4068
+ * Examples:
4069
+ *
4070
+ * ```ts
4071
+ * // Dispatches an action and waits until no action of its type is in progress.
4072
+ * dispatch(new ChangeNameAction('Bill'));
4073
+ * let action = await store.waitActionType(ChangeNameAction);
4074
+ * expect(action instanceof ChangeNameAction).toBe(true);
4075
+ * expect(action?.status.isCompletedOk).toBe(true);
4076
+ * expect(store.state.name).toBe('Bill');
4077
+ * ```
4078
+ *
4079
+ * See also:
4080
+ * `waitCondition` - Waits until the state is in a given condition.
4081
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
4082
+ * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
4083
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
4084
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
4085
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
4086
+ *
4087
+ * You should only use this method in tests.
4088
+ */
4089
+ async waitActionType(actionType, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
4090
+ const { triggerAction } = await this._waitActionCondition((actionsInProgress) => {
4091
+ return !(Array.from(actionsInProgress).some((action) => action.constructor === actionType));
4092
+ }, {
4093
+ completeImmediately: completeImmediately,
4094
+ completedErrorMessage: "No action of the given type was in progress",
4095
+ timeoutMillis: timeoutMillis,
4096
+ onTimeout: onTimeout,
4097
+ });
4098
+ return triggerAction;
4099
+ }
4100
+ /**
4101
+ * Returns a promise that completes when ALL actions of the given type are NOT in progress
4102
+ * (none of them is being dispatched):
4103
+ *
4104
+ * - If NO action of the given types is currently in progress when the method is called,
4105
+ * and `completeImmediately` is false (the default), this method will throw an error.
4106
+ *
4107
+ * - If NO action of the given type is currently in progress when the method is called,
4108
+ * and `completeImmediately` is true, the promise completes immediately and throws no error.
4109
+ *
4110
+ * - If any action of the given types is in progress, the promise completes only when
4111
+ * no action of the given types is in progress anymore.
4112
+ *
4113
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
4114
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
4115
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
4116
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
4117
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
4118
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
4119
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
4120
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
4121
+ *
4122
+ * Examples:
4123
+ *
4124
+ * ```ts
4125
+ * // Dispatches two actions in PARALLEL and wait for their TYPES:
4126
+ * expect(store.state.portfolio).toEqual(['TSLA']);
4127
+ * dispatch(new BuyAction('IBM'));
4128
+ * dispatch(new SellAction('TSLA'));
4129
+ * await store.waitAllActionTypes([BuyAction, SellAction]);
4130
+ * expect(store.state.portfolio).toEqual(['IBM']);
4131
+ * ```
4132
+ *
4133
+ * See also:
4134
+ * `waitCondition` - Waits until the state is in a given condition.
4135
+ * `waitActionCondition` - Waits until the actions in progress meet a given condition.
4136
+ * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
4137
+ * `waitActionType` - Waits until an action of a given type is NOT in progress.
4138
+ * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
4139
+ * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
4140
+ *
4141
+ * You should only use this method in tests.
4142
+ */
4143
+ async waitAllActionTypes(actionTypes, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
4144
+ if (actionTypes.length === 0) {
4145
+ await this._waitActionCondition((actions) => actions.size === 0, {
4146
+ completeImmediately: completeImmediately,
4147
+ completedErrorMessage: "No actions are in progress",
4148
+ timeoutMillis: timeoutMillis,
4149
+ onTimeout: onTimeout,
4150
+ });
4151
+ }
4152
+ else {
4153
+ await this._waitActionCondition((actionsInProgress) => {
4154
+ for (const actionType of actionTypes) {
4155
+ if (Array.from(actionsInProgress).some(action => action.constructor === actionType))
4156
+ return false;
4157
+ }
4158
+ return true;
4159
+ }, {
4160
+ completeImmediately: completeImmediately,
4161
+ completedErrorMessage: "No action of the given types was in progress",
4162
+ timeoutMillis: timeoutMillis,
4163
+ onTimeout: onTimeout,
4164
+ });
4165
+ }
4166
+ }
4167
+ async waitAnyActionTypeFinishes(actionTypes, { timeoutMillis = null, onTimeout, } = {}) {
4168
+ const { triggerAction } = await this._waitActionCondition(
4169
+ //
4170
+ (actionsInProgress, triggerAction) => {
4171
+ // If the triggerAction is one of the actionTypes,
4172
+ if ((triggerAction !== null) && actionTypes.includes(triggerAction.constructor)) {
4173
+ // If the actions in progress do not contain the triggerAction, then the triggerAction has finished.
4174
+ // Otherwise, the triggerAction has just been dispatched, which is not what we want.
4175
+ const isFinished = !Array.from(actionsInProgress).includes(triggerAction);
4176
+ return isFinished;
4177
+ }
4178
+ return false;
4179
+ }, {
4180
+ completedErrorMessage: "Assertion error",
4181
+ timeoutMillis: timeoutMillis,
4182
+ onTimeout: onTimeout,
4183
+ });
4184
+ // Only null when it timed out and `onTimeout` was given.
4185
+ // Otherwise, the condition is only met when an action finishes.
4186
+ return triggerAction;
4187
+ }
4188
+ /**
4189
+ * Returns a copy of the set of the actions in progress.
4190
+ *
4191
+ * Each call returns a new copy. It doesn't change when actions are later dispatched or
4192
+ * finish, and changing it doesn't affect the store.
4193
+ *
4194
+ * For debug purposes, the `toString` method of the returned set will
4195
+ * call `KissAction.toString()` for all actions.
4196
+ */
4197
+ actionsInProgress() {
4198
+ return new PrintableSet(this._actionsInProgress);
4199
+ }
4200
+ /**
4201
+ * Waits until the store state meets a certain condition, and then dispatches an action.
4202
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
4203
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
4204
+ * the condition, so no other action can change the state in between.
4205
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
4206
+ * dispatched one after the other, and each condition is checked again right before its
4207
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
4208
+ *
4209
+ * ```ts
4210
+ * store.dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
4211
+ * ```
4212
+ *
4213
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
4214
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
4215
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
4216
+ * timeout is logged with `Store.log()`. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
4217
+ * (or -1, or `Infinity`), but note that while it waits, the condition runs on every state change.
4218
+ * A `logOut()` cancels the `dispatchWhen`s that are still waiting: their action is not
4219
+ * dispatched, and their `onTimeout` is not called.
4220
+ *
4221
+ * ```ts
4222
+ * store.dispatchWhen(
4223
+ * new BuyStock('IBM'),
4224
+ * (state) => state.stocks.getPrice('IBM') >= 100,
4225
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
4226
+ * );
4227
+ * ```
4228
+ *
4229
+ * See also:
4230
+ * - `this.dispatchWhen` inside actions.
4231
+ * - `useDispatchWhen` (or `useStore().dispatchWhen`) in components.
4232
+ */
4233
+ dispatchWhen(action, condition, { timeoutMillis, onTimeout, }) {
4234
+ // Only happens if the condition or `onTimeout` throws. Log it, since nobody awaits `dispatchWhen`.
4235
+ const logFailure = (error) => Store.log(`dispatchWhen failed, and did not dispatch ${action}: ${error}`);
4236
+ // Unlike `waitCondition`, this doesn't use a Promise, so that the action is dispatched
4237
+ // synchronously: right away if the condition is already met, or right after the state
4238
+ // change that meets it. Otherwise, other dispatches could change the state in between.
4239
+ let isMet;
4240
+ try {
4241
+ isMet = condition(this._state);
4242
+ }
4243
+ catch (error) {
4244
+ logFailure(error);
4245
+ return;
4246
+ }
4247
+ if (isMet) {
4248
+ this._dispatchWhenAction(action);
4249
+ return;
4250
+ }
4251
+ let cancelTimer = () => { };
4252
+ // Called by `logOut`. Stops checking the condition, and stops the timer.
4253
+ const cancel = () => {
4254
+ cancelTimer();
4255
+ this._waitConditions = this._waitConditions.filter(c => c !== entry);
4256
+ Store._logLazy(() => `The dispatchWhen of ${action} was cancelled by logOut, or by disposing the store.`);
4257
+ };
4258
+ const fail = (error) => {
4259
+ cancelTimer();
4260
+ this._dispatchWhenCancels.delete(cancel);
4261
+ logFailure(error);
4262
+ };
4263
+ // Called by `_registerState` after checking all conditions. Other `dispatchWhen` met by the
4264
+ // same state change may have been dispatched before, and changed the state. So the condition
4265
+ // is checked again: if it's no longer met, it keeps waiting, with the same timeout.
4266
+ const dispatchIfStillMet = () => {
4267
+ // Cancelled by `logOut` (possibly dispatched by an earlier action).
4268
+ if (!this._dispatchWhenCancels.has(cancel))
4269
+ return;
4270
+ let isStillMet;
4271
+ try {
4272
+ isStillMet = condition(this._state);
4273
+ }
4274
+ catch (error) {
4275
+ fail(error);
4276
+ return;
4277
+ }
4278
+ if (isStillMet) {
4279
+ cancelTimer();
4280
+ this._dispatchWhenCancels.delete(cancel);
4281
+ this._dispatchWhenAction(action);
4282
+ }
4283
+ else
4284
+ this._waitConditions.push(entry);
4285
+ };
4286
+ const entry = {
4287
+ check: condition,
4288
+ // The condition was removed from `_waitConditions`, but it's still waiting until
4289
+ // `dispatchIfStillMet` is called.
4290
+ resolve: () => this._dispatchWhenQueue.push(dispatchIfStillMet),
4291
+ reject: fail,
4292
+ };
4293
+ this._waitConditions.push(entry);
4294
+ this._dispatchWhenCancels.add(cancel);
4295
+ if (timeoutMillis > 0) {
4296
+ cancelTimer = _setLongTimeout(() => {
4297
+ // Stop checking the condition, since the action will not be dispatched anymore.
4298
+ this._dispatchWhenCancels.delete(cancel);
4299
+ this._waitConditions = this._waitConditions.filter(c => c !== entry);
4300
+ try {
4301
+ if (onTimeout)
4302
+ onTimeout();
4303
+ else
4304
+ Store.log(`dispatchWhen timed out, and did not dispatch ${action}.`);
4305
+ }
4306
+ catch (error) {
4307
+ logFailure(error);
4308
+ }
4309
+ }, timeoutMillis);
4310
+ }
4311
+ }
4312
+ // Dispatches an action of `dispatchWhen`. A synchronous error is logged, and doesn't affect
4313
+ // the action that changed the state.
4314
+ _dispatchWhenAction(action) {
4315
+ try {
4316
+ this.dispatch(action);
4317
+ }
4318
+ catch (error) {
4319
+ Store.log(`dispatchWhen failed to dispatch ${action}: ${error}`);
4320
+ }
4321
+ }
4322
+ }
4323
+ class Mocks {
4324
+ mocks = new Map();
4325
+ add(actionType, mockFunction) {
4326
+ // A `null` mock function means the dispatch is aborted.
4327
+ this.mocks.set(actionType, mockFunction ?? (() => null));
4328
+ }
4329
+ remove(actionType) {
4330
+ this.mocks.delete(actionType);
4331
+ }
4332
+ clear() {
4333
+ this.mocks.clear();
4334
+ }
4335
+ get(actionType) {
4336
+ return this.mocks.get(actionType);
4337
+ }
4338
+ }
4339
+ /**
4340
+ * A plain `Set` whose `toString` lists its elements (for actions, calling `KissAction.toString()`),
4341
+ * instead of printing `[object Set]`. Used for the copies of the actions in progress.
4342
+ */
4343
+ class PrintableSet extends Set {
4344
+ toString() {
4345
+ return Array.from(this).toString();
4346
+ }
4347
+ }
4348
+ /**
4349
+ * Like `setTimeout`, but also works for delays larger than `setTimeout` accepts (about 24.8
4350
+ * days), by chaining timers. A delay of `Infinity` never fires. Returns a function that cancels
4351
+ * the timeout.
4352
+ */
4353
+ function _setLongTimeout(callback, millis) {
4354
+ if (millis === Infinity)
4355
+ return () => { };
4356
+ let timer;
4357
+ const schedule = (remaining) => {
4358
+ const delay = Math.min(remaining, MAX_TIMEOUT_MILLIS);
4359
+ timer = setTimeout(() => {
4360
+ if (remaining > delay)
4361
+ schedule(remaining - delay);
4362
+ else
4363
+ callback();
4364
+ }, delay);
4365
+ };
4366
+ schedule(millis);
4367
+ return () => clearTimeout(timer);
4368
+ }
4369
+ /**
4370
+ * Called when a wait times out. If `onTimeout` was given, calls it and resolves the wait.
4371
+ * Otherwise, rejects the wait with a `TimeoutException`. If `onTimeout` throws, rejects
4372
+ * the wait with that error.
4373
+ */
4374
+ function _settleTimeout(timeoutMillis, onTimeout, resolve, reject) {
4375
+ if (onTimeout === undefined) {
4376
+ reject(new TimeoutException(`Timeout exceeded: ${timeoutMillis} milliseconds.`));
4377
+ }
4378
+ else {
4379
+ try {
4380
+ onTimeout();
4381
+ resolve();
4382
+ }
4383
+ catch (error) {
4384
+ reject(error);
4385
+ }
4386
+ }
4387
+ }
4388
+ // Adds the explicit resource management methods to the store (see the `Store` interface
4389
+ // above), if the runtime has the symbols. Older runtimes don't, and `using` can't be used with
4390
+ // them anyway.
4391
+ if (typeof Symbol.dispose === 'symbol') {
4392
+ Store.prototype[Symbol.dispose] = function () {
4393
+ void this.dispose();
4394
+ };
4395
+ }
4396
+ if (typeof Symbol.asyncDispose === 'symbol') {
4397
+ Store.prototype[Symbol.asyncDispose] = function () {
4398
+ return this.dispose();
4399
+ };
4400
+ }