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
@@ -1,262 +1,579 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ProcessPersistence = void 0;
4
- const Persistor_1 = require("./Persistor");
5
- const KissAction_1 = require("./KissAction");
6
- const Store_1 = require("./Store");
7
- class ProcessPersistence {
8
- constructor(persistor, lastPersistedState) {
9
- this.isPersisting = false;
10
- this.isANewStateAvailable = false;
11
- this.lastPersistTime = new Date();
12
- this.isPaused = false;
13
- this.isInit = false;
14
- this.finishedPersistingCallback = null;
15
- this.persistor = persistor;
16
- this.lastPersistedState = lastPersistedState;
17
- this.newestState = null;
18
- }
19
- async readInitialState(store, initialState) {
20
- let stateReadFromPersistor = null;
21
- try {
22
- stateReadFromPersistor = await this.persistor.readState();
23
- }
24
- catch (error) {
25
- this.log('Error reading state:' + error + '. State will reset.');
26
- try {
27
- await this.persistor.deleteState();
28
- }
29
- catch (error) {
30
- this.log('Error deleting the state:' + error + '.');
31
- }
32
- }
33
- if (stateReadFromPersistor === null) {
34
- try {
35
- // If it was not possible to read the persisted state,
36
- // we persist the initial-state passed to the Store constructor.
37
- await this.persistor.saveInitialState(initialState);
38
- }
39
- catch (error) {
40
- this.log('Error saving initial state:' + error + '.');
41
- }
42
- }
43
- //
44
- else {
45
- // If the saved state was read successfully, we replace the store state with it.
46
- // In this case, the initial-state passed in the Store constructor was used
47
- // only while the persisted state is loading.
48
- await store.dispatchAndWait(new KissAction_1.UpdateStateAction((_) => stateReadFromPersistor, false));
49
- }
50
- }
51
- log(message) {
52
- try {
53
- Store_1.Store.log(message);
54
- }
55
- catch (error) {
56
- // Discard error.
57
- }
58
- }
59
- get throttle() {
60
- return this.persistor.throttle || 0;
61
- }
62
- async saveInitialState(initialState) {
63
- this.lastPersistedState = initialState;
64
- await this.persistor.saveInitialState(initialState);
65
- }
66
- /**
67
- * Same as `Persistor.readState` but will remember the read state as the `lastPersistedState`.
68
- */
69
- async readState() {
70
- const state = await this.persistor.readState();
71
- this.lastPersistedState = state;
72
- return state;
73
- }
74
- /**
75
- * Same as `Persistor.deleteState` but will clear the `lastPersistedState`.
76
- */
77
- async deleteState() {
78
- this.lastPersistedState = null;
79
- await this.persistor.deleteState();
80
- }
81
- /**
82
- * Call `logOut()` when you want to delete the persisted state, and return the store
83
- * state to the given initial-state. That's usually necessary when the user logs out
84
- * of your app, or the user deletes its account, so that another user may log in,
85
- * or start a new sign-up process.
86
- *
87
- * Note: If you know about any timers or async processes that you may have started,
88
- * you should stop/cancel them all before calling this method.
89
- *
90
- * You may opt to:
91
- *
92
- * - Wait for `throttle` milliseconds to make sure all async processes that the app may
93
- * have started have time to finish. The default `throttle` is 3000 milliseconds (3 seconds).
94
- *
95
- * - Wait for all actions currently running to finish, but wait at most `actionsThrottle`
96
- * milliseconds. If the actions are not finished by then, the state will be deleted anyway.
97
- * The default `actionsThrottle` is 6000 milliseconds (6 seconds).
98
- */
99
- async logOut({ store, initialState, throttle = 3000, actionsThrottle = 6000, }) {
100
- // Pauses the persistor, so it doesn't start a new persistence process.
101
- this.pause();
102
- // Cancel the persistence timer.
103
- this._cancelTimer();
104
- // Set the store to shut down, so it doesn't start any new actions.
105
- store.setShutDown(true);
106
- // If the state is NOT currently being persisted,
107
- if (!this.isPersisting) {
108
- // Clear the callback that is called when it finishes persisting.
109
- this.finishedPersistingCallback = null;
110
- // Wait for the throttle period to finish.
111
- await new Promise(resolve => setTimeout(resolve, throttle));
112
- // Wait for all actions currently running to finish,
113
- // but wait at most `actionsThrottle` milliseconds.
114
- await store.waitAllActions(null, {
115
- timeoutMillis: actionsThrottle,
116
- completeImmediately: true
117
- })
118
- .catch((error) => {
119
- });
120
- // Delete the old persisted state.
121
- await this.deleteState();
122
- // Synchronously change the store state to the initial-state.
123
- store.dispatchSync(new KissAction_1.UpdateStateAction((state) => initialState));
124
- // Persist the new initial-state.
125
- await this._persist(new Date(), initialState).then();
126
- // Restart the store accepting new actions.
127
- store.setShutDown(false);
128
- }
129
- //
130
- // If it's currently being persisted, we can't delete the state right now.
131
- else {
132
- // But as soon as it finishes persisting, try again.
133
- this.finishedPersistingCallback = async () => {
134
- await this.logOut({
135
- store, initialState, throttle, actionsThrottle
136
- });
137
- };
138
- }
139
- }
140
- /**
141
- * 1) If we're still persisting the last time, don't persist no matter what.
142
- * 2) If action is of type `UpdateStateAction` with `ifPersists` false,
143
- * don't persist, but consider the state as persisted.
144
- * 3) If throttle period is done (or if action is PersistAction), persist.
145
- * 4) If throttle period is NOT done, create a timer to persist as soon as it finishes.
146
- *
147
- * Return true if the persist process started.
148
- * Return false if persistence was postponed.
149
- *
150
- */
151
- process(action, newState) {
152
- this.isInit = true;
153
- this.newestState = newState;
154
- if (this.isPaused || this.lastPersistedState === newState)
155
- return false;
156
- if ((action instanceof KissAction_1.UpdateStateAction) && (!action.ifPersists)) {
157
- this.lastPersistedState = this.newestState;
158
- return false;
159
- }
160
- // 1) If we're still persisting the last time, don't persist no matter what.
161
- if (this.isPersisting) {
162
- this.isANewStateAvailable = true;
163
- return false;
164
- }
165
- //
166
- else {
167
- const now = new Date();
168
- // 2) If throttle period is done (or if action is PersistAction), persist.
169
- if (now.valueOf() - this.lastPersistTime.valueOf() >= this.throttle
170
- || (action instanceof Persistor_1.PersistAction)) {
171
- this._cancelTimer();
172
- this._persist(now, newState).then();
173
- return true;
174
- }
175
- // 3) If throttle period is NOT done, create a timer to persist as soon as it finishes.
176
- else {
177
- if (!this.timer) {
178
- const asSoonAsThrottleFinishes = this.throttle - (now.valueOf() - this.lastPersistTime.valueOf());
179
- this.timer = setTimeout(() => {
180
- this.timer = undefined;
181
- this.process(null, this.newestState); // TypeScript forced cast
182
- }, asSoonAsThrottleFinishes);
183
- }
184
- return false;
185
- }
186
- }
187
- }
188
- _cancelTimer() {
189
- if (this.timer) {
190
- clearTimeout(this.timer);
191
- this.timer = undefined;
192
- }
193
- }
194
- async _persist(now, newState) {
195
- this.isPersisting = true;
196
- this.lastPersistTime = now;
197
- this.isANewStateAvailable = false;
198
- try {
199
- await this.persistor.persistDifference(this.lastPersistedState, newState);
200
- }
201
- //
202
- finally {
203
- this.lastPersistedState = newState;
204
- this.isPersisting = false;
205
- this.finishedPersistingCallback?.();
206
- // If a new state became available while the present state was saving, save again.
207
- if (this.isANewStateAvailable) {
208
- this.isANewStateAvailable = false;
209
- this.process(null, this.newestState);
210
- }
211
- }
212
- }
213
- /**
214
- * Pause the `Persistor` temporarily.
215
- *
216
- * When `pause` is called, the Persistor will not start a new persistence process, until method
217
- * `resume` is called. This will not affect the current persistence process, if one is currently
218
- * running.
219
- *
220
- * Note: A persistence process starts when the `persistDifference` method is called, and
221
- * finishes when the promise returned by that method completes.
222
- *
223
- */
224
- pause() {
225
- this.isPaused = true;
226
- }
227
- /**
228
- * Persists the current state (if it's not yet persisted), then pauses the `Persistor`
229
- * temporarily.
230
- *
231
- *
232
- * When `persistAndPause` is called, this will not affect the current persistence process, if
233
- * one is currently running. If no persistence process was running, it will immediately start a
234
- * new persistence process (ignoring `throttle`).
235
- *
236
- * Then, the Persistor will not start another persistence process, until method `resume` is
237
- * called.
238
- *
239
- * Note: A persistence process starts when the `persistDifference` method is called, and
240
- * finishes when the promise returned by that method completes.
241
- *
242
- */
243
- async persistAndPause() {
244
- this.isPaused = true;
245
- this._cancelTimer();
246
- if (this.isInit //
247
- && !this.isPersisting //
248
- && (this.lastPersistedState !== this.newestState)) {
249
- const now = new Date();
250
- return this._persist(now, this.newestState); // TypeScript forced cast
251
- }
252
- }
253
- /**
254
- * Resumes persistence by the `Persistor`, after calling `pause` or `persistAndPause`.
255
- */
256
- resume() {
257
- this.isPaused = false;
258
- if (this.isInit)
259
- this.process(null, this.newestState);
260
- }
261
- }
262
- exports.ProcessPersistence = ProcessPersistence;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProcessPersistence = void 0;
4
+ const Persistor_1 = require("./Persistor");
5
+ const KissAction_1 = require("./KissAction");
6
+ const Store_1 = require("./Store");
7
+ const StoreException_1 = require("./StoreException");
8
+ const utils_1 = require("./utils");
9
+ class ProcessPersistence {
10
+ constructor(persistor, lastPersistedState) {
11
+ this.isPersisting = false;
12
+ this.isANewStateAvailable = false;
13
+ this.lastPersistTime = new Date();
14
+ this.isPaused = false;
15
+ this.isInit = false;
16
+ // False while `readInitialState` is running. State changes are only persisted after it finishes.
17
+ this.isReady = false;
18
+ // True only while the store applies the state read from the persistor. That's the only
19
+ // dispatch allowed before the store is ready.
20
+ this.isApplyingReadState = false;
21
+ // Called by `readInitialState` right after `isReady` becomes true. The store uses it to
22
+ // publish the readiness to the `useIsStoreReady` hook.
23
+ this.onReady = null;
24
+ // Called when the persistence process currently running finishes. See `_waitForPersisting`.
25
+ this._persistingWaiters = [];
26
+ // True if a `PersistAction` was dispatched while a persistence operation was running.
27
+ // When it finishes, the state is persisted ignoring the throttle.
28
+ this._isPersistActionWaiting = false;
29
+ // How many `logOut` calls are running. See `_startLogOut`.
30
+ this._logOutsRunning = 0;
31
+ // Called when no `logOut` is running anymore. See `_waitForLogOut`.
32
+ this._logOutWaiters = [];
33
+ /**
34
+ * Called with the persistence errors: the errors thrown by `Persistor.persistDifference`
35
+ * (after `Persistor.wrapError`, and only if it didn't return `null`), the errors thrown
36
+ * while reading the persisted state, and the errors added with `Persistor.addError`.
37
+ * The `originalError` is the error before `Persistor.wrapError` (or the same error, if it
38
+ * didn't go through `wrapError`). If not set, the errors are logged with `Store.log()`.
39
+ * The `observeOnly` is true when the error is also thrown to the caller (by `logOut`), so it
40
+ * should only be observed (given to the `errorObserver`), and not thrown again.
41
+ */
42
+ this.onError = null;
43
+ this.persistor = persistor;
44
+ this.lastPersistedState = lastPersistedState;
45
+ this.newestState = null;
46
+ this._ready = new Promise(resolve => this._resolveReady = resolve);
47
+ }
48
+ /**
49
+ * Resolves when the persisted state has been read (or failed to read) at startup.
50
+ * Never rejects.
51
+ */
52
+ ready() {
53
+ return this._ready;
54
+ }
55
+ async readInitialState(store, initialState) {
56
+ try {
57
+ await this._readInitialState(store, initialState);
58
+ }
59
+ //
60
+ finally {
61
+ // Now persist the state changes that happened while reading/saving the initial state.
62
+ this.processAddedErrors();
63
+ this.isReady = true;
64
+ // Tells the store right away, so that it publishes the readiness to `useIsStoreReady`.
65
+ // This runs after the read state was applied to the store (if there was one), so a
66
+ // component that sees the store as ready also sees the restored state.
67
+ this.onReady?.();
68
+ this._resolveReady();
69
+ if (this.isInit)
70
+ this.process(null, this.newestState);
71
+ }
72
+ }
73
+ async _readInitialState(store, initialState) {
74
+ let stateReadFromPersistor = null;
75
+ try {
76
+ stateReadFromPersistor = await this.persistor.readState();
77
+ }
78
+ catch (error) {
79
+ this.log('Error reading state:' + error + '. State will reset.');
80
+ this.reportError(error);
81
+ try {
82
+ await this.persistor.deleteState();
83
+ }
84
+ catch (error) {
85
+ this.log('Error deleting the state:' + error + '.');
86
+ this.reportError(error);
87
+ }
88
+ }
89
+ if (stateReadFromPersistor === null) {
90
+ try {
91
+ // If it was not possible to read the persisted state,
92
+ // we persist the initial-state passed to the Store constructor.
93
+ await this.persistor.saveInitialState(initialState);
94
+ }
95
+ catch (error) {
96
+ // Nothing was saved. Otherwise, the next save would diff against the initial-state,
97
+ // which was never saved. With null, the next save saves the whole state.
98
+ this.lastPersistedState = null;
99
+ this.log('Error saving initial state:' + error + '.');
100
+ this.reportError(error);
101
+ }
102
+ }
103
+ //
104
+ else {
105
+ // If the saved state was read successfully, we replace the store state with it.
106
+ // In this case, the initial-state passed in the Store constructor was used
107
+ // only while the persisted state is loading.
108
+ // The slices of server state merged while the persisted state was being read (see
109
+ // `Store.mergeServerState`) are merged into it again, so that they are not lost.
110
+ const stateToApply = store._applyPendingServerSlices(stateReadFromPersistor);
111
+ let promise;
112
+ this.isApplyingReadState = true;
113
+ try {
114
+ promise = store.dispatchAndWait(new KissAction_1.UpdateStateAction((_) => stateToApply, false));
115
+ }
116
+ finally {
117
+ this.isApplyingReadState = false;
118
+ }
119
+ await promise;
120
+ // The state just read is what's saved, even if the persistor is paused. Otherwise, the
121
+ // next save would diff against the initial-state, which was never saved.
122
+ this.lastPersistedState = stateReadFromPersistor;
123
+ }
124
+ }
125
+ log(message) {
126
+ try {
127
+ Store_1.Store.log(message);
128
+ }
129
+ catch {
130
+ // Discard error.
131
+ }
132
+ }
133
+ /**
134
+ * Gives the error to `onError`, or logs it if `onError` is not set.
135
+ */
136
+ reportError(error, originalError = error, observeOnly = false) {
137
+ if (this.onError) {
138
+ try {
139
+ this.onError(error, originalError, observeOnly);
140
+ }
141
+ catch (_error) {
142
+ this.log('Error processing a persistence error:' + _error + '.');
143
+ }
144
+ }
145
+ //
146
+ else
147
+ this.log('Persistence error:' + error + '.');
148
+ }
149
+ /**
150
+ * Reports the errors added with `Persistor.addError`, removing them from the persistor.
151
+ */
152
+ processAddedErrors() {
153
+ while (true) {
154
+ let error;
155
+ try {
156
+ error = this.persistor.getAndRemoveFirstError?.();
157
+ }
158
+ catch {
159
+ return;
160
+ }
161
+ if (error === null || error === undefined)
162
+ break;
163
+ this.reportError(error);
164
+ }
165
+ }
166
+ get throttle() {
167
+ return this.persistor.throttle || 0;
168
+ }
169
+ /**
170
+ * Same as `Persistor.saveInitialState` but will remember the `initialState` as the
171
+ * `lastPersistedState`. If a save is running, waits for it to finish first, so that it can't
172
+ * overwrite the `initialState` later.
173
+ */
174
+ async saveInitialState(initialState) {
175
+ return this._runAlone(async () => {
176
+ this.lastPersistedState = initialState;
177
+ try {
178
+ await this.persistor.saveInitialState(initialState);
179
+ }
180
+ catch (error) {
181
+ // Not saved, so it's not considered persisted (unless it was replaced in the meantime).
182
+ if (this.lastPersistedState === initialState)
183
+ this.lastPersistedState = null;
184
+ throw error;
185
+ }
186
+ });
187
+ }
188
+ /**
189
+ * Same as `Persistor.readState` but will remember the read state as the `lastPersistedState`.
190
+ * If a save is running, waits for it to finish first, so that it reads the saved state, and
191
+ * so that the save can't change the `lastPersistedState` later.
192
+ */
193
+ async readState() {
194
+ return this._runAlone(async () => {
195
+ const state = await this.persistor.readState();
196
+ this.lastPersistedState = state;
197
+ return state;
198
+ });
199
+ }
200
+ /**
201
+ * Same as `Persistor.deleteState` but will clear the `lastPersistedState`.
202
+ * If a save is running, waits for it to finish first, so that it can't put the deleted
203
+ * state back later.
204
+ */
205
+ async deleteState() {
206
+ return this._runAlone(async () => {
207
+ this.lastPersistedState = null;
208
+ await this.persistor.deleteState();
209
+ });
210
+ }
211
+ /**
212
+ * Runs the `operation` when no other persistence operation is running, so that they don't
213
+ * overlap. While it runs, state changes are not saved. They are saved when it finishes, if
214
+ * necessary.
215
+ */
216
+ async _runAlone(operation) {
217
+ while (this.isPersisting)
218
+ await this._waitForPersisting();
219
+ this._startOperation();
220
+ try {
221
+ return await operation();
222
+ }
223
+ finally {
224
+ this._finishOperation();
225
+ }
226
+ }
227
+ _startOperation() {
228
+ this.isPersisting = true;
229
+ }
230
+ /**
231
+ * Called when a persistence operation finishes (even if it failed). If the state may have
232
+ * changed while it was running, persists it if necessary.
233
+ */
234
+ _finishOperation() {
235
+ this.processAddedErrors();
236
+ this.isPersisting = false;
237
+ const waiters = this._persistingWaiters;
238
+ this._persistingWaiters = [];
239
+ for (const resolve of waiters)
240
+ resolve();
241
+ const newStateAvailable = this.isANewStateAvailable;
242
+ const persistActionWaiting = this._isPersistActionWaiting;
243
+ this.isANewStateAvailable = false;
244
+ this._isPersistActionWaiting = false;
245
+ // If a new state became available while the operation was running, save it if necessary.
246
+ // If a PersistAction was dispatched meanwhile, the throttle is ignored.
247
+ if (newStateAvailable)
248
+ this._process(null, this.newestState, persistActionWaiting);
249
+ }
250
+ /**
251
+ * Call `logOut()` when you want to delete the persisted state, and return the store
252
+ * state to the given initial-state. That's usually necessary when the user logs out
253
+ * of your app, or the user deletes its account, so that another user may log in,
254
+ * or start a new sign-up process.
255
+ *
256
+ * Note: If you know about any timers or async processes that you may have started,
257
+ * you should stop/cancel them all before calling this method.
258
+ *
259
+ * You may opt to:
260
+ *
261
+ * - Wait for `throttle` milliseconds to make sure all async processes that the app may
262
+ * have started have time to finish. The default `throttle` is 3000 milliseconds (3 seconds).
263
+ *
264
+ * - Wait for all actions currently running to finish, but wait at most `actionsThrottle`
265
+ * milliseconds. If the actions are not finished by then, the state will be deleted anyway.
266
+ * The default `actionsThrottle` is 6000 milliseconds (6 seconds).
267
+ *
268
+ * The result of the actions dispatched before logOut is discarded, and so are the actions
269
+ * they dispatch after it.
270
+ *
271
+ * Same as `store.logOut`. See it for more details.
272
+ */
273
+ async logOut({ store, initialState, throttle = 3000, actionsThrottle = 6000, }) {
274
+ return store._logOut(this, initialState, throttle, actionsThrottle);
275
+ }
276
+ /**
277
+ * For Kiss internal use only. Called by the store when `logOut` starts.
278
+ * While a logOut is running, the persistor doesn't start a new persistence process
279
+ * (except to persist the initial-state). This is kept apart from `pause`/`resume`, so that
280
+ * a persistor paused by the app, before or during logOut, stays paused after it.
281
+ * @internal
282
+ */
283
+ _startLogOut() {
284
+ // Logging out while the persisted state is still being read is a developer error:
285
+ // the read would finish afterwards and bring back the old user's state.
286
+ if (!this.isReady)
287
+ throw new StoreException_1.StoreException('Called logOut() while the persisted state is still being read. ' +
288
+ 'Wait for store.ready() before calling logOut().');
289
+ this._logOutsRunning++;
290
+ this._cancelTimer();
291
+ }
292
+ /**
293
+ * For Kiss internal use only. Called by the store during `logOut`.
294
+ * If the state is currently being persisted, we can't delete it right now. Wait until the
295
+ * current persistence finishes. Since a logOut is running, no new persistence process will
296
+ * start after that.
297
+ * @internal
298
+ */
299
+ async _waitWhilePersisting() {
300
+ while (this.isPersisting)
301
+ await this._waitForPersisting();
302
+ }
303
+ /**
304
+ * For Kiss internal use only. Called by the store during `logOut`, to delete the persisted
305
+ * state. If it fails, the error is reported (only observed, since logOut throws it), and
306
+ * returned. Returns `null` if it succeeded.
307
+ * @internal
308
+ */
309
+ async _deleteLogOutState() {
310
+ // Another logOut that runs at the same time may be persisting its initial-state.
311
+ await this._waitWhilePersisting();
312
+ try {
313
+ await this.deleteState();
314
+ return null;
315
+ }
316
+ catch (error) {
317
+ this.reportError(error, error, true);
318
+ return { error };
319
+ }
320
+ }
321
+ /**
322
+ * For Kiss internal use only. Called by the store during `logOut`, to persist the initial-state.
323
+ * Note this is done even if the persistor is paused. If it fails, the error (after
324
+ * `Persistor.wrapError`) is reported (only observed, since logOut throws it), and returned.
325
+ * Returns `null` if it succeeded, or if `wrapError` swallowed the error.
326
+ * @internal
327
+ */
328
+ async _persistLogOutState(initialState) {
329
+ // Another logOut that runs at the same time may be persisting its initial-state. If both
330
+ // saves ran at the same time, the one that finishes last would win, and it could be the
331
+ // initial-state of the other logOut.
332
+ await this._waitWhilePersisting();
333
+ return this._persist(new Date(), initialState, true);
334
+ }
335
+ /**
336
+ * For Kiss internal use only. Called by the store when `logOut` finishes (even if it failed).
337
+ * If no other logOut is running, and the persistor is not paused, persistence resumes: if the
338
+ * state changed after the initial-state was persisted, this persists the new state.
339
+ * @internal
340
+ */
341
+ _endLogOut() {
342
+ this._logOutsRunning--;
343
+ if (this._logOutsRunning > 0)
344
+ return;
345
+ const waiters = this._logOutWaiters;
346
+ this._logOutWaiters = [];
347
+ for (const resolve of waiters)
348
+ resolve();
349
+ if (!this.isPaused && this.isInit)
350
+ this.process(null, this.newestState);
351
+ }
352
+ /**
353
+ * Resolves when no `logOut` is running anymore.
354
+ * Only call it while `_logOutsRunning` is more than zero.
355
+ */
356
+ _waitForLogOut() {
357
+ return new Promise(resolve => this._logOutWaiters.push(resolve));
358
+ }
359
+ /**
360
+ * 1) If we're still persisting the last time, don't persist no matter what.
361
+ * Instead, check again when it finishes.
362
+ * 2) If action is of type `UpdateStateAction` with `ifPersists` false,
363
+ * don't persist, but consider the state as persisted (if no earlier change is waiting to
364
+ * be saved). This is done even while the persistor is paused.
365
+ * 3) If throttle period is done (or if action is PersistAction), persist.
366
+ * 4) If throttle period is NOT done, create a timer to persist as soon as it finishes.
367
+ *
368
+ * Return true if the persist process started.
369
+ * Return false if persistence was postponed.
370
+ *
371
+ */
372
+ process(action, newState) {
373
+ return this._process(action, newState, false);
374
+ }
375
+ /**
376
+ * Same as `process`, but if `ignoreThrottle` is true, the throttle is ignored,
377
+ * as if the action were a `PersistAction`.
378
+ */
379
+ _process(action, newState, ignoreThrottle) {
380
+ // True if an earlier state change was not saved yet. For example, because it's waiting for
381
+ // the throttle, for a running save to finish, or for the paused persistor to resume.
382
+ const hasUnsavedChange = this.isInit && (this.newestState !== this.lastPersistedState);
383
+ this.isInit = true;
384
+ this.newestState = newState;
385
+ const isNotPersisted = (action instanceof KissAction_1.UpdateStateAction) && (!action.ifPersists);
386
+ // 1) While a persistence operation is running, remember to check again when it finishes.
387
+ // This is done even if the new state is the last persisted state, since the running
388
+ // operation will change the last persisted state when it finishes. But not for a state
389
+ // that should not be persisted.
390
+ if (this.isPersisting && !isNotPersisted) {
391
+ this.isANewStateAvailable = true;
392
+ if ((action instanceof Persistor_1.PersistAction || ignoreThrottle) && !this.isPaused)
393
+ this._isPersistActionWaiting = true;
394
+ }
395
+ if (this.lastPersistedState === newState)
396
+ return false;
397
+ // This is checked even while the persistor is paused. Otherwise, when it resumes,
398
+ // it would see a difference, and save the state that should not be persisted.
399
+ if (isNotPersisted) {
400
+ // Only consider this state as persisted if no earlier change is waiting to be saved.
401
+ // Otherwise, those earlier changes would be lost. In that case, the pending save will
402
+ // save the newest state, which includes this one.
403
+ if (!hasUnsavedChange && !this.timer && !this.isPersisting && !this.isANewStateAvailable)
404
+ this.lastPersistedState = this.newestState;
405
+ return false;
406
+ }
407
+ if (this.isPaused)
408
+ return false;
409
+ // While a logOut is running, don't persist. When it finishes, it persists what's needed.
410
+ if (this._logOutsRunning > 0)
411
+ return false;
412
+ // While the initial state is being read/saved, don't persist. It will be persisted when it finishes.
413
+ if (!this.isReady)
414
+ return false;
415
+ // 1) If we're still persisting the last time, don't persist no matter what.
416
+ // It was already remembered above, to check again when it finishes.
417
+ if (this.isPersisting) {
418
+ return false;
419
+ }
420
+ //
421
+ else {
422
+ const now = new Date();
423
+ // 2) If throttle period is done (or if action is PersistAction), persist.
424
+ if (now.valueOf() - this.lastPersistTime.valueOf() >= this.throttle
425
+ || (action instanceof Persistor_1.PersistAction)
426
+ || ignoreThrottle) {
427
+ this._cancelTimer();
428
+ this._persist(now, newState).then();
429
+ return true;
430
+ }
431
+ // 3) If throttle period is NOT done, create a timer to persist as soon as it finishes.
432
+ else {
433
+ if (!this.timer) {
434
+ const asSoonAsThrottleFinishes = this.throttle - (now.valueOf() - this.lastPersistTime.valueOf());
435
+ this.timer = setTimeout(() => {
436
+ this.timer = undefined;
437
+ this.process(null, this.newestState); // TypeScript forced cast
438
+ }, (0, utils_1.capTimeoutMillis)(asSoonAsThrottleFinishes));
439
+ }
440
+ return false;
441
+ }
442
+ }
443
+ }
444
+ _cancelTimer() {
445
+ if (this.timer) {
446
+ clearTimeout(this.timer);
447
+ this.timer = undefined;
448
+ }
449
+ }
450
+ /**
451
+ * Resolves when the persistence process currently running finishes.
452
+ * Only call it while `isPersisting` is true.
453
+ *
454
+ * Note we use the `isPersisting` flag, and don't keep the promise of the running process.
455
+ * When `persistDifference` throws synchronously, instead of returning a rejected promise,
456
+ * `_persist` finishes before it even returns its promise. A kept promise would then never be
457
+ * cleared, and waiting for it in a loop would freeze the app.
458
+ */
459
+ _waitForPersisting() {
460
+ return new Promise(resolve => this._persistingWaiters.push(resolve));
461
+ }
462
+ // Never rejects. A `persistDifference` that throws synchronously, or returns a rejected
463
+ // promise, is handled the same way: its error is reported, and the state is not saved.
464
+ /**
465
+ * Returns the error (after `Persistor.wrapError`) if the save failed, or `null` if it
466
+ * succeeded, or if `wrapError` swallowed the error. If `observeOnly` is true, the error is
467
+ * only observed, since the caller throws it.
468
+ */
469
+ async _persist(now, newState, observeOnly = false) {
470
+ let failure = null;
471
+ this._startOperation();
472
+ this.lastPersistTime = now;
473
+ this.isANewStateAvailable = false;
474
+ try {
475
+ await this.persistor.persistDifference(this.lastPersistedState, newState);
476
+ // Only consider the state persisted if it succeeded. Otherwise, the next time we persist,
477
+ // the difference will be calculated from the last state that was actually persisted.
478
+ this.lastPersistedState = newState;
479
+ }
480
+ //
481
+ catch (error) {
482
+ // The error is reported, never thrown, so it can't become an unhandled rejection.
483
+ // Note the save is not retried here. It will be tried again when the state changes.
484
+ let processedError;
485
+ try {
486
+ processedError = this.persistor.wrapError ? this.persistor.wrapError(error) : error;
487
+ }
488
+ catch (_error) {
489
+ // If `wrapError` throws, the thrown error is used instead.
490
+ processedError = _error;
491
+ }
492
+ if (processedError !== null && processedError !== undefined) {
493
+ this.reportError(processedError, error, observeOnly);
494
+ failure = { error: processedError };
495
+ }
496
+ }
497
+ //
498
+ finally {
499
+ // If a new state became available while the present state was saving, save again.
500
+ this._finishOperation();
501
+ }
502
+ return failure;
503
+ }
504
+ /**
505
+ * Pause the `Persistor` temporarily.
506
+ *
507
+ * When `pause` is called, the Persistor will not start a new persistence process, until method
508
+ * `resume` is called. This will not affect the current persistence process, if one is currently
509
+ * running.
510
+ *
511
+ * Note: A persistence process starts when the `persistDifference` method is called, and
512
+ * finishes when the promise returned by that method completes.
513
+ *
514
+ */
515
+ pause() {
516
+ this.isPaused = true;
517
+ }
518
+ /**
519
+ * For Kiss internal use only. Called by `store.dispose()`. Pauses the persistor, and cancels
520
+ * the pending save (a state change waiting for the throttle). A save that is already running
521
+ * still finishes.
522
+ */
523
+ dispose() {
524
+ this.isPaused = true;
525
+ this._cancelTimer();
526
+ }
527
+ /**
528
+ * Persists the current state (if it's not yet persisted), then pauses the `Persistor`
529
+ * temporarily.
530
+ *
531
+ *
532
+ * When `persistAndPause` is called while the persisted state is still being read, while a
533
+ * `logOut` is running, or while a persistence process is running, it waits for them to
534
+ * finish. Note logOut persists its initial-state, and the state before it is never persisted. Then, if the current state is
535
+ * not yet persisted, it immediately starts a new persistence process (ignoring `throttle`).
536
+ * The returned promise completes when the current state is persisted.
537
+ *
538
+ * If the save fails, the returned promise still resolves. It never rejects. This is on
539
+ * purpose, not a bug: this method is usually called when the app is shutting down or going to
540
+ * the background, and then the app can't recover from a failed save anyway. The error is not
541
+ * lost: it's reported (see `onError`) before the promise resolves, so it can be logged.
542
+ *
543
+ * Then, the Persistor will not start another persistence process, until method `resume` is
544
+ * called.
545
+ *
546
+ * Note: A persistence process starts when the `persistDifference` method is called, and
547
+ * finishes when the promise returned by that method completes.
548
+ *
549
+ */
550
+ async persistAndPause() {
551
+ this.isPaused = true;
552
+ this._cancelTimer();
553
+ // If the persisted state is still being read, wait until it finishes.
554
+ await this._ready;
555
+ // If a logOut is running, the current state belongs to the previous user, and must not be
556
+ // persisted. Wait until the logOut finishes, since it persists its initial-state (even
557
+ // though the persistor is paused). And if the state is being persisted, wait until it
558
+ // finishes. Since the persistor is paused, no new persistence process will start after that.
559
+ while (this._logOutsRunning > 0 || this.isPersisting) {
560
+ if (this._logOutsRunning > 0)
561
+ await this._waitForLogOut();
562
+ else
563
+ await this._waitForPersisting();
564
+ }
565
+ if (this.isInit && (this.lastPersistedState !== this.newestState)) {
566
+ const now = new Date();
567
+ await this._persist(now, this.newestState); // TypeScript forced cast
568
+ }
569
+ }
570
+ /**
571
+ * Resumes persistence by the `Persistor`, after calling `pause` or `persistAndPause`.
572
+ */
573
+ resume() {
574
+ this.isPaused = false;
575
+ if (this.isInit)
576
+ this.process(null, this.newestState);
577
+ }
578
+ }
579
+ exports.ProcessPersistence = ProcessPersistence;