kiss-for-react 2.0.0 → 2.0.2
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.
- package/README.md +6 -13
- package/lib/cjs/Esserializer/deserializer.js +82 -15
- package/lib/cjs/Hooks.js +9 -7
- package/lib/cjs/KissAction.js +173 -46
- package/lib/cjs/Store.js +94 -30
- package/lib/cjs/StoreProvider.js +99 -21
- package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
- package/lib/cjs/types/Hooks.d.ts.map +1 -1
- package/lib/cjs/types/KissAction.d.ts +69 -11
- package/lib/cjs/types/KissAction.d.ts.map +1 -1
- package/lib/cjs/types/Store.d.ts +15 -2
- package/lib/cjs/types/Store.d.ts.map +1 -1
- package/lib/cjs/types/StoreProvider.d.ts +21 -6
- package/lib/cjs/types/StoreProvider.d.ts.map +1 -1
- package/lib/esm/Esserializer/deserializer.mjs +82 -15
- package/lib/esm/Hooks.mjs +9 -7
- package/lib/esm/KissAction.mjs +173 -46
- package/lib/esm/Store.mjs +94 -30
- package/lib/esm/StoreProvider.mjs +103 -21
- package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
- package/lib/esm/types/Hooks.d.ts.map +1 -1
- package/lib/esm/types/KissAction.d.ts +69 -11
- package/lib/esm/types/KissAction.d.ts.map +1 -1
- package/lib/esm/types/Store.d.ts +15 -2
- package/lib/esm/types/Store.d.ts.map +1 -1
- package/lib/esm/types/StoreProvider.d.ts +21 -6
- package/lib/esm/types/StoreProvider.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
<img src="https://kissforreact.org/img/KISS_outline.svg" alt="Kiss for React Image" width="150" />
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## React state management for AI agents
|
|
4
|
+
|
|
5
|
+
Kiss helps AI agents stay on track, session after session, while spending fewer tokens.
|
|
6
|
+
|
|
7
|
+
* <img src="http://localhost:3001/img/claude.svg" alt="Claude" width="20" height="20" style={{verticalAlign: 'middle', marginRight: '0.4rem'}} />[Read Claude's opinion about Kiss](https://kissforreact.org/react/getting-started/claude-opinion-kiss)
|
|
8
|
+
* <img src="http://localhost:3001/img/openai.svg" alt="OpenAI" width="20" height="20" className="invert-in-dark" style={{verticalAlign: 'middle', marginRight: '0.4rem'}} />[Read Codex's opinion about Kiss](https://kissforreact.org/react/getting-started/codex-opinion-kiss)
|
|
4
9
|
|
|
5
10
|
- Helps the AI write well-structured code, separating business logic and UI
|
|
6
11
|
- Forces the AI to write predictable, testable, maintainable code
|
|
@@ -21,18 +26,6 @@ npm install kiss-for-react
|
|
|
21
26
|
|
|
22
27
|
### Linter and Quick fixes → [eslint-plugin-kiss-for-react](https://www.npmjs.com/package/eslint-plugin-kiss-for-react)
|
|
23
28
|
|
|
24
|
-
## Why it helps AI agents
|
|
25
|
-
|
|
26
|
-
Kiss improves AI-driven code generation by giving the AI strong guardrails
|
|
27
|
-
that force it to do the right thing while saving tokens.
|
|
28
|
-
[Read about it here](https://kissforreact.org/react/category/ai).
|
|
29
|
-
|
|
30
|
-
## For the human
|
|
31
|
-
|
|
32
|
-
AI can sometimes create code that works but seems alien when you read it.
|
|
33
|
-
With Kiss the code remains human-readable the whole time.
|
|
34
|
-
[Read about it here](https://kissforreact.org/react/category/ai).
|
|
35
|
-
|
|
36
29
|
---
|
|
37
30
|
|
|
38
31
|
# Overview
|
|
@@ -132,13 +132,31 @@ function _tryToConstruct(classObj, isEs6Class, parameters) {
|
|
|
132
132
|
}
|
|
133
133
|
}
|
|
134
134
|
/**
|
|
135
|
-
* Copies the deserialized values of `parsedObj` into `instance
|
|
135
|
+
* Copies the deserialized values of `parsedObj` into `instance`, and returns it.
|
|
136
|
+
*
|
|
136
137
|
* Properties with a getter or a setter (own or inherited from the class), and read-only
|
|
137
|
-
* properties
|
|
138
|
+
* properties inherited from the class, keep the value the constructor gave them. Own read-only
|
|
138
139
|
* properties with object values are updated in place (see `_copyInPlace`).
|
|
140
|
+
*
|
|
141
|
+
* Some saved values can't be set in `instance`: a primitive value in an own read-only property
|
|
142
|
+
* (for example, when the constructor calls `Object.freeze(this)`), or a new property in an
|
|
143
|
+
* object that can't get new properties. Then a copy of `instance` with these values is returned
|
|
144
|
+
* instead (see `_copyWithValues`).
|
|
139
145
|
*/
|
|
140
146
|
function _copyDeserializedValues(instance, parsedObj, classMapping, options) {
|
|
141
147
|
const { ignoreProperties, rawProperties } = options;
|
|
148
|
+
// The values that can't be set in `instance`.
|
|
149
|
+
const valuesForCopy = new Map();
|
|
150
|
+
const setValue = (key, value) => {
|
|
151
|
+
const own = Object.getOwnPropertyDescriptor(instance, key);
|
|
152
|
+
const canSet = own ? own.writable !== false : Object.isExtensible(instance);
|
|
153
|
+
if (canSet) {
|
|
154
|
+
(0, general_1.setOwnProperty)(instance, key, value);
|
|
155
|
+
}
|
|
156
|
+
else if (!own || !Object.is(own.value, value)) {
|
|
157
|
+
valuesForCopy.set(key, value);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
142
160
|
for (const savedKey in parsedObj) {
|
|
143
161
|
if (savedKey === constant_1.TYPE_FIELD || savedKey === constant_1.VALUE_FIELD) {
|
|
144
162
|
continue;
|
|
@@ -149,7 +167,7 @@ function _copyDeserializedValues(instance, parsedObj, classMapping, options) {
|
|
|
149
167
|
}
|
|
150
168
|
const value = parsedObj[savedKey];
|
|
151
169
|
if (rawProperties?.includes(key)) {
|
|
152
|
-
(
|
|
170
|
+
setValue(key, JSON.stringify(value));
|
|
153
171
|
continue;
|
|
154
172
|
}
|
|
155
173
|
const descriptor = _findPropertyDescriptor(instance, key);
|
|
@@ -159,31 +177,80 @@ function _copyDeserializedValues(instance, parsedObj, classMapping, options) {
|
|
|
159
177
|
continue;
|
|
160
178
|
}
|
|
161
179
|
if (descriptor.writable === false) {
|
|
162
|
-
// An inherited
|
|
163
|
-
if (
|
|
164
|
-
|
|
180
|
+
// An inherited value is shared by all instances, so it's not changed.
|
|
181
|
+
if (Object.prototype.hasOwnProperty.call(instance, key)) {
|
|
182
|
+
const current = instance[key];
|
|
183
|
+
setValue(key, (0, general_1.notObject)(current) || _isSavedPrimitive(value)
|
|
184
|
+
? deserializeFromParsedObjWithClassMapping(value, classMapping)
|
|
185
|
+
: _copyInPlace(current, value, classMapping));
|
|
165
186
|
}
|
|
166
187
|
continue;
|
|
167
188
|
}
|
|
168
189
|
}
|
|
169
|
-
(
|
|
190
|
+
setValue(key, deserializeFromParsedObjWithClassMapping(value, classMapping));
|
|
191
|
+
}
|
|
192
|
+
return valuesForCopy.size === 0 ? instance : _copyWithValues(instance, valuesForCopy);
|
|
193
|
+
}
|
|
194
|
+
/** Returns true if the saved `value` is a primitive, or a primitive JSON can't represent, like `NaN`. */
|
|
195
|
+
function _isSavedPrimitive(value) {
|
|
196
|
+
if ((0, general_1.notObject)(value)) {
|
|
197
|
+
return true;
|
|
170
198
|
}
|
|
171
|
-
|
|
199
|
+
const type = value[constant_1.TYPE_FIELD];
|
|
200
|
+
return type === constant_1.TYPE_UNDEFINED || type === constant_1.TYPE_NUMBER || type === constant_1.TYPE_BIGINT;
|
|
172
201
|
}
|
|
173
202
|
/**
|
|
174
|
-
* Copies the saved `source` into the existing `target`, in place: the built-in data
|
|
175
|
-
* entries of a Map), and the fields, like `_copyDeserializedValues` does.
|
|
176
|
-
*
|
|
203
|
+
* Copies the saved `source` into the existing object `target`, in place: the built-in data
|
|
204
|
+
* (like the entries of a Map), and the fields, like `_copyDeserializedValues` does.
|
|
205
|
+
* Returns `target`, or a copy of it, if some saved values can't be set in it
|
|
206
|
+
* (see `_copyDeserializedValues`).
|
|
177
207
|
*/
|
|
178
208
|
function _copyInPlace(target, source, classMapping) {
|
|
179
|
-
if ((0, general_1.notObject)(target)) {
|
|
180
|
-
return;
|
|
181
|
-
}
|
|
182
209
|
if (constant_1.VALUE_FIELD in source) {
|
|
183
210
|
const deserializeNested = (value) => deserializeFromParsedObjWithClassMapping(value, classMapping);
|
|
184
211
|
(0, builtins_1.findInheritedBuiltinType)(target)?.fill?.(target, source[constant_1.VALUE_FIELD], deserializeNested);
|
|
185
212
|
}
|
|
186
|
-
_copyDeserializedValues(target, source, classMapping, {});
|
|
213
|
+
return _copyDeserializedValues(target, source, classMapping, {});
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Returns a copy of `instance`, with the given `values` in place of its own properties, or as
|
|
217
|
+
* new properties. The copy has the same prototype and the same property attributes, and it's
|
|
218
|
+
* frozen, sealed, or can't get new properties, if `instance` is.
|
|
219
|
+
*
|
|
220
|
+
* The copy is created without calling the constructor, as `_createInstance` does when the
|
|
221
|
+
* constructor throws. So it doesn't have the private fields (`#field`) of the class.
|
|
222
|
+
*
|
|
223
|
+
* An instance of a class that extends a built-in class (like a Map) keeps its built-in data
|
|
224
|
+
* where a copy can't have it. So it is returned as is, without the `values`.
|
|
225
|
+
*/
|
|
226
|
+
function _copyWithValues(instance, values) {
|
|
227
|
+
if ((0, builtins_1.findInheritedBuiltinType)(instance)) {
|
|
228
|
+
return instance;
|
|
229
|
+
}
|
|
230
|
+
const copy = Object.create(Object.getPrototypeOf(instance));
|
|
231
|
+
const descriptors = Object.getOwnPropertyDescriptors(instance);
|
|
232
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
233
|
+
const descriptor = descriptors[key];
|
|
234
|
+
if (typeof key === 'string' && values.has(key)) {
|
|
235
|
+
descriptor.value = values.get(key);
|
|
236
|
+
}
|
|
237
|
+
Object.defineProperty(copy, key, descriptor);
|
|
238
|
+
}
|
|
239
|
+
for (const [key, value] of values) {
|
|
240
|
+
if (!Object.prototype.hasOwnProperty.call(descriptors, key)) {
|
|
241
|
+
Object.defineProperty(copy, key, { value, writable: true, enumerable: true, configurable: true });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (Object.isFrozen(instance)) {
|
|
245
|
+
Object.freeze(copy);
|
|
246
|
+
}
|
|
247
|
+
else if (Object.isSealed(instance)) {
|
|
248
|
+
Object.seal(copy);
|
|
249
|
+
}
|
|
250
|
+
else if (!Object.isExtensible(instance)) {
|
|
251
|
+
Object.preventExtensions(copy);
|
|
252
|
+
}
|
|
253
|
+
return copy;
|
|
187
254
|
}
|
|
188
255
|
/**
|
|
189
256
|
* Returns the descriptor of the property `key` of `obj`, which may be its own, or inherited
|
package/lib/cjs/Hooks.js
CHANGED
|
@@ -42,9 +42,11 @@ const Evt_1 = require("./Evt");
|
|
|
42
42
|
// never shows parts of two different states at the same time.
|
|
43
43
|
//
|
|
44
44
|
// - `useSelect`, `useObject` and `useAllState` use the React team's `useSyncExternalStoreWithSelector`,
|
|
45
|
-
// whose snapshot is the whole (immutable) state
|
|
46
|
-
//
|
|
47
|
-
//
|
|
45
|
+
// whose snapshot is the whole (immutable) state (read through the context: the live state,
|
|
46
|
+
// or, inside a `StoreSlice` not committed yet, the live state with the slice merged into it),
|
|
47
|
+
// and whose selector picks a part of it. It keeps the last selected value, and compares the
|
|
48
|
+
// new one with it (`Object.is` for `useSelect`, value by value for `useObject`), so an
|
|
49
|
+
// unchanged selection doesn't render the component.
|
|
48
50
|
//
|
|
49
51
|
// - `useIsWaiting`, `useIsFailed` and `useExceptionFor` read a boolean or an exception from the
|
|
50
52
|
// store, and subscribe to the status changes of the actions. `useIsStoreReady` reads a boolean
|
|
@@ -78,8 +80,8 @@ const Evt_1 = require("./Evt");
|
|
|
78
80
|
* Prefer `useSelect` because it's shorter.
|
|
79
81
|
*/
|
|
80
82
|
function useSelect(selector) {
|
|
81
|
-
const { store, getServerState } = useStoreContext();
|
|
82
|
-
return (0, with_selector_1.useSyncExternalStoreWithSelector)(store._subscribeState,
|
|
83
|
+
const { store, getState, getServerState } = useStoreContext();
|
|
84
|
+
return (0, with_selector_1.useSyncExternalStoreWithSelector)(store._subscribeState, getState, getServerState, selector, Object.is);
|
|
83
85
|
}
|
|
84
86
|
/**
|
|
85
87
|
* Returns a part of the store state:
|
|
@@ -132,8 +134,8 @@ function useSelector(selector) {
|
|
|
132
134
|
* so you can use it in the dependencies of an effect, or pass it to a memoized component.
|
|
133
135
|
*/
|
|
134
136
|
function useObject(selector) {
|
|
135
|
-
const { store, getServerState } = useStoreContext();
|
|
136
|
-
return (0, with_selector_1.useSyncExternalStoreWithSelector)(store._subscribeState,
|
|
137
|
+
const { store, getState, getServerState } = useStoreContext();
|
|
138
|
+
return (0, with_selector_1.useSyncExternalStoreWithSelector)(store._subscribeState, getState, getServerState, selector, _shallowEqual);
|
|
137
139
|
}
|
|
138
140
|
// Returns true if `a` and `b` are the same, or are both plain objects, arrays, `Map`s or `Set`s
|
|
139
141
|
// with the same values (compared with `Object.is`). The entries of a `Map` or `Set` must also be
|
package/lib/cjs/KissAction.js
CHANGED
|
@@ -17,7 +17,12 @@ var Poll;
|
|
|
17
17
|
* Otherwise, runs the action immediately and starts periodic polling.
|
|
18
18
|
*/
|
|
19
19
|
Poll["start"] = "start";
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Stop polling (cancels the timer and does not run the action).
|
|
22
|
+
* Also aborts the actions of the same polling key that were dispatched with `Poll.start` or
|
|
23
|
+
* `Poll.runNowAndRestart`, but had not started polling yet (for example, because they were
|
|
24
|
+
* still in an async `before()`), so that they don't start polling later.
|
|
25
|
+
*/
|
|
21
26
|
Poll["stop"] = "stop";
|
|
22
27
|
/**
|
|
23
28
|
* Run the action immediately and restart polling from now.
|
|
@@ -1753,7 +1758,10 @@ class KissAction {
|
|
|
1753
1758
|
/**
|
|
1754
1759
|
* Stops all polling at once, for all polling keys, as if `Poll.stop` was dispatched for each
|
|
1755
1760
|
* of them. This is probably useful during logout or similar scenarios. Runs that are already
|
|
1756
|
-
* in progress still finish, but no new ticks are dispatched.
|
|
1761
|
+
* in progress still finish, but no new ticks are dispatched. The actions with `Poll.start` or
|
|
1762
|
+
* `Poll.runNowAndRestart` that were dispatched before, but had not started polling yet (for
|
|
1763
|
+
* example, because they were still in an async `before()`) are aborted, so that they don't
|
|
1764
|
+
* start polling later.
|
|
1757
1765
|
*/
|
|
1758
1766
|
stopAllPolling() {
|
|
1759
1767
|
this.store._stopAllPolling();
|
|
@@ -2926,6 +2934,14 @@ exports.ActionStatus = ActionStatus;
|
|
|
2926
2934
|
* doesn't fail, and doesn't show errors. It also doesn't roll back the optimistic value, and
|
|
2927
2935
|
* doesn't reload, since that would change the state of the next user.
|
|
2928
2936
|
*
|
|
2937
|
+
* ## Aborting
|
|
2938
|
+
*
|
|
2939
|
+
* When the command is aborted (by `abort()`, or by `store.abort(ActionType)`) while its server
|
|
2940
|
+
* call runs, its result is ignored. When the call finishes, the server response is not applied,
|
|
2941
|
+
* the optimistic value is not rolled back, nothing is reloaded, and the call is not retried. The
|
|
2942
|
+
* optimistic value stays in the state. The command finishes silently, with
|
|
2943
|
+
* `isDispatchAborted: true`.
|
|
2944
|
+
*
|
|
2929
2945
|
* ## CheckInternet
|
|
2930
2946
|
*
|
|
2931
2947
|
* When combined with `checkInternet`, if there is no internet: no optimistic state is
|
|
@@ -3129,6 +3145,10 @@ class OptimisticCommand extends KissAction {
|
|
|
3129
3145
|
// the state of the next user. It's aborted, so it doesn't fail, and doesn't show errors.
|
|
3130
3146
|
if (this._hasStoppedRetrying)
|
|
3131
3147
|
throw error;
|
|
3148
|
+
// When the command was aborted, its result is ignored, so it doesn't roll back and
|
|
3149
|
+
// doesn't reload. The store finishes it silently.
|
|
3150
|
+
if (this.isAborted)
|
|
3151
|
+
throw error;
|
|
3132
3152
|
commandFailed = true;
|
|
3133
3153
|
commandError = error;
|
|
3134
3154
|
// Decides if it's safe to roll back (default: only if we are still seeing our own
|
|
@@ -3147,6 +3167,9 @@ class OptimisticCommand extends KissAction {
|
|
|
3147
3167
|
}
|
|
3148
3168
|
}
|
|
3149
3169
|
}
|
|
3170
|
+
// When the command was aborted while its server call ran, its result is ignored, so it
|
|
3171
|
+
// doesn't apply the server response, and doesn't reload. The store finishes it silently.
|
|
3172
|
+
this.abortSignal.throwIfAborted();
|
|
3150
3173
|
// Applies the server response, if any. This is outside the `try` above, because the command
|
|
3151
3174
|
// succeeded: if applying the response throws, the action fails with that error, but there
|
|
3152
3175
|
// is no rollback and no reload.
|
|
@@ -3169,6 +3192,8 @@ class OptimisticCommand extends KissAction {
|
|
|
3169
3192
|
});
|
|
3170
3193
|
if (doReload) {
|
|
3171
3194
|
const reloadResult = await this.reloadFromServer();
|
|
3195
|
+
// The command was aborted while reloading, so the reload result is ignored.
|
|
3196
|
+
this.abortSignal.throwIfAborted();
|
|
3172
3197
|
// Reads the current value again, because the state may have changed while reloading.
|
|
3173
3198
|
const apply = this.shouldApplyReload({
|
|
3174
3199
|
currentValue: this.getValueFromState(this.state),
|
|
@@ -3216,6 +3241,9 @@ class OptimisticCommand extends KissAction {
|
|
|
3216
3241
|
// An aborted command is not retried.
|
|
3217
3242
|
if (error instanceof StoreException_1.AbortDispatchException)
|
|
3218
3243
|
throw error;
|
|
3244
|
+
// A command aborted with `abort()` or `store.abort()` is not retried either.
|
|
3245
|
+
if (this.isAborted)
|
|
3246
|
+
throw error;
|
|
3219
3247
|
// When `dispatchSync` threw because the command is ASYNC, its result is ignored, so
|
|
3220
3248
|
// there's no point retrying.
|
|
3221
3249
|
if (this._isDiscardedByDispatchSync)
|
|
@@ -3231,9 +3259,12 @@ class OptimisticCommand extends KissAction {
|
|
|
3231
3259
|
throw error;
|
|
3232
3260
|
try {
|
|
3233
3261
|
// It also stops waiting right away when `clearInternalActionProps()` is called.
|
|
3262
|
+
// And when the command is aborted, in which case it keeps the abort error.
|
|
3234
3263
|
await this.store._waitRetryDelay(this, this._nextRetryDelay());
|
|
3235
3264
|
}
|
|
3236
|
-
catch {
|
|
3265
|
+
catch (waitError) {
|
|
3266
|
+
if (this.isAborted && !this.store._wereInternalActionPropsCleared(this))
|
|
3267
|
+
throw waitError;
|
|
3237
3268
|
throw this._stopRetrying();
|
|
3238
3269
|
}
|
|
3239
3270
|
}
|
|
@@ -3505,6 +3536,10 @@ exports.OptimisticCommand = OptimisticCommand;
|
|
|
3505
3536
|
* `true` meanwhile. The dispatches made while the key is taken apply their optimistic value,
|
|
3506
3537
|
* and then finish right away.
|
|
3507
3538
|
*
|
|
3539
|
+
* This includes a dispatch made while the server response is applied (for example, by
|
|
3540
|
+
* `store.dispatchWhen`, when the state with the response meets its condition). If that dispatch
|
|
3541
|
+
* changed the value, the dispatch that took the key sends one more request, with the new value.
|
|
3542
|
+
*
|
|
3508
3543
|
* ## Clearing
|
|
3509
3544
|
*
|
|
3510
3545
|
* `store.clearInternalActionProps()` (which is also called by `store.setShutDown(true)`)
|
|
@@ -3514,6 +3549,16 @@ exports.OptimisticCommand = OptimisticCommand;
|
|
|
3514
3549
|
* doesn't apply the server response, and doesn't call `onFinish`. It's aborted with an
|
|
3515
3550
|
* `AbortDispatchException`, so it doesn't fail, and doesn't show errors.
|
|
3516
3551
|
*
|
|
3552
|
+
* ## Aborting
|
|
3553
|
+
*
|
|
3554
|
+
* When the dispatch that sends the requests is aborted (by `abort()`, or by
|
|
3555
|
+
* `store.abort(ActionType)`) while a request is in flight, it stops when that request finishes,
|
|
3556
|
+
* or when the request rejects because of the `abortSignal`. It releases the key, doesn't send
|
|
3557
|
+
* follow-up requests, doesn't apply the server response, and doesn't call `onFinish`. It
|
|
3558
|
+
* finishes silently, with `isDispatchAborted: true`. The value in the state is not changed, so
|
|
3559
|
+
* a local change made while the request was in flight may not reach the server. The next
|
|
3560
|
+
* dispatch of the key takes the key, and sends its own value.
|
|
3561
|
+
*
|
|
3517
3562
|
* Notes:
|
|
3518
3563
|
* - It can be combined with `checkInternet`, both `{ dialog: true | false }` and
|
|
3519
3564
|
* `{ abort: true }`. If there is no internet, the optimistic value is not applied, and no
|
|
@@ -3611,7 +3656,8 @@ class OptimisticSync extends KissAction {
|
|
|
3611
3656
|
*
|
|
3612
3657
|
* Note `onFinish` is called in both success and failure scenarios. On success, it runs only
|
|
3613
3658
|
* after the state is stable for this key. On failure, it runs immediately after the request
|
|
3614
|
-
* fails (there is no further stabilization or follow-up).
|
|
3659
|
+
* fails (there is no further stabilization or follow-up). It's not called when the action is
|
|
3660
|
+
* aborted, or when `store.clearInternalActionProps()` released the key.
|
|
3615
3661
|
*
|
|
3616
3662
|
* Important: The key is released *before* `onFinish` runs. This means new dispatches for the
|
|
3617
3663
|
* same key may start a new request while `onFinish` is still running.
|
|
@@ -3694,6 +3740,10 @@ class OptimisticSync extends KissAction {
|
|
|
3694
3740
|
* If they are different, it means the state was changed after we sent the request, so we
|
|
3695
3741
|
* should send another request with the new value.
|
|
3696
3742
|
*
|
|
3743
|
+
* It's also called after the server response is applied, if applying it caused another
|
|
3744
|
+
* change of the state (for example, a save dispatched by `store.dispatchWhen`). Then, the
|
|
3745
|
+
* `sentValue` is the value that the server response put in the state.
|
|
3746
|
+
*
|
|
3697
3747
|
* Values are compared with `Object.is` (which is the same as `===`, except that `NaN` is equal
|
|
3698
3748
|
* to `NaN`). So, make sure `getValueFromState` returns the same object you applied, or
|
|
3699
3749
|
* override this method if you need custom equality logic.
|
|
@@ -3740,27 +3790,47 @@ class OptimisticSync extends KissAction {
|
|
|
3740
3790
|
// in flight (for example, on logout). So, stop here.
|
|
3741
3791
|
if (!this.store._hasOptimisticSyncKey(this))
|
|
3742
3792
|
throw this._clearedError();
|
|
3743
|
-
|
|
3793
|
+
// The action was aborted while the request was in flight, so its result is ignored: it
|
|
3794
|
+
// doesn't apply the server response, and doesn't send follow-up requests.
|
|
3795
|
+
this.abortSignal.throwIfAborted();
|
|
3796
|
+
let stateValue = this.getValueFromState(this.state);
|
|
3744
3797
|
// If the state changed while the request was in flight, sends a follow-up request with
|
|
3745
3798
|
// the current value, without applying the server response, since the state isn't stable.
|
|
3746
|
-
|
|
3747
|
-
if ((this.maxFollowUpRequests !== -1) && (requestCount > this.maxFollowUpRequests))
|
|
3748
|
-
throw new StoreException_1.StoreException(`Too many follow-up requests in action ${this.constructor.name} (> ${this.maxFollowUpRequests}).`);
|
|
3749
|
-
sentValue = stateValue;
|
|
3750
|
-
continue;
|
|
3751
|
-
}
|
|
3799
|
+
let sendAnother = this.ifShouldSendAnotherRequest({ stateValue, sentValue, requestCount });
|
|
3752
3800
|
// The state is stable for this key, so we apply the server response, if any.
|
|
3753
|
-
if (serverResponse !== null && serverResponse !== undefined) {
|
|
3801
|
+
if (!sendAnother && serverResponse !== null && serverResponse !== undefined) {
|
|
3754
3802
|
const newState = this.applyServerResponseToState(this.state, serverResponse);
|
|
3755
|
-
if (newState !== null)
|
|
3803
|
+
if (newState !== null) {
|
|
3756
3804
|
this._applyState(newState);
|
|
3805
|
+
// Applying the response may have changed the state again (for example, by a save of
|
|
3806
|
+
// this key dispatched by `store.dispatchWhen`). That save didn't send its value,
|
|
3807
|
+
// since this dispatch holds the key. So, if the value changed, sends a follow-up.
|
|
3808
|
+
if (this.state !== newState) {
|
|
3809
|
+
stateValue = this.getValueFromState(this.state);
|
|
3810
|
+
sendAnother = this.ifShouldSendAnotherRequest({
|
|
3811
|
+
stateValue,
|
|
3812
|
+
sentValue: this.getValueFromState(newState),
|
|
3813
|
+
requestCount,
|
|
3814
|
+
});
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3757
3817
|
}
|
|
3758
|
-
|
|
3818
|
+
if (!sendAnother)
|
|
3819
|
+
break;
|
|
3820
|
+
if ((this.maxFollowUpRequests !== -1) && (requestCount > this.maxFollowUpRequests))
|
|
3821
|
+
throw new StoreException_1.StoreException(`Too many follow-up requests in action ${this.constructor.name} (> ${this.maxFollowUpRequests}).`);
|
|
3822
|
+
sentValue = stateValue;
|
|
3759
3823
|
}
|
|
3760
3824
|
}
|
|
3761
3825
|
catch (error) {
|
|
3762
3826
|
if (!this.store._hasOptimisticSyncKey(this))
|
|
3763
3827
|
throw this._clearedError();
|
|
3828
|
+
// An aborted action releases the key, but doesn't call `onFinish`, since its result is
|
|
3829
|
+
// ignored. The store finishes it silently.
|
|
3830
|
+
if (this.isAborted) {
|
|
3831
|
+
this.store._releaseOptimisticSyncKey(this);
|
|
3832
|
+
throw error;
|
|
3833
|
+
}
|
|
3764
3834
|
finishError = error;
|
|
3765
3835
|
}
|
|
3766
3836
|
// Releases the key before `onFinish`, so that new dispatches can send requests.
|
|
@@ -3992,6 +4062,13 @@ let _deviceId = undefined;
|
|
|
3992
4062
|
* `onFinish`. It's aborted with an `AbortDispatchException`, so it doesn't fail, and doesn't
|
|
3993
4063
|
* show errors.
|
|
3994
4064
|
*
|
|
4065
|
+
* ## Aborting
|
|
4066
|
+
*
|
|
4067
|
+
* As in `OptimisticSync`, when the dispatch that sends the requests is aborted (by `abort()`, or
|
|
4068
|
+
* by `store.abort(ActionType)`) while a request is in flight, it stops when that request
|
|
4069
|
+
* finishes. It releases the key, doesn't send follow-up requests, doesn't apply the server
|
|
4070
|
+
* response, and doesn't call `onFinish`. It finishes silently, with `isDispatchAborted: true`.
|
|
4071
|
+
*
|
|
3995
4072
|
* Notes:
|
|
3996
4073
|
* - It can be combined with `checkInternet`, both `{ dialog: true | false }` and
|
|
3997
4074
|
* `{ abort: true }`. If there is no internet, the optimistic value is not applied, and no
|
|
@@ -4025,9 +4102,6 @@ class OptimisticSyncWithPush extends KissAction {
|
|
|
4025
4102
|
// The server revision informed by `informServerRevision()` during the current request, or
|
|
4026
4103
|
// `null` if it was not informed. It's reset before each request.
|
|
4027
4104
|
this._informedServerRevision = null;
|
|
4028
|
-
// True if `informServerRevision()`, during the current request, found that the push applied
|
|
4029
|
-
// while the request was in flight is older than the request. It's reset before each request.
|
|
4030
|
-
this._wasPushStale = false;
|
|
4031
4105
|
}
|
|
4032
4106
|
/**
|
|
4033
4107
|
* Optionally, override `optimisticSyncKeyParams()` to differentiate the coalescing by the
|
|
@@ -4145,9 +4219,12 @@ class OptimisticSyncWithPush extends KissAction {
|
|
|
4145
4219
|
// longer from a push. If a push was applied while the request was in flight, the server
|
|
4146
4220
|
// applied it before this request, so the pushed value is stale.
|
|
4147
4221
|
if (value > known.serverRevision) {
|
|
4148
|
-
|
|
4149
|
-
|
|
4150
|
-
|
|
4222
|
+
this.store._setOptimisticSyncRevision(this._key, {
|
|
4223
|
+
...known,
|
|
4224
|
+
serverRevision: value,
|
|
4225
|
+
isPush: false,
|
|
4226
|
+
hasStalePushValue: known.isPush || known.hasStalePushValue,
|
|
4227
|
+
});
|
|
4151
4228
|
}
|
|
4152
4229
|
}
|
|
4153
4230
|
/**
|
|
@@ -4157,7 +4234,8 @@ class OptimisticSyncWithPush extends KissAction {
|
|
|
4157
4234
|
*
|
|
4158
4235
|
* Note `onFinish` is called in both success and failure scenarios. On success, it runs only
|
|
4159
4236
|
* after the state is stable for this key. On failure, it runs immediately after the request
|
|
4160
|
-
* fails (there is no further stabilization or follow-up).
|
|
4237
|
+
* fails (there is no further stabilization or follow-up). It's not called when the action is
|
|
4238
|
+
* aborted, or when `store.clearInternalActionProps()` released the key.
|
|
4161
4239
|
*
|
|
4162
4240
|
* Important: The key is released *before* `onFinish` runs. This means new dispatches for the
|
|
4163
4241
|
* same key may start a new request while `onFinish` is still running.
|
|
@@ -4209,6 +4287,7 @@ class OptimisticSyncWithPush extends KissAction {
|
|
|
4209
4287
|
localRevision,
|
|
4210
4288
|
serverRevision: known.serverRevision,
|
|
4211
4289
|
isPush: false,
|
|
4290
|
+
hasStalePushValue: false,
|
|
4212
4291
|
localValue: this.getValueFromState(newState),
|
|
4213
4292
|
});
|
|
4214
4293
|
// Always applies the optimistic update immediately.
|
|
@@ -4236,7 +4315,6 @@ class OptimisticSyncWithPush extends KissAction {
|
|
|
4236
4315
|
this.lastSentValue = sentValue;
|
|
4237
4316
|
// Reset before each request, to detect if `informServerRevision()` was called.
|
|
4238
4317
|
this._informedServerRevision = null;
|
|
4239
|
-
this._wasPushStale = false;
|
|
4240
4318
|
// Sends the value, and gets the server response (may be null or undefined).
|
|
4241
4319
|
const serverResponse = await this.sendValueToServer(sentValue, sentLocalRevision, OptimisticSyncWithPush.deviceId());
|
|
4242
4320
|
// The keys were released by `store.clearInternalActionProps()` while the request was
|
|
@@ -4248,39 +4326,54 @@ class OptimisticSyncWithPush extends KissAction {
|
|
|
4248
4326
|
throw new StoreException_1.StoreException(`Action ${this.constructor.name} is an OptimisticSyncWithPush, which requires calling ` +
|
|
4249
4327
|
'`informServerRevision()` inside `sendValueToServer()`. ' +
|
|
4250
4328
|
'If you don\'t need server-push handling, use `OptimisticSync` instead.');
|
|
4329
|
+
// The action was aborted while the request was in flight, so its result is ignored: it
|
|
4330
|
+
// doesn't apply the server response, and doesn't send follow-up requests.
|
|
4331
|
+
this.abortSignal.throwIfAborted();
|
|
4332
|
+
// A push applied while a request was in flight turned out to be older than that request
|
|
4333
|
+
// (because of `informServerRevision()`, or of the echo of that request). So, the pushed
|
|
4334
|
+
// value in the state is stale, and the latest local value is put back in the state. It's
|
|
4335
|
+
// then sent by the follow-up request, if any, and otherwise it's the value the server has.
|
|
4251
4336
|
const known = this._revisionOf(this._key);
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
!Object.is(this.getValueFromState(this.state), known.localValue))
|
|
4258
|
-
this._applyState(this.applyOptimisticValueToState(this.state, known.localValue));
|
|
4337
|
+
if (known.hasStalePushValue) {
|
|
4338
|
+
this.store._setOptimisticSyncRevision(this._key, { ...known, hasStalePushValue: false });
|
|
4339
|
+
if (!Object.is(this.getValueFromState(this.state), known.localValue))
|
|
4340
|
+
this._applyState(this.applyOptimisticValueToState(this.state, known.localValue));
|
|
4341
|
+
}
|
|
4259
4342
|
// If the latest change was made locally (not by a push), and the local-revision advanced
|
|
4260
4343
|
// since this request was sent, the user changed the value while the request was in
|
|
4261
4344
|
// flight. So, sends a follow-up request with the current value, without applying the
|
|
4262
4345
|
// server response, since the state isn't stable.
|
|
4263
|
-
|
|
4264
|
-
if ((this.maxFollowUpRequests !== -1) && (requestCount > this.maxFollowUpRequests))
|
|
4265
|
-
throw new StoreException_1.StoreException(`Too many follow-up requests in action ${this.constructor.name} (> ${this.maxFollowUpRequests}).`);
|
|
4266
|
-
sentValue = this.getValueFromState(this.state);
|
|
4267
|
-
sentLocalRevision = known.localRevision;
|
|
4268
|
-
continue;
|
|
4269
|
-
}
|
|
4346
|
+
let sendAnother = this._hasLocalChangeAfter(sentLocalRevision);
|
|
4270
4347
|
// The state is stable for this key, so we apply the server response, if any, but only
|
|
4271
4348
|
// if it's not stale (no newer server revision is known, for example from a push).
|
|
4272
|
-
if (serverResponse !== null && serverResponse !== undefined &&
|
|
4273
|
-
informedServerRevision >=
|
|
4349
|
+
if (!sendAnother && serverResponse !== null && serverResponse !== undefined &&
|
|
4350
|
+
informedServerRevision >= this._revisionOf(this._key).serverRevision) {
|
|
4274
4351
|
const newState = this.applyServerResponseToState(this.state, serverResponse);
|
|
4275
|
-
if (newState !== null)
|
|
4352
|
+
if (newState !== null) {
|
|
4276
4353
|
this._applyState(newState);
|
|
4354
|
+
// Applying the response may have dispatched a save of this key (for example, by
|
|
4355
|
+
// `store.dispatchWhen`). That save didn't send its value, since this dispatch holds
|
|
4356
|
+
// the key. So, sends it in a follow-up request.
|
|
4357
|
+
sendAnother = this._hasLocalChangeAfter(sentLocalRevision);
|
|
4358
|
+
}
|
|
4277
4359
|
}
|
|
4278
|
-
|
|
4360
|
+
if (!sendAnother)
|
|
4361
|
+
break;
|
|
4362
|
+
if ((this.maxFollowUpRequests !== -1) && (requestCount > this.maxFollowUpRequests))
|
|
4363
|
+
throw new StoreException_1.StoreException(`Too many follow-up requests in action ${this.constructor.name} (> ${this.maxFollowUpRequests}).`);
|
|
4364
|
+
sentValue = this.getValueFromState(this.state);
|
|
4365
|
+
sentLocalRevision = this._revisionOf(this._key).localRevision;
|
|
4279
4366
|
}
|
|
4280
4367
|
}
|
|
4281
4368
|
catch (error) {
|
|
4282
4369
|
if (!this.store._hasOptimisticSyncKey(this))
|
|
4283
4370
|
throw this._clearedError();
|
|
4371
|
+
// An aborted action releases the key, but doesn't call `onFinish`, since its result is
|
|
4372
|
+
// ignored. The store finishes it silently.
|
|
4373
|
+
if (this.isAborted) {
|
|
4374
|
+
this.store._releaseOptimisticSyncKey(this);
|
|
4375
|
+
throw error;
|
|
4376
|
+
}
|
|
4284
4377
|
finishError = error;
|
|
4285
4378
|
}
|
|
4286
4379
|
// Releases the key before `onFinish`, so that new dispatches can send requests.
|
|
@@ -4299,6 +4392,14 @@ class OptimisticSyncWithPush extends KissAction {
|
|
|
4299
4392
|
_revisionOf(key) {
|
|
4300
4393
|
return _revisionOf(this.store, key, this.getServerRevisionFromState(this.state, key));
|
|
4301
4394
|
}
|
|
4395
|
+
/**
|
|
4396
|
+
* True if the latest change of the key of this dispatch was made locally (not by a push), and
|
|
4397
|
+
* is newer than the given local-revision.
|
|
4398
|
+
*/
|
|
4399
|
+
_hasLocalChangeAfter(localRevision) {
|
|
4400
|
+
const known = this._revisionOf(this._key);
|
|
4401
|
+
return !known.isPush && (known.localRevision > localRevision);
|
|
4402
|
+
}
|
|
4302
4403
|
_clearedError() {
|
|
4303
4404
|
return (0, StoreException_1.kissAbort)('The internal action props were cleared, so the action stopped syncing.');
|
|
4304
4405
|
}
|
|
@@ -4341,6 +4442,7 @@ function _revisionOf(store, key, serverRevisionFromState) {
|
|
|
4341
4442
|
localRevision: kept?.localRevision ?? 0,
|
|
4342
4443
|
serverRevision: Math.max(kept?.serverRevision ?? -1, serverRevisionFromState),
|
|
4343
4444
|
isPush: kept?.isPush ?? false,
|
|
4445
|
+
hasStalePushValue: kept?.hasStalePushValue ?? false,
|
|
4344
4446
|
localValue: kept?.localValue,
|
|
4345
4447
|
};
|
|
4346
4448
|
}
|
|
@@ -4359,12 +4461,18 @@ function _revisionOf(store, key, serverRevisionFromState) {
|
|
|
4359
4461
|
*
|
|
4360
4462
|
* 1. If the push is not newer than the newest known server revision for the key (considering
|
|
4361
4463
|
* both the revision kept by Kiss, and `getServerRevisionFromState()`), it's stale or out of
|
|
4362
|
-
* order, so it's ignored.
|
|
4464
|
+
* order, so it's ignored. There is one exception: the echo of the latest request of this
|
|
4465
|
+
* device, when the server response already informed its server revision (with
|
|
4466
|
+
* `informServerRevision`), but the state doesn't have that revision yet. It's applied as in
|
|
4467
|
+
* step 3, so that `applyServerPushToState` saves the server revision in the state.
|
|
4363
4468
|
*
|
|
4364
4469
|
* 2. If the push is the echo of an older request of this same device (the user changed the
|
|
4365
4470
|
* value again after that request was sent), it's not applied, since the state already has a
|
|
4366
4471
|
* newer local value. Its server revision is still recorded, but it doesn't count as a push,
|
|
4367
|
-
* so the newer local value is still sent in a follow-up request.
|
|
4472
|
+
* so the newer local value is still sent in a follow-up request. If a push from another
|
|
4473
|
+
* device was applied before this echo, that push is older than the request, so its value is
|
|
4474
|
+
* stale: the request in flight puts the latest local value back in the state when it
|
|
4475
|
+
* finishes, and sends it in the follow-up request.
|
|
4368
4476
|
*
|
|
4369
4477
|
* 3. Otherwise (a push from another device, or the echo of the latest request of this device),
|
|
4370
4478
|
* it's applied with `applyServerPushToState`, and recorded as the latest change of the key.
|
|
@@ -4458,16 +4566,33 @@ class ServerPush extends KissAction {
|
|
|
4458
4566
|
if (typeof serverRevision !== 'number' || !Number.isFinite(serverRevision))
|
|
4459
4567
|
throw new StoreException_1.StoreException(`Action ${this.constructor.name} pushed an invalid server revision: ` +
|
|
4460
4568
|
`it must be a finite number, but got ${String(serverRevision)}.`);
|
|
4461
|
-
const
|
|
4569
|
+
const serverRevisionFromState = this.getServerRevisionFromState(this.state, key);
|
|
4570
|
+
const known = _revisionOf(this.store, key, serverRevisionFromState);
|
|
4571
|
+
const isSelf = (deviceId === OptimisticSyncWithPush.deviceId());
|
|
4572
|
+
// The echo of the latest request of this device, whose server revision is already known,
|
|
4573
|
+
// because the server response came first, and informed it with `informServerRevision`. But
|
|
4574
|
+
// that revision is not in the state yet. So, the echo is applied, which lets
|
|
4575
|
+
// `applyServerPushToState` save the revision in the state. Otherwise, a stale push could
|
|
4576
|
+
// overwrite the value after the app restarts with the persisted state.
|
|
4577
|
+
const isEchoOfInformedRevision = isSelf &&
|
|
4578
|
+
(serverRevision === known.serverRevision) &&
|
|
4579
|
+
(serverRevisionFromState < serverRevision) &&
|
|
4580
|
+
(localRevision >= known.localRevision);
|
|
4462
4581
|
// Ignores stale and out-of-order pushes.
|
|
4463
|
-
if (serverRevision <= known.serverRevision)
|
|
4582
|
+
if (serverRevision <= known.serverRevision && !isEchoOfInformedRevision)
|
|
4464
4583
|
return null;
|
|
4465
|
-
const isSelf = (deviceId === OptimisticSyncWithPush.deviceId());
|
|
4466
4584
|
// The echo of an older request of this device: the state already has a newer local value.
|
|
4467
4585
|
// So, it only records the server revision. It does NOT apply the push, and does NOT count
|
|
4468
4586
|
// as a push, since then the newer local value would not be sent in a follow-up request.
|
|
4587
|
+
// If the value in the state came from a push, that push is older than this echo, so the
|
|
4588
|
+
// pushed value is stale. Then, the request in flight puts the latest local value back.
|
|
4469
4589
|
if (isSelf && (localRevision < known.localRevision)) {
|
|
4470
|
-
this.store._setOptimisticSyncRevision(key, {
|
|
4590
|
+
this.store._setOptimisticSyncRevision(key, {
|
|
4591
|
+
...known,
|
|
4592
|
+
serverRevision,
|
|
4593
|
+
isPush: false,
|
|
4594
|
+
hasStalePushValue: known.isPush || known.hasStalePushValue,
|
|
4595
|
+
});
|
|
4471
4596
|
return null;
|
|
4472
4597
|
}
|
|
4473
4598
|
// Safe to apply (a push from another device, or the echo of the latest local value).
|
|
@@ -4481,6 +4606,8 @@ class ServerPush extends KissAction {
|
|
|
4481
4606
|
localRevision: isSelf ? Math.max(known.localRevision, localRevision) : known.localRevision,
|
|
4482
4607
|
serverRevision,
|
|
4483
4608
|
isPush: (newState === null) ? known.isPush : true,
|
|
4609
|
+
// An applied push replaces the stale pushed value in the state, if any.
|
|
4610
|
+
hasStalePushValue: (newState === null) ? known.hasStalePushValue : false,
|
|
4484
4611
|
});
|
|
4485
4612
|
return newState;
|
|
4486
4613
|
}
|