@hyper-fetch/core 9.7.0 → 9.8.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.
package/dist/index.mjs CHANGED
@@ -21,236 +21,164 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  //#endregion
24
- //#region src/optimistic/optimistic.utils.ts
25
- var isComparableId = (value) => typeof value === "string" || typeof value === "number";
24
+ //#region src/plugin/plugin.ts
26
25
  /**
27
- * Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
28
- * strings match each other the same way route params do (`"1"` matches `1`).
26
+ * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.
27
+ * Extend this to build devtools, logging, analytics, or custom side-effect plugins.
29
28
  */
30
- var isOptimisticMatch = (item, match, key = "id") => {
31
- if (typeof match === "function") return !!match(item);
32
- if (item === null || typeof item !== "object") return false;
33
- const value = item[key];
34
- if (Object.is(value, match)) return true;
35
- return isComparableId(value) && isComparableId(match) && String(value) === String(match);
36
- };
37
- var assertList = (list) => {
38
- if (!Array.isArray(list)) throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
39
- return list;
40
- };
41
- var assertEntry = (data) => {
42
- if (data === null || typeof data !== "object" || Array.isArray(data)) throw new TypeError("Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list");
43
- return data;
44
- };
45
- var addToField = (item, field, by) => {
46
- const value = item[field];
47
- return {
48
- ...item,
49
- [field]: (typeof value === "number" ? value : 0) + by
29
+ var Plugin = class {
30
+ name;
31
+ data;
32
+ client = void 0;
33
+ pluginMethods = {};
34
+ constructor(config) {
35
+ this.config = config;
36
+ this.name = config.name;
37
+ if (config.data) this.data = config.data;
38
+ }
39
+ /** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */
40
+ initialize = (client) => {
41
+ this.client = client;
42
+ return this;
50
43
  };
51
- };
52
- /**
53
- * Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.
54
- */
55
- var mapMatching = (list, { match, key }, map) => {
56
- const items = assertList(list);
57
- let changed = false;
58
- const next = items.map((item) => {
59
- if (!isOptimisticMatch(item, match, key)) return item;
60
- changed = true;
61
- return map(item);
62
- });
63
- return changed ? next : items;
64
- };
65
- var patchItems = (list, selector, fields) => {
66
- return mapMatching(list, selector, (item) => ({
67
- ...item,
68
- ...fields
69
- }));
70
- };
71
- var insertItem = (list, item, options) => {
72
- const items = assertList(list);
73
- const at = options?.at ?? "end";
74
- if (at === "start") return [item, ...items];
75
- if (at === "end") return [...items, item];
76
- const next = [...items];
77
- next.splice(at, 0, item);
78
- return next;
79
- };
80
- var removeItems = (list, { match, key }) => {
81
- const items = assertList(list);
82
- const next = items.filter((item) => !isOptimisticMatch(item, match, key));
83
- return next.length === items.length ? items : next;
84
- };
85
- var incrementItems = (list, selector, { field, by }) => {
86
- return mapMatching(list, selector, (item) => addToField(item, field, by));
87
- };
88
- var incrementField = (data, field, by) => {
89
- return addToField(assertEntry(data), field, by);
90
- };
91
- /**
92
- * Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when
93
- * the list did not change.
94
- */
95
- var updateListField = (data, field, update) => {
96
- const entry = assertEntry(data);
97
- const list = entry[field] ?? [];
98
- const next = update(assertList(list));
99
- return next === list ? entry : {
100
- ...entry,
101
- [field]: next
44
+ /** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */
45
+ trigger = (method, data) => {
46
+ const callback = this.pluginMethods[method];
47
+ if (callback) callback(data);
102
48
  };
103
- };
104
- //#endregion
105
- //#region src/optimistic/optimistic.ts
106
- /**
107
- * One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its
108
- * `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.
109
- * Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.
110
- */
111
- var OptimisticOperation = class OptimisticOperation {
112
- /** @internal */
113
- target;
114
- /** @internal */
115
- allVariants;
116
- /** @internal */
117
- update;
118
- /** @internal */
119
- onRollback = void 0;
120
- /** @internal */
121
- onCommit = void 0;
122
- constructor(options) {
123
- this.target = options.target;
124
- this.allVariants = options.allVariants;
125
- this.update = options.update;
126
- this.onRollback = options.onRollback;
127
- this.onCommit = options.onCommit;
128
- }
129
49
  /**
130
- * Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
131
- * the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
132
- * `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
133
- * is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
134
- * Without it nothing is undone locally and the target is refetched.
50
+ * Callback that will be executed when plugin is mounted
135
51
  */
136
- rollback(callback) {
137
- return new OptimisticOperation({
138
- target: this.target,
139
- allVariants: this.allVariants,
140
- update: this.update,
141
- onRollback: callback,
142
- onCommit: this.onCommit
143
- });
144
- }
52
+ onMount = (callback) => {
53
+ this.pluginMethods.onMount = callback;
54
+ return this;
55
+ };
145
56
  /**
146
- * Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and
147
- * returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves
148
- * the data as it is. Must be synchronous.
57
+ * Callback that will be executed when plugin is unmounted
149
58
  */
150
- commit(callback) {
151
- return new OptimisticOperation({
152
- target: this.target,
153
- allVariants: this.allVariants,
154
- update: this.update,
155
- onRollback: this.onRollback,
156
- onCommit: callback
157
- });
158
- }
159
- };
160
- var createTarget = (target, allVariants) => {
161
- const operation = (update) => {
162
- return new OptimisticOperation({
163
- target,
164
- allVariants,
165
- update
166
- });
59
+ onUnmount = (callback) => {
60
+ this.pluginMethods.onUnmount = callback;
61
+ return this;
167
62
  };
168
- const createListHelpers = (onList) => ({
169
- patch: (match, fields, options) => {
170
- return operation(onList((list) => patchItems(list, {
171
- match,
172
- key: options?.key
173
- }, fields)));
174
- },
175
- insert: (item, options) => {
176
- return operation(onList((list) => insertItem(list, item, options)));
177
- },
178
- remove: (match, options) => {
179
- return operation(onList((list) => removeItems(list, {
180
- match,
181
- key: options?.key
182
- })));
183
- },
184
- increment: (match, field, by, options) => {
185
- return operation(onList((list) => incrementItems(list, {
186
- match,
187
- key: options?.key
188
- }, {
189
- field,
190
- by
191
- })));
192
- }
193
- });
194
- const listHelpers = createListHelpers((update) => (data) => update(data));
195
- return {
196
- ...listHelpers,
197
- set: (updater) => operation(updater),
198
- increment: (...args) => {
199
- if (args.length >= 3) {
200
- const [match, field, by, options] = args;
201
- return listHelpers.increment(match, field, by, options);
202
- }
203
- const [field, by] = args;
204
- return operation((data) => incrementField(data, field, by));
205
- },
206
- list: (field) => {
207
- return createListHelpers((update) => (data) => updateListField(data, field, update));
208
- }
63
+ /**
64
+ * Callback that will be executed when request is created
65
+ */
66
+ onRequestCreate = (callback) => {
67
+ this.pluginMethods.onRequestCreate = callback;
68
+ return this;
209
69
  };
210
- };
211
- var optimisticFactory = (target) => createTarget(target, false);
212
- optimisticFactory.all = (target) => createTarget(target, true);
213
- /**
214
- * Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
215
- * `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
216
- * the targets once the last pending mutation on them is done.
217
- *
218
- * - `optimistic(getTodos)` - the entry of this request (its params and query params)
219
- * - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
220
- *
221
- * Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
222
- * `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
223
- *
224
- * @example
225
- * optimistic(getTodos)
226
- * .patch(params.todoId, payload)
227
- * .rollback(({ data, previous }) => {
228
- * const before = previous.find((todo) => todo.id === params.todoId);
229
- * return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
230
- * });
231
- */
232
- var optimistic = optimisticFactory;
233
- //#endregion
234
- //#region src/constants/time.constants.ts
235
- var Time = /* @__PURE__ */ function(Time) {
236
- Time[Time["SEC"] = 1e3] = "SEC";
237
- Time[Time["MIN"] = 6e4] = "MIN";
238
- Time[Time["HOUR"] = 36e5] = "HOUR";
239
- Time[Time["DAY"] = 864e5] = "DAY";
240
- Time[Time["WEEK"] = 6048e5] = "WEEK";
241
- Time[Time["MONTH_30"] = 2592e6] = "MONTH_30";
242
- Time[Time["MONTH_31"] = 26784e5] = "MONTH_31";
243
- Time[Time["YEAR"] = 31536e6] = "YEAR";
244
- Time[Time["YEAR_LEAP"] = 316224e5] = "YEAR_LEAP";
245
- return Time;
246
- }({});
247
- //#endregion
248
- //#region src/request/request.hooks.ts
249
- var HOOK_NAMES = [
250
- "onBeforeSent",
251
- "onRequestStart",
252
- "onResponseStart",
253
- "onUploadProgress",
70
+ /**
71
+ * Callback that will be executed when request gets triggered
72
+ */
73
+ onRequestTrigger = (callback) => {
74
+ this.pluginMethods.onRequestTrigger = callback;
75
+ return this;
76
+ };
77
+ /**
78
+ * Callback that will be executed when request starts
79
+ */
80
+ onRequestStart = (callback) => {
81
+ this.pluginMethods.onRequestStart = callback;
82
+ return this;
83
+ };
84
+ /**
85
+ * Callback that will be executed when response is successful
86
+ */
87
+ onRequestSuccess = (callback) => {
88
+ this.pluginMethods.onRequestSuccess = callback;
89
+ return this;
90
+ };
91
+ /**
92
+ * Callback that will be executed when response is failed
93
+ */
94
+ onRequestError = (callback) => {
95
+ this.pluginMethods.onRequestError = callback;
96
+ return this;
97
+ };
98
+ /**
99
+ * Callback that will be executed when response is finished
100
+ */
101
+ onRequestFinished = (callback) => {
102
+ this.pluginMethods.onRequestFinished = callback;
103
+ return this;
104
+ };
105
+ /** Called when the dispatcher storage is fully cleared */
106
+ onDispatcherCleared = (callback) => {
107
+ this.pluginMethods.onDispatcherCleared = callback;
108
+ return this;
109
+ };
110
+ /** Called when a dispatcher queue has no more pending requests */
111
+ onDispatcherQueueDrained = (callback) => {
112
+ this.pluginMethods.onDispatcherQueueDrained = callback;
113
+ return this;
114
+ };
115
+ /** Called when a dispatcher queue transitions to running, paused, or stopped */
116
+ onDispatcherQueueRunning = (callback) => {
117
+ this.pluginMethods.onDispatcherQueueRunning = callback;
118
+ return this;
119
+ };
120
+ /** Called when a new item is added to a dispatcher queue */
121
+ onDispatcherItemAdded = (callback) => {
122
+ this.pluginMethods.onDispatcherItemAdded = callback;
123
+ return this;
124
+ };
125
+ /** Called when an item is removed from a dispatcher queue */
126
+ onDispatcherItemDeleted = (callback) => {
127
+ this.pluginMethods.onDispatcherItemDeleted = callback;
128
+ return this;
129
+ };
130
+ /** Called when a new dispatcher queue is created */
131
+ onDispatcherQueueCreated = (callback) => {
132
+ this.pluginMethods.onDispatcherQueueCreated = callback;
133
+ return this;
134
+ };
135
+ /** Called when an entire dispatcher queue is cleared */
136
+ onDispatcherQueueCleared = (callback) => {
137
+ this.pluginMethods.onDispatcherQueueCleared = callback;
138
+ return this;
139
+ };
140
+ /** Called when a cache entry is created or updated */
141
+ onCacheItemChange = (callback) => {
142
+ this.pluginMethods.onCacheItemChange = callback;
143
+ return this;
144
+ };
145
+ /** Called when a cache entry is deleted */
146
+ onCacheItemDelete = (callback) => {
147
+ this.pluginMethods.onCacheItemDelete = callback;
148
+ return this;
149
+ };
150
+ /** Called when a cache entry is invalidated */
151
+ onCacheItemInvalidate = (callback) => {
152
+ this.pluginMethods.onCacheItemInvalidate = callback;
153
+ return this;
154
+ };
155
+ /** Called when the adapter fetcher is about to execute a request */
156
+ onAdapterFetch = (callback) => {
157
+ this.pluginMethods.onAdapterFetch = callback;
158
+ return this;
159
+ };
160
+ };
161
+ //#endregion
162
+ //#region src/constants/time.constants.ts
163
+ var Time = /* @__PURE__ */ function(Time) {
164
+ Time[Time["SEC"] = 1e3] = "SEC";
165
+ Time[Time["MIN"] = 6e4] = "MIN";
166
+ Time[Time["HOUR"] = 36e5] = "HOUR";
167
+ Time[Time["DAY"] = 864e5] = "DAY";
168
+ Time[Time["WEEK"] = 6048e5] = "WEEK";
169
+ Time[Time["MONTH_30"] = 2592e6] = "MONTH_30";
170
+ Time[Time["MONTH_31"] = 26784e5] = "MONTH_31";
171
+ Time[Time["YEAR"] = 31536e6] = "YEAR";
172
+ Time[Time["YEAR_LEAP"] = 316224e5] = "YEAR_LEAP";
173
+ return Time;
174
+ }({});
175
+ //#endregion
176
+ //#region src/request/request.hooks.ts
177
+ var HOOK_NAMES = [
178
+ "onBeforeSent",
179
+ "onRequestStart",
180
+ "onResponseStart",
181
+ "onUploadProgress",
254
182
  "onDownloadProgress",
255
183
  "onResponse",
256
184
  "onRemove"
@@ -1061,63 +989,273 @@ var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
1061
989
  /** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
1062
990
  var SAFE_HTTP_METHODS = [HttpMethods.GET, HttpMethods.QUERY];
1063
991
  //#endregion
1064
- //#region src/utils/error.utils.ts
992
+ //#region src/optimistic/optimistic.utils.ts
993
+ var isComparableId = (value) => typeof value === "string" || typeof value === "number";
1065
994
  /**
1066
- * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request
1067
- * lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the
1068
- * lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).
1069
- * @internal
1070
- * @param error value thrown by the user code
995
+ * Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
996
+ * strings match each other the same way route params do (`"1"` matches `1`).
1071
997
  */
1072
- var throwOutsideLifecycle = (error) => {
1073
- setTimeout(() => {
1074
- throw error;
1075
- });
998
+ var isOptimisticMatch = (item, match, key = "id") => {
999
+ if (typeof match === "function") return !!match(item);
1000
+ if (item === null || typeof item !== "object") return false;
1001
+ const value = item[key];
1002
+ if (Object.is(value, match)) return true;
1003
+ return isComparableId(value) && isComparableId(match) && String(value) === String(match);
1004
+ };
1005
+ var assertList = (list) => {
1006
+ if (!Array.isArray(list)) throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
1007
+ return list;
1008
+ };
1009
+ var assertEntry = (data) => {
1010
+ if (data === null || typeof data !== "object" || Array.isArray(data)) throw new TypeError("Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list");
1011
+ return data;
1012
+ };
1013
+ var addToField = (item, field, by) => {
1014
+ const value = item[field];
1015
+ return {
1016
+ ...item,
1017
+ [field]: (typeof value === "number" ? value : 0) + by
1018
+ };
1076
1019
  };
1077
1020
  /**
1078
- * Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on
1079
- * and the error is thrown outside of it.
1080
- * @internal
1081
- * @param callback code of the user to run
1082
- * @returns `true` when the callback finished, `false` when it threw
1021
+ * Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.
1083
1022
  */
1084
- var runUserCode = (callback) => {
1085
- try {
1086
- callback();
1087
- return true;
1088
- } catch (error) {
1089
- throwOutsideLifecycle(error);
1090
- return false;
1091
- }
1023
+ var mapMatching = (list, { match, key }, map) => {
1024
+ const items = assertList(list);
1025
+ let changed = false;
1026
+ const next = items.map((item) => {
1027
+ if (!isOptimisticMatch(item, match, key)) return item;
1028
+ changed = true;
1029
+ return map(item);
1030
+ });
1031
+ return changed ? next : items;
1092
1032
  };
1093
- //#endregion
1094
- //#region src/utils/uuid.utils.ts
1095
- var getUniqueRequestId = (request) => {
1096
- return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
1033
+ var patchItems = (list, selector, fields) => {
1034
+ return mapMatching(list, selector, (item) => ({
1035
+ ...item,
1036
+ ...fields
1037
+ }));
1097
1038
  };
1098
- //#endregion
1099
- //#region src/utils/emitter.utils.ts
1100
- var import_events = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1101
- var R = typeof Reflect === "object" ? Reflect : null;
1102
- var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply(target, receiver, args) {
1103
- return Function.prototype.apply.call(target, receiver, args);
1104
- };
1105
- var ReflectOwnKeys;
1106
- if (R && typeof R.ownKeys === "function") ReflectOwnKeys = R.ownKeys;
1107
- else if (Object.getOwnPropertySymbols) ReflectOwnKeys = function ReflectOwnKeys(target) {
1108
- return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
1109
- };
1110
- else ReflectOwnKeys = function ReflectOwnKeys(target) {
1111
- return Object.getOwnPropertyNames(target);
1039
+ var insertItem = (list, item, options) => {
1040
+ const items = assertList(list);
1041
+ const at = options?.at ?? "end";
1042
+ if (at === "start") return [item, ...items];
1043
+ if (at === "end") return [...items, item];
1044
+ const next = [...items];
1045
+ next.splice(at, 0, item);
1046
+ return next;
1047
+ };
1048
+ var removeItems = (list, { match, key }) => {
1049
+ const items = assertList(list);
1050
+ const next = items.filter((item) => !isOptimisticMatch(item, match, key));
1051
+ return next.length === items.length ? items : next;
1052
+ };
1053
+ var incrementItems = (list, selector, { field, by }) => {
1054
+ return mapMatching(list, selector, (item) => addToField(item, field, by));
1055
+ };
1056
+ var incrementField = (data, field, by) => {
1057
+ return addToField(assertEntry(data), field, by);
1058
+ };
1059
+ /**
1060
+ * Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when
1061
+ * the list did not change.
1062
+ */
1063
+ var updateListField = (data, field, update) => {
1064
+ const entry = assertEntry(data);
1065
+ const list = entry[field] ?? [];
1066
+ const next = update(assertList(list));
1067
+ return next === list ? entry : {
1068
+ ...entry,
1069
+ [field]: next
1112
1070
  };
1113
- function ProcessEmitWarning(warning) {
1114
- if (console && console.warn) console.warn(warning);
1071
+ };
1072
+ //#endregion
1073
+ //#region src/optimistic/optimistic.ts
1074
+ /**
1075
+ * One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its
1076
+ * `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.
1077
+ * Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.
1078
+ */
1079
+ var OptimisticOperation = class OptimisticOperation {
1080
+ /** @internal */
1081
+ target;
1082
+ /** @internal */
1083
+ allVariants;
1084
+ /** @internal */
1085
+ update;
1086
+ /** @internal */
1087
+ onRollback = void 0;
1088
+ /** @internal */
1089
+ onCommit = void 0;
1090
+ constructor(options) {
1091
+ this.target = options.target;
1092
+ this.allVariants = options.allVariants;
1093
+ this.update = options.update;
1094
+ this.onRollback = options.onRollback;
1095
+ this.onCommit = options.onCommit;
1115
1096
  }
1116
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
1117
- return value !== value;
1118
- };
1119
- function EventEmitter() {
1120
- EventEmitter.init.call(this);
1097
+ /**
1098
+ * Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
1099
+ * the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
1100
+ * `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
1101
+ * is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
1102
+ * Without it nothing is undone locally and the target is refetched.
1103
+ */
1104
+ rollback(callback) {
1105
+ return new OptimisticOperation({
1106
+ target: this.target,
1107
+ allVariants: this.allVariants,
1108
+ update: this.update,
1109
+ onRollback: callback,
1110
+ onCommit: this.onCommit
1111
+ });
1112
+ }
1113
+ /**
1114
+ * Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and
1115
+ * returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves
1116
+ * the data as it is. Must be synchronous.
1117
+ */
1118
+ commit(callback) {
1119
+ return new OptimisticOperation({
1120
+ target: this.target,
1121
+ allVariants: this.allVariants,
1122
+ update: this.update,
1123
+ onRollback: this.onRollback,
1124
+ onCommit: callback
1125
+ });
1126
+ }
1127
+ };
1128
+ var createTarget = (target, allVariants) => {
1129
+ const operation = (update) => {
1130
+ return new OptimisticOperation({
1131
+ target,
1132
+ allVariants,
1133
+ update
1134
+ });
1135
+ };
1136
+ const createListHelpers = (onList) => ({
1137
+ patch: (match, fields, options) => {
1138
+ return operation(onList((list) => patchItems(list, {
1139
+ match,
1140
+ key: options?.key
1141
+ }, fields)));
1142
+ },
1143
+ insert: (item, options) => {
1144
+ return operation(onList((list) => insertItem(list, item, options)));
1145
+ },
1146
+ remove: (match, options) => {
1147
+ return operation(onList((list) => removeItems(list, {
1148
+ match,
1149
+ key: options?.key
1150
+ })));
1151
+ },
1152
+ increment: (match, field, by, options) => {
1153
+ return operation(onList((list) => incrementItems(list, {
1154
+ match,
1155
+ key: options?.key
1156
+ }, {
1157
+ field,
1158
+ by
1159
+ })));
1160
+ }
1161
+ });
1162
+ const listHelpers = createListHelpers((update) => (data) => update(data));
1163
+ return {
1164
+ ...listHelpers,
1165
+ set: (updater) => operation(updater),
1166
+ increment: (...args) => {
1167
+ if (args.length >= 3) {
1168
+ const [match, field, by, options] = args;
1169
+ return listHelpers.increment(match, field, by, options);
1170
+ }
1171
+ const [field, by] = args;
1172
+ return operation((data) => incrementField(data, field, by));
1173
+ },
1174
+ list: (field) => {
1175
+ return createListHelpers((update) => (data) => updateListField(data, field, update));
1176
+ }
1177
+ };
1178
+ };
1179
+ var optimisticFactory = (target) => createTarget(target, false);
1180
+ optimisticFactory.all = (target) => createTarget(target, true);
1181
+ /**
1182
+ * Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
1183
+ * `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
1184
+ * the targets once the last pending mutation on them is done.
1185
+ *
1186
+ * - `optimistic(getTodos)` - the entry of this request (its params and query params)
1187
+ * - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
1188
+ *
1189
+ * Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
1190
+ * `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
1191
+ *
1192
+ * @example
1193
+ * optimistic(getTodos)
1194
+ * .patch(params.todoId, payload)
1195
+ * .rollback(({ data, previous }) => {
1196
+ * const before = previous.find((todo) => todo.id === params.todoId);
1197
+ * return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
1198
+ * });
1199
+ */
1200
+ var optimistic = optimisticFactory;
1201
+ //#endregion
1202
+ //#region src/utils/error.utils.ts
1203
+ /**
1204
+ * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request
1205
+ * lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the
1206
+ * lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).
1207
+ * @internal
1208
+ * @param error value thrown by the user code
1209
+ */
1210
+ var throwOutsideLifecycle = (error) => {
1211
+ setTimeout(() => {
1212
+ throw error;
1213
+ });
1214
+ };
1215
+ /**
1216
+ * Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on
1217
+ * and the error is thrown outside of it.
1218
+ * @internal
1219
+ * @param callback code of the user to run
1220
+ * @returns `true` when the callback finished, `false` when it threw
1221
+ */
1222
+ var runUserCode = (callback) => {
1223
+ try {
1224
+ callback();
1225
+ return true;
1226
+ } catch (error) {
1227
+ throwOutsideLifecycle(error);
1228
+ return false;
1229
+ }
1230
+ };
1231
+ //#endregion
1232
+ //#region src/utils/uuid.utils.ts
1233
+ var getUniqueRequestId = (request) => {
1234
+ return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
1235
+ };
1236
+ //#endregion
1237
+ //#region src/utils/emitter.utils.ts
1238
+ var import_events = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1239
+ var R = typeof Reflect === "object" ? Reflect : null;
1240
+ var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply(target, receiver, args) {
1241
+ return Function.prototype.apply.call(target, receiver, args);
1242
+ };
1243
+ var ReflectOwnKeys;
1244
+ if (R && typeof R.ownKeys === "function") ReflectOwnKeys = R.ownKeys;
1245
+ else if (Object.getOwnPropertySymbols) ReflectOwnKeys = function ReflectOwnKeys(target) {
1246
+ return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
1247
+ };
1248
+ else ReflectOwnKeys = function ReflectOwnKeys(target) {
1249
+ return Object.getOwnPropertyNames(target);
1250
+ };
1251
+ function ProcessEmitWarning(warning) {
1252
+ if (console && console.warn) console.warn(warning);
1253
+ }
1254
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
1255
+ return value !== value;
1256
+ };
1257
+ function EventEmitter() {
1258
+ EventEmitter.init.call(this);
1121
1259
  }
1122
1260
  module.exports = EventEmitter;
1123
1261
  module.exports.once = once;
@@ -1426,1222 +1564,1084 @@ var EventEmitter = class extends import_events.default {
1426
1564
  removeListener = this.off;
1427
1565
  };
1428
1566
  //#endregion
1429
- //#region src/request/request.utils.ts
1430
- var scopeKey = (key, scope) => {
1431
- return scope ? `${scope}__${key}` : key;
1432
- };
1433
- var stringifyKey = (value) => {
1434
- try {
1435
- if (typeof value === "string") return value;
1436
- if (value === void 0 || value === null) return "";
1437
- const data = JSON.stringify(value);
1438
- if (typeof data !== "string") throw new TypeError();
1439
- return data;
1440
- } catch {
1441
- return "";
1567
+ //#region src/optimistic/optimistic.settlement.ts
1568
+ var clientStates = /* @__PURE__ */ new WeakMap();
1569
+ var getClientState = (client) => {
1570
+ let state = clientStates.get(client);
1571
+ if (!state) {
1572
+ state = {
1573
+ keys: /* @__PURE__ */ new Map(),
1574
+ staleRequests: /* @__PURE__ */ new Map()
1575
+ };
1576
+ clientStates.set(client, state);
1442
1577
  }
1443
- };
1444
- var getProgressValue = ({ loaded, total }) => {
1445
- if (!loaded || !total) return 0;
1446
- return Number((loaded * 100 / total).toFixed(0));
1447
- };
1448
- var getRequestEta = (startDate, progressDate, { total, loaded }) => {
1449
- const uploadSpeed = loaded / (+progressDate - +startDate || 1);
1450
- const totalValue = Math.max(total, loaded);
1451
- const sizeLeft = totalValue - loaded;
1452
- const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;
1453
- return {
1454
- timeLeft: totalValue === loaded ? 0 : estimatedTimeValue,
1455
- sizeLeft
1456
- };
1457
- };
1458
- var getProgressData = (requestStartTime, progressDate, progressEvent) => {
1459
- const { total, loaded } = progressEvent;
1460
- if (Number.isNaN(total) || Number.isNaN(loaded)) return {
1461
- progress: 0,
1462
- timeLeft: 0,
1463
- sizeLeft: 0,
1464
- total: 0,
1465
- loaded: 0,
1466
- startTimestamp: +requestStartTime
1467
- };
1468
- const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);
1469
- return {
1470
- progress: getProgressValue(progressEvent),
1471
- timeLeft,
1472
- sizeLeft,
1473
- total,
1474
- loaded,
1475
- startTimestamp: +requestStartTime
1476
- };
1477
- };
1478
- var getSimpleKey = (request) => {
1479
- return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;
1578
+ return state;
1480
1579
  };
1481
1580
  /**
1482
- * Cache instance for individual request that collects individual requests responses from
1483
- * the same endpoint (they may differ base on the custom key, endpoint params etc)
1484
- * @param request
1485
- * @param useInitialValues
1486
- * @returns
1581
+ * Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request
1582
+ * lifecycle, like every other user code running in it - the request and the other changes still settle.
1487
1583
  */
1488
- var getRequestKey = (request, useInitialValues) => {
1489
- return `${stringifyKey(request.method)}_${useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint)}_${useInitialValues ? "" : stringifyKey(request.queryParams)}`;
1584
+ var reportFailure = (client, title, extra) => {
1585
+ client.logger.error({
1586
+ title,
1587
+ type: "system",
1588
+ extra
1589
+ });
1590
+ throwOutsideLifecycle(extra.error);
1490
1591
  };
1491
- var getRequestDispatcher = (request, dispatcherType = "auto") => {
1492
- const { fetchDispatcher, submitDispatcher } = request.client;
1493
- const isSafeRead = SAFE_HTTP_METHODS.includes(request.method);
1494
- const isFetchDispatcher = dispatcherType === "auto" && isSafeRead || dispatcherType === "fetch";
1495
- return [isFetchDispatcher ? fetchDispatcher : submitDispatcher, isFetchDispatcher];
1592
+ var readEntry = (client, storageKey) => {
1593
+ return client.cache.get(storageKey);
1496
1594
  };
1497
1595
  /**
1498
- * Runs the response mapper of the request. Mapper is user code running in the middle of the response handling,
1499
- * so its failure is logged and ends up as a failed response carrying the thrown value as the `error`.
1500
- * Failures are always delivered through a promise, so sync and async mappers fail the same way.
1501
- * @internal
1502
- * @param request request with the optional response mapper
1503
- * @param response response to be mapped
1504
- * @returns mapped response, promise of it for async and failed mappers, `undefined` when there is no mapper
1596
+ * Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its
1597
+ * timestamps and staleness - an optimistic value doesn't make the entry fresh.
1505
1598
  */
1506
- var runResponseMapper = (request, response) => {
1507
- const getFailedResponse = (error) => {
1508
- request.client.logger.error({
1509
- title: "Response mapper failed",
1510
- type: "system",
1511
- extra: {
1599
+ var writeData = (request, entry, data) => {
1600
+ const entryRequest = request.clone({
1601
+ staleTime: entry.staleTime,
1602
+ cacheTime: entry.cacheTime
1603
+ });
1604
+ request.client.cache.set(entryRequest, {
1605
+ ...entry,
1606
+ data
1607
+ });
1608
+ };
1609
+ /**
1610
+ * Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint
1611
+ * whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).
1612
+ */
1613
+ var resolveTargets = (client, operation) => {
1614
+ const { target } = operation;
1615
+ const targets = /* @__PURE__ */ new Map();
1616
+ if (!operation.allVariants) {
1617
+ targets.set(scopeKey(target.cacheKey, target.scope), target);
1618
+ return targets;
1619
+ }
1620
+ const prefix = target.cacheKey === getRequestKey(target) ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_` : `${target.cacheKey}_`;
1621
+ client.cache.keys().forEach((storageKey) => {
1622
+ const entry = client.cache.storage.get(storageKey);
1623
+ if (!entry || entry.scope !== target.scope) return;
1624
+ if (entry.cacheKey === target.cacheKey) targets.set(storageKey, target);
1625
+ else if (entry.cacheKey.startsWith(prefix)) targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey));
1626
+ });
1627
+ return targets;
1628
+ };
1629
+ /**
1630
+ * Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:
1631
+ * a throw or a promise is reported and the key gets refreshed.
1632
+ */
1633
+ var runSettleCallback = (pending, { operation, storageKey, request, previous }, outcome) => {
1634
+ const { client } = pending;
1635
+ const entry = readEntry(client, storageKey);
1636
+ const isCommit = outcome.type === "success";
1637
+ const title = isCommit ? "Optimistic commit failed" : "Optimistic rollback failed";
1638
+ const run = (data) => {
1639
+ if (outcome.type === "success") {
1640
+ const response = outcome.response;
1641
+ return operation.onCommit?.({
1642
+ data,
1643
+ response,
1644
+ request: outcome.request
1645
+ });
1646
+ }
1647
+ const { type: _type, ...args } = outcome;
1648
+ return operation.onRollback?.({
1649
+ ...args,
1650
+ data,
1651
+ previous
1652
+ });
1653
+ };
1654
+ if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) return;
1655
+ try {
1656
+ const next = run(entry.data);
1657
+ if (next instanceof Promise) {
1658
+ next.catch((error) => reportFailure(client, title, {
1512
1659
  error,
1513
- request,
1514
- response
1515
- }
1660
+ storageKey
1661
+ }));
1662
+ throw new TypeError("Optimistic rollback and commit must be synchronous, the returned promise was ignored");
1663
+ }
1664
+ if (next !== void 0 && next !== entry.data) writeData(request, entry, next);
1665
+ } catch (error) {
1666
+ reportFailure(client, title, {
1667
+ error,
1668
+ storageKey,
1669
+ request: outcome.request
1516
1670
  });
1517
- return {
1518
- ...response,
1519
- data: null,
1671
+ pending.failed.add(storageKey);
1672
+ }
1673
+ };
1674
+ /** Rollback of the hand-written object form - runs once, its failure can't affect the request */
1675
+ var runObjectRollback = (pending, args) => {
1676
+ const { client, result } = pending;
1677
+ const onFailure = (error) => {
1678
+ reportFailure(client, "Optimistic rollback failed", {
1520
1679
  error,
1521
- success: false
1522
- };
1680
+ reason: args.reason,
1681
+ request: args.request
1682
+ });
1523
1683
  };
1524
1684
  try {
1525
- const mapping = request.unstable_responseMapper?.(response);
1526
- return mapping instanceof Promise ? mapping.catch(getFailedResponse) : mapping;
1685
+ Promise.resolve(result.rollback?.(args)).catch(onFailure);
1527
1686
  } catch (error) {
1528
- return Promise.resolve(getFailedResponse(error));
1687
+ onFailure(error);
1529
1688
  }
1530
1689
  };
1531
- var mapResponseForSend = async (request, response) => {
1532
- const mapping = runResponseMapper(request, response);
1533
- if (mapping instanceof Promise) return await mapping;
1534
- return mapping || response;
1535
- };
1536
- var sendRequest = async (request, options) => {
1537
- const { client } = request;
1538
- const { requestManager } = client;
1539
- const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
1540
- let mutationContext;
1541
- let pendingOptimistic;
1542
- const optimisticSource = options?.optimistic ?? request.optimistic;
1543
- if (optimisticSource) {
1690
+ var runObjectInvalidation = ({ client, result }, request) => {
1691
+ result.invalidate?.forEach((target) => {
1544
1692
  try {
1545
- const result = Array.isArray(optimisticSource) ? optimisticSource : optimisticSource({
1546
- request,
1547
- client: request.client,
1548
- payload: request.payload,
1549
- params: request.params,
1550
- queryParams: request.queryParams,
1551
- optimistic
1552
- });
1553
- mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);
1693
+ client.cache.invalidate(target);
1554
1694
  } catch (error) {
1555
- return {
1556
- data: null,
1557
- error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${error instanceof Error ? error.message : error}`),
1558
- status: null,
1559
- success: false,
1560
- extra: client.adapter.defaultExtra,
1561
- requestTimestamp: Date.now(),
1562
- responseTimestamp: Date.now()
1563
- };
1695
+ reportFailure(client, "Optimistic invalidation failed", {
1696
+ error,
1697
+ target,
1698
+ request
1699
+ });
1564
1700
  }
1565
- pendingOptimistic = applyOptimistic(client, mutationContext);
1566
- }
1567
- return new Promise((resolve) => {
1568
- let isResolved = false;
1569
- let isDelivered = false;
1570
- let isSettled = false;
1571
- const requestId = dispatcher.add(request);
1572
- const queryKey = scopeKey(request.queryKey, request.scope);
1573
- const { $hooks } = request;
1574
- const getWillBeResent = ({ response, details }) => {
1575
- if (response.success || details.isCanceled) return false;
1576
- if (!dispatcher.getRequest(queryKey, requestId)) return false;
1577
- return details.willRetry || request.offline && details.isOffline;
1578
- };
1579
- const mappings = /* @__PURE__ */ new WeakMap();
1580
- const getMapping = (values) => {
1581
- if (!mappings.has(values)) mappings.set(values, runResponseMapper(request, values.response));
1582
- return mappings.get(values);
1583
- };
1584
- const unmountSettlement = pendingOptimistic ? requestManager.events.onResponseById(requestId, (values) => {
1585
- const pending = pendingOptimistic;
1586
- const willBeResent = getWillBeResent(values);
1587
- const settle = (response) => {
1588
- if (isSettled || !response.success && willBeResent) return;
1589
- isSettled = true;
1590
- if (values.details.isCanceled) settleOptimistic(pending, {
1591
- type: "rollback",
1592
- reason: "abort",
1593
- response,
1594
- request
1595
- });
1596
- else if (response.success) settleOptimistic(pending, {
1597
- type: "success",
1598
- response,
1599
- request
1600
- });
1601
- else settleOptimistic(pending, {
1602
- type: "rollback",
1603
- reason: "error",
1604
- response,
1605
- request
1606
- });
1607
- };
1608
- const mapping = getMapping(values);
1609
- if (mapping instanceof Promise) mapping.then(settle);
1610
- else settle(mapping || values.response);
1611
- }) : void 0;
1612
- const beforeSentData = {
1613
- requestId,
1614
- request,
1615
- mutationContext
1616
- };
1617
- runUserCode(() => options?.onBeforeSent?.(beforeSentData));
1618
- runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
1619
- const unmountRequestStart = requestManager.events.onRequestStartById(requestId, (data) => {
1620
- const enriched = {
1621
- ...data,
1622
- mutationContext
1623
- };
1624
- runUserCode(() => options?.onRequestStart?.(enriched));
1625
- runUserCode(() => $hooks.__emit("onRequestStart", enriched));
1626
- });
1627
- const unmountResponseStart = requestManager.events.onResponseStartById(requestId, (data) => {
1628
- const enriched = {
1629
- ...data,
1630
- mutationContext
1631
- };
1632
- runUserCode(() => options?.onResponseStart?.(enriched));
1633
- runUserCode(() => $hooks.__emit("onResponseStart", enriched));
1634
- });
1635
- const unmountUpload = requestManager.events.onUploadProgressById(requestId, (data) => {
1636
- const enriched = {
1637
- ...data,
1638
- mutationContext
1639
- };
1640
- runUserCode(() => options?.onUploadProgress?.(enriched));
1641
- runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
1701
+ });
1702
+ };
1703
+ /**
1704
+ * `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.
1705
+ * A predicate that throws is reported and the change is reverted.
1706
+ */
1707
+ var shouldRollback = (pending, outcome) => {
1708
+ const { rollbackOnError } = pending.result;
1709
+ if (outcome.reason !== "error" || rollbackOnError === void 0 || rollbackOnError === true) return true;
1710
+ if (rollbackOnError === false) return false;
1711
+ try {
1712
+ return !!rollbackOnError({
1713
+ response: outcome.response,
1714
+ request: outcome.request
1642
1715
  });
1643
- const unmountDownload = requestManager.events.onDownloadProgressById(requestId, (data) => {
1644
- const enriched = {
1645
- ...data,
1646
- mutationContext
1647
- };
1648
- runUserCode(() => options?.onDownloadProgress?.(enriched));
1649
- runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
1716
+ } catch (error) {
1717
+ reportFailure(pending.client, "Optimistic rollbackOnError failed", {
1718
+ error,
1719
+ request: outcome.request
1650
1720
  });
1651
- const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
1652
- const { response } = values;
1653
- const willBeResent = getWillBeResent(values);
1654
- isResolved = !willBeResent;
1655
- const enrichedValues = {
1656
- ...values,
1657
- mutationContext
1658
- };
1659
- const mapping = getMapping(values);
1660
- const handleResponse = (success, data) => {
1661
- if (isDelivered || !success && willBeResent) return;
1662
- isDelivered = true;
1663
- runUserCode(() => options?.onResponse?.(enrichedValues));
1664
- runUserCode(() => $hooks.__emit("onResponse", enrichedValues));
1665
- resolve(data);
1666
- umountAll();
1667
- };
1668
- if (mapping instanceof Promise) (async () => {
1669
- const responseData = await mapping;
1670
- const { success } = responseData;
1671
- handleResponse(success, responseData);
1672
- })();
1673
- else {
1674
- const data = mapping || response;
1675
- const { success } = data;
1676
- handleResponse(success, data);
1677
- }
1678
- });
1679
- const unmountRemoveQueueElement = requestManager.events.onRemoveById(requestId, (data) => {
1680
- if (!isResolved) {
1681
- isResolved = true;
1682
- isDelivered = true;
1683
- if (pendingOptimistic && !isSettled) {
1684
- isSettled = true;
1685
- settleOptimistic(pendingOptimistic, {
1686
- type: "rollback",
1687
- reason: "removed",
1688
- request
1689
- });
1690
- }
1691
- const enriched = {
1692
- ...data,
1693
- mutationContext
1694
- };
1695
- runUserCode(() => options?.onRemove?.(enriched));
1696
- runUserCode(() => $hooks.__emit("onRemove", enriched));
1697
- resolve({
1698
- data: null,
1699
- status: null,
1700
- success: false,
1701
- error: getErrorMessage("deleted"),
1702
- extra: request.client.adapter.defaultExtra,
1703
- requestTimestamp: Date.now(),
1704
- responseTimestamp: Date.now()
1705
- });
1706
- umountAll();
1707
- }
1708
- });
1709
- function umountAll() {
1710
- unmountSettlement?.();
1711
- unmountRequestStart();
1712
- unmountResponseStart();
1713
- unmountUpload();
1714
- unmountDownload();
1715
- unmountResponse();
1716
- unmountRemoveQueueElement();
1717
- }
1718
- });
1719
- };
1720
- //#endregion
1721
- //#region src/request/request.ts
1722
- /**
1723
- * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.
1724
- * It is executed at any time via methods like `send` or `exec`.
1725
- *
1726
- * We can set it up with options like endpoint, method, headers and more.
1727
- * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.
1728
- *
1729
- * @info We should not use this class directly in the standard development flow.
1730
- * We can initialize it using the `createRequest` method on the **Client** class.
1731
- *
1732
- * @attention The most important thing about the request is that it keeps data in the format that can be dumped.
1733
- * This is necessary for the persistence and different dispatcher storage types.
1734
- * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.
1735
- *
1736
- * It should be serializable to JSON and deserializable back to the class.
1737
- * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.
1738
- */
1739
- var Request = class Request {
1740
- endpoint;
1741
- headers = void 0;
1742
- auth;
1743
- method;
1744
- params;
1745
- payload;
1746
- queryParams;
1747
- options = void 0;
1748
- cancelable;
1749
- retry;
1750
- retryTime;
1751
- cacheTime;
1752
- cache;
1753
- staleTime;
1754
- queued;
1755
- offline;
1756
- abortKey;
1757
- cacheKey;
1758
- queryKey;
1759
- used;
1760
- deduplicate;
1761
- deduplicateTime;
1762
- structuralSharing;
1763
- scope;
1764
- /**
1765
- * Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call
1766
- * made on this request instance (and its clones), without needing to pass them to `send()` each time.
1767
- * Useful for cross-cutting concerns like logging, analytics, or toast notifications.
1768
- *
1769
- * Each method registers a callback and returns an unsubscribe function.
1770
- * Multiple listeners per hook are supported.
1771
- */
1772
- $hooks = createRequestHooks();
1773
- isMockerEnabled = false;
1774
- static OPTIONAL_FIELDS = [
1775
- "unstable_mock",
1776
- "unstable_payloadMapper",
1777
- "unstable_requestMapper",
1778
- "unstable_responseMapper",
1779
- "retryOnError",
1780
- "optimistic"
1781
- ];
1782
- unstable_mock = void 0;
1783
- /** @internal */
1784
- unstable_payloadMapper = void 0;
1785
- /** @internal */
1786
- unstable_requestMapper = void 0;
1787
- /** @internal */
1788
- unstable_responseMapper = void 0;
1789
- /** @internal */
1790
- retryOnError = void 0;
1791
- /** @internal */
1792
- optimistic = void 0;
1793
- unstable_hasParams = false;
1794
- unstable_hasPayload = false;
1795
- unstable_hasQuery = false;
1796
- unstable_hasMutationContext = void 0;
1797
- updatedAbortKey;
1798
- updatedCacheKey;
1799
- updatedQueryKey;
1800
- constructor(client, requestOptions, initialRequestConfiguration) {
1801
- this.client = client;
1802
- this.requestOptions = requestOptions;
1803
- this.initialRequestConfiguration = initialRequestConfiguration;
1804
- const { endpoint, headers, auth = true, method = client.adapter.defaultMethod, options, cancelable = false, retry = 0, retryTime = 500, cacheTime = Time.MIN * 5, cache = true, staleTime = Time.MIN * 5, queued = false, offline = true, abortKey, cacheKey, queryKey, deduplicate = false, deduplicateTime = null, structuralSharing = true } = {
1805
- ...this.client.adapter.unstable_getRequestDefaults?.(requestOptions),
1806
- ...requestOptions
1807
- };
1808
- this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;
1809
- this.headers = initialRequestConfiguration?.headers ?? headers;
1810
- this.auth = initialRequestConfiguration?.auth ?? auth;
1811
- this.method = method;
1812
- this.params = initialRequestConfiguration?.params;
1813
- this.payload = initialRequestConfiguration?.payload;
1814
- this.queryParams = initialRequestConfiguration?.queryParams;
1815
- this.options = initialRequestConfiguration?.options ?? options;
1816
- this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;
1817
- this.retry = initialRequestConfiguration?.retry ?? retry;
1818
- this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;
1819
- this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;
1820
- this.cache = initialRequestConfiguration?.cache ?? cache;
1821
- this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;
1822
- this.queued = initialRequestConfiguration?.queued ?? queued;
1823
- this.offline = initialRequestConfiguration?.offline ?? offline;
1824
- this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);
1825
- this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);
1826
- this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);
1827
- this.used = initialRequestConfiguration?.used ?? false;
1828
- this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;
1829
- this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;
1830
- this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;
1831
- this.scope = initialRequestConfiguration?.scope ?? null;
1832
- this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;
1833
- this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;
1834
- this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;
1835
- }
1836
- /** Set the request headers. Returns a cloned request with the new headers applied. */
1837
- setHeaders = (headers) => {
1838
- return this.clone({ headers });
1839
- };
1840
- /** Set whether authentication interceptors should run for this request. */
1841
- setAuth = (auth) => {
1842
- return this.clone({ auth });
1843
- };
1844
- /** Set the URL path parameters (e.g., `:userId`). */
1845
- setParams = (params) => {
1846
- return this.clone({ params });
1847
- };
1848
- /** Set the request body payload. Passing `null` removes the payload set before. */
1849
- setPayload = (payload) => {
1850
- return this.clone({ payload });
1851
- };
1852
- /** Set the query parameters appended to the URL. */
1853
- setQueryParams = (queryParams) => {
1854
- return this.clone({ queryParams });
1855
- };
1856
- /** Set adapter-specific options (e.g., axios config, fetch init). */
1857
- setOptions = (options) => {
1858
- return this.clone({ options });
1859
- };
1860
- /**
1861
- * Set a scope identifier for this request.
1862
- * All keys (cache, queue, abort) are prefixed with this scope, isolating
1863
- * the request from other scopes. In "server" client mode, setting a scope
1864
- * also enables caching (which is otherwise disabled to prevent cross-request leaks).
1865
- */
1866
- setScope = (scopeId) => {
1867
- const cloned = this.clone();
1868
- cloned.scope = scopeId;
1869
- return cloned;
1870
- };
1871
- /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */
1872
- setCancelable = (cancelable) => {
1873
- return this.clone({ cancelable });
1874
- };
1875
- /** Set the number of retry attempts on failure. */
1876
- setRetry = (retry) => {
1877
- return this.clone({ retry });
1878
- };
1879
- /** Set the delay in milliseconds between retry attempts. */
1880
- setRetryTime = (retryTime) => {
1881
- return this.clone({ retryTime });
1882
- };
1883
- /**
1884
- * Set a callback that controls whether a failed request should be retried.
1885
- * Called on each failed attempt before scheduling the next retry.
1886
- * Return `true` to allow the retry, `false` to stop retrying immediately.
1887
- */
1888
- setRetryOnError = (callback) => {
1889
- const cloned = this.clone();
1890
- cloned.retryOnError = callback;
1891
- return cloned;
1892
- };
1893
- /**
1894
- * Configure optimistic update behavior for this request.
1895
- * The callback runs before the request is sent and receives `{ request, client, payload, params, queryParams,
1896
- * optimistic }`. A synchronous callback changes the cache within the `send()` call.
1897
- *
1898
- * Return an array of changes built with `optimistic()` - core applies them, runs their `.commit()` on success or
1899
- * `.rollback()` on final failure, abort or queue removal, and refreshes the targets after the last pending mutation
1900
- * on them. Or return an object with `updates`, `context` (available in lifecycle callbacks as `mutationContext`),
1901
- * `rollback` (called once on failure, abort or queue removal), `invalidate` (requests invalidated on success),
1902
- * `rollbackOnError` and `revalidate`.
1903
- * Everything runs for every way of sending the request, not only inside of framework hooks.
1904
- *
1905
- * @example
1906
- * toggleTodo.setOptimistic(({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)]);
1907
- */
1908
- setOptimistic = (callback) => {
1909
- const cloned = this.clone();
1910
- cloned.optimistic = callback;
1911
- return cloned;
1912
- };
1913
- /** Set how long (in ms) the response remains in cache before being garbage collected. */
1914
- setCacheTime = (cacheTime) => {
1915
- return this.clone({ cacheTime });
1916
- };
1917
- /** Set whether this request should use the cache. */
1918
- setCache = (cache) => {
1919
- return this.clone({ cache });
1920
- };
1921
- /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */
1922
- setStaleTime = (staleTime) => {
1923
- return this.clone({ staleTime });
1924
- };
1925
- /** Set whether the request should be queued and executed sequentially rather than immediately. */
1926
- setQueued = (queued) => {
1927
- return this.clone({ queued });
1928
- };
1929
- /** Override the abort key used to cancel this request. */
1930
- setAbortKey = (abortKey) => {
1931
- return this.clone({
1932
- abortKey,
1933
- updatedAbortKey: true
1934
- });
1935
- };
1936
- /** Override the cache key used to store/retrieve the response. */
1937
- setCacheKey = (cacheKey) => {
1938
- return this.clone({
1939
- cacheKey,
1940
- updatedCacheKey: true
1941
- });
1942
- };
1943
- /** Override the query key that identifies this request in the dispatcher queue. */
1944
- setQueryKey = (queryKey) => {
1945
- return this.clone({
1946
- queryKey,
1947
- updatedQueryKey: true
1948
- });
1949
- };
1950
- /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
1951
- setDeduplicate = (deduplicate) => {
1952
- return this.clone({ deduplicate });
1953
- };
1954
- /** Set the time window (in ms) during which identical requests are deduplicated. */
1955
- setDeduplicateTime = (deduplicateTime) => {
1956
- return this.clone({ deduplicateTime });
1957
- };
1958
- /** Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache. */
1959
- setStructuralSharing = (structuralSharing) => {
1960
- return this.clone({ structuralSharing });
1961
- };
1962
- /** Mark the request as used (prevents automatic refetching in hooks). */
1963
- setUsed = (used) => {
1964
- return this.clone({ used });
1965
- };
1966
- /** Set whether the request should be stored in the offline queue when there is no network connection. */
1967
- setOffline = (offline) => {
1968
- return this.clone({ offline });
1969
- };
1970
- /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */
1971
- setMock = (fn, config = {}) => {
1972
- this.unstable_mock = {
1973
- fn,
1974
- config
1975
- };
1976
- this.isMockerEnabled = true;
1977
- return this;
1978
- };
1979
- /** Remove any attached mock handler and disable mocking for this request. */
1980
- clearMock = () => {
1981
- this.unstable_mock = void 0;
1982
- this.isMockerEnabled = false;
1983
- return this;
1984
- };
1985
- /** Enable or disable the mocker for this request without removing the mock handler. */
1986
- setMockingEnabled = (isMockerEnabled) => {
1987
- this.isMockerEnabled = isMockerEnabled;
1988
- return this;
1989
- };
1990
- /**
1991
- * Map data before it gets send to the server
1992
- * @param payloadMapper
1993
- * @returns
1994
- */
1995
- setPayloadMapper = (payloadMapper) => {
1996
- const cloned = this.clone();
1997
- cloned.unstable_payloadMapper = payloadMapper;
1998
- return cloned;
1999
- };
2000
- /**
2001
- * Map request before it gets send to the server
2002
- * @param requestMapper mapper of the request
2003
- * @returns new request
2004
- */
2005
- setRequestMapper = (requestMapper) => {
2006
- const cloned = this.clone();
2007
- cloned.unstable_requestMapper = requestMapper;
2008
- return cloned;
2009
- };
2010
- /**
2011
- * Map the response to the new interface
2012
- * @param responseMapper our mapping callback
2013
- * @returns new response
2014
- */
2015
- setResponseMapper = (responseMapper) => {
2016
- const cloned = this.clone();
2017
- cloned.unstable_responseMapper = responseMapper;
2018
- return cloned;
2019
- };
2020
- paramsMapper = (params) => {
2021
- const { endpoint } = this.requestOptions;
2022
- const stringEndpoint = String(endpoint);
2023
- const names = params ? Object.keys(params) : [];
2024
- if (!params || names.length === 0) return stringEndpoint;
2025
- const [start, ...segments] = stringEndpoint.split(":");
2026
- return [start, ...segments.map((segment) => {
2027
- const name = names.reduce((longest, current) => segment.startsWith(current) && current.length > longest.length ? current : longest, "");
2028
- return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;
2029
- })].join("");
2030
- };
2031
- /** Serialize the request configuration into a plain JSON object for persistence or transfer. */
2032
- toJSON() {
2033
- return {
2034
- requestOptions: this.requestOptions,
2035
- endpoint: this.endpoint,
2036
- headers: this.headers,
2037
- auth: this.auth,
2038
- method: this.method,
2039
- params: this.params,
2040
- payload: this.payload,
2041
- queryParams: this.queryParams,
2042
- options: this.options,
2043
- cancelable: this.cancelable,
2044
- retry: this.retry,
2045
- retryTime: this.retryTime,
2046
- cacheTime: this.cacheTime,
2047
- cache: this.cache,
2048
- staleTime: this.staleTime,
2049
- queued: this.queued,
2050
- offline: this.offline,
2051
- abortKey: this.abortKey,
2052
- cacheKey: this.cacheKey,
2053
- queryKey: this.queryKey,
2054
- used: this.used,
2055
- disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,
2056
- disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,
2057
- updatedAbortKey: this.updatedAbortKey,
2058
- updatedCacheKey: this.updatedCacheKey,
2059
- updatedQueryKey: this.updatedQueryKey,
2060
- deduplicate: this.deduplicate,
2061
- deduplicateTime: this.deduplicateTime,
2062
- structuralSharing: this.structuralSharing,
2063
- scope: this.scope,
2064
- isMockerEnabled: this.isMockerEnabled,
2065
- hasMock: !!this.unstable_mock
2066
- };
2067
- }
2068
- /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */
2069
- clone(configuration) {
2070
- const initialRequestConfiguration = {
2071
- ...this.toJSON(),
2072
- ...configuration,
2073
- options: configuration?.options || this.options,
2074
- abortKey: configuration?.abortKey || (this.updatedAbortKey ? this.abortKey : void 0),
2075
- cacheKey: configuration?.cacheKey || (this.updatedCacheKey ? this.cacheKey : void 0),
2076
- queryKey: configuration?.queryKey || (this.updatedQueryKey ? this.queryKey : void 0),
2077
- updatedAbortKey: !!configuration?.abortKey || this.updatedAbortKey,
2078
- updatedCacheKey: !!configuration?.cacheKey || this.updatedCacheKey,
2079
- updatedQueryKey: !!configuration?.queryKey || this.updatedQueryKey,
2080
- endpoint: this.paramsMapper(configuration?.params || this.params),
2081
- queryParams: configuration?.queryParams || this.queryParams,
2082
- payload: configuration?.payload === null ? void 0 : configuration?.payload ?? this.payload,
2083
- params: configuration?.params || this.params
2084
- };
2085
- const cloned = new Request(this.client, this.requestOptions, initialRequestConfiguration);
2086
- cloned.unstable_payloadMapper = this.unstable_payloadMapper;
2087
- cloned.unstable_responseMapper = this.unstable_responseMapper;
2088
- cloned.unstable_requestMapper = this.unstable_requestMapper;
2089
- cloned.retryOnError = this.retryOnError;
2090
- cloned.unstable_mock = this.unstable_mock;
2091
- cloned.isMockerEnabled = this.isMockerEnabled;
2092
- cloned.optimistic = this.optimistic;
2093
- cloned.$hooks = createRequestHooks(this.$hooks.__snapshot());
2094
- return cloned;
2095
- }
2096
- /** Abort all in-flight requests sharing this request's abort key. */
2097
- abort = () => {
2098
- const { requestManager } = this.client;
2099
- requestManager.abortByKey(scopeKey(this.abortKey, this.scope));
2100
- return this.clone();
2101
- };
2102
- /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */
2103
- dehydrate = (config) => {
2104
- const { response, override = true } = config || {};
2105
- if (response) return {
2106
- override,
2107
- cacheTime: this.cacheTime,
2108
- staleTime: this.staleTime,
2109
- cacheKey: this.cacheKey,
2110
- scope: this.scope,
2111
- timestamp: Date.now(),
2112
- hydrated: true,
2113
- cache: true,
2114
- response
2115
- };
2116
- const cacheData = this.client.cache.get(scopeKey(this.cacheKey, this.scope));
2117
- if (!cacheData) return;
2118
- return {
2119
- override,
2120
- cacheTime: this.cacheTime,
2121
- staleTime: this.staleTime,
2122
- cacheKey: this.cacheKey,
2123
- scope: this.scope,
2124
- timestamp: Date.now(),
2125
- hydrated: true,
2126
- cache: true,
2127
- response: {
2128
- data: cacheData.data,
2129
- error: cacheData.error,
2130
- status: cacheData.status,
2131
- success: cacheData.success,
2132
- extra: cacheData.extra,
2133
- requestTimestamp: cacheData.requestTimestamp,
2134
- responseTimestamp: cacheData.responseTimestamp
2135
- }
2136
- };
2137
- };
2138
- /**
2139
- * Read the response from cache data
2140
- *
2141
- * If it returns error and data at the same time, it means that latest request was failed
2142
- * and we show previous data from cache together with error received from actual request
2143
- */
2144
- read() {
2145
- const cacheData = this.client.cache.get(scopeKey(this.cacheKey, this.scope));
2146
- if (cacheData) return {
2147
- data: cacheData.data,
2148
- error: cacheData.error,
2149
- status: cacheData.status,
2150
- success: cacheData.success,
2151
- extra: cacheData.extra,
2152
- requestTimestamp: cacheData.requestTimestamp,
2153
- responseTimestamp: cacheData.responseTimestamp
2154
- };
1721
+ return true;
2155
1722
  }
2156
- /**
2157
- * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.
2158
- * @param options
2159
- * @disableReturns
2160
- * @returns
2161
- * ```tsx
2162
- * Promise<[Data | null, Error | null, HttpStatus]>
2163
- * ```
2164
- */
2165
- exec = async (options) => {
2166
- const { adapter, requestManager } = this.client;
2167
- const request = this.clone(options);
2168
- const requestId = this.client.unstable_requestIdMapper(this);
2169
- const scopedAbortKey = scopeKey(this.abortKey, this.scope);
2170
- requestManager.addAbortController(scopedAbortKey, requestId);
2171
- const response = await adapter.fetch(request, requestId);
2172
- requestManager.removeAbortController(scopedAbortKey, requestId);
2173
- return mapResponseForSend(request, response);
2174
- };
2175
- /**
2176
- * Method used to perform requests with usage of cache and queues
2177
- * @param options
2178
- * @param requestCallback
2179
- * @disableReturns
2180
- * @returns
2181
- * ```tsx
2182
- * Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>
2183
- * ```
2184
- */
2185
- send = async (options) => {
2186
- const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, ...configuration } = options || {};
2187
- const request = this.clone(configuration);
2188
- const sendRequestOptions = options === void 0 ? void 0 : {
2189
- ...options,
2190
- cachePolicy: void 0
2191
- };
2192
- if (cachePolicy === "network-only") return sendRequest(request, sendRequestOptions);
2193
- const cached = request.read();
2194
- if (cachePolicy === "cache-first") {
2195
- if (cached) return mapResponseForSend(request, cached);
2196
- return sendRequest(request, sendRequestOptions);
2197
- }
2198
- if (cached) {
2199
- const resolved = await mapResponseForSend(request, cached);
2200
- sendRequest(request, sendRequestOptions);
2201
- return resolved;
1723
+ };
1724
+ var getRunningRequestsOnKey = (client, storageKey) => {
1725
+ return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey);
1726
+ };
1727
+ var hasStaleRequests = (state, storageKey) => {
1728
+ return [...state.staleRequests.values()].includes(storageKey);
1729
+ };
1730
+ /** Refreshes the key once nothing pending or stale is left on it */
1731
+ var refreshWhenIdle = (client, state, storageKey) => {
1732
+ const keyState = state.keys.get(storageKey);
1733
+ if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) return;
1734
+ state.keys.delete(storageKey);
1735
+ if (keyState.refresh) client.cache.invalidate(keyState.request);
1736
+ };
1737
+ var release = (pending, refresh) => {
1738
+ const { client, targets, failed, guarded } = pending;
1739
+ const state = getClientState(client);
1740
+ targets.forEach((request, storageKey) => {
1741
+ const keyState = state.keys.get(storageKey);
1742
+ const shouldRefresh = refresh || failed.has(storageKey);
1743
+ if (!guarded.has(storageKey)) {
1744
+ if (keyState && shouldRefresh) keyState.refresh = true;
1745
+ else if (shouldRefresh) client.cache.invalidate(request);
1746
+ return;
2202
1747
  }
2203
- return sendRequest(request, sendRequestOptions);
2204
- };
2205
- /** Reconstruct a Request instance from a previously serialized JSON representation. */
2206
- static fromJSON = (client, json) => {
2207
- return new Request(client, json.requestOptions, json);
2208
- };
1748
+ if (!keyState) return;
1749
+ keyState.pending -= 1;
1750
+ keyState.refresh = keyState.refresh || shouldRefresh;
1751
+ keyState.request = request;
1752
+ getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {
1753
+ state.staleRequests.set(requestId, storageKey);
1754
+ });
1755
+ refreshWhenIdle(client, state, storageKey);
1756
+ });
2209
1757
  };
2210
- //#endregion
2211
- //#region src/optimistic/optimistic.settlement.ts
2212
- var clientStates = /* @__PURE__ */ new WeakMap();
2213
- var getClientState = (client) => {
2214
- let state = clientStates.get(client);
2215
- if (!state) {
2216
- state = {
2217
- keys: /* @__PURE__ */ new Map(),
2218
- staleRequests: /* @__PURE__ */ new Map()
1758
+ /**
1759
+ * @internal
1760
+ * Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.
1761
+ */
1762
+ var getOptimisticResult = (value) => {
1763
+ if (Array.isArray(value)) return { updates: value };
1764
+ return value || {};
1765
+ };
1766
+ /**
1767
+ * @internal
1768
+ * Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,
1769
+ * the others still apply.
1770
+ */
1771
+ var applyOptimistic = (client, result) => {
1772
+ const pending = {
1773
+ client,
1774
+ result,
1775
+ applied: [],
1776
+ targets: /* @__PURE__ */ new Map(),
1777
+ guarded: /* @__PURE__ */ new Set(),
1778
+ failed: /* @__PURE__ */ new Set()
1779
+ };
1780
+ const state = getClientState(client);
1781
+ result.updates?.forEach((value) => {
1782
+ try {
1783
+ if (!(value instanceof OptimisticOperation)) throw new TypeError("Optimistic updates accept operations created with optimistic()");
1784
+ const operation = value;
1785
+ resolveTargets(client, operation).forEach((request, storageKey) => {
1786
+ pending.targets.set(storageKey, request);
1787
+ const entry = readEntry(client, storageKey);
1788
+ if (!entry) return;
1789
+ try {
1790
+ const next = operation.update(entry.data);
1791
+ if (next !== entry.data) writeData(request, entry, next);
1792
+ pending.applied.push({
1793
+ operation,
1794
+ storageKey,
1795
+ request,
1796
+ previous: entry.data
1797
+ });
1798
+ pending.guarded.add(storageKey);
1799
+ } catch (error) {
1800
+ reportFailure(client, "Optimistic update failed", {
1801
+ error,
1802
+ storageKey
1803
+ });
1804
+ pending.failed.add(storageKey);
1805
+ }
1806
+ });
1807
+ } catch (error) {
1808
+ reportFailure(client, "Optimistic update failed", {
1809
+ error,
1810
+ operation: value
1811
+ });
1812
+ }
1813
+ });
1814
+ pending.guarded.forEach((storageKey) => {
1815
+ const request = pending.targets.get(storageKey);
1816
+ const keyState = state.keys.get(storageKey) ?? {
1817
+ pending: 0,
1818
+ refresh: false,
1819
+ request
2219
1820
  };
2220
- clientStates.set(client, state);
1821
+ keyState.pending += 1;
1822
+ state.keys.set(storageKey, keyState);
1823
+ });
1824
+ return pending;
1825
+ };
1826
+ /**
1827
+ * @internal
1828
+ * Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the
1829
+ * rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.
1830
+ */
1831
+ var settleOptimistic = (pending, outcome) => {
1832
+ const { result, applied } = pending;
1833
+ const canRefresh = result.revalidate !== false;
1834
+ if (outcome.type === "success") {
1835
+ applied.forEach((operation) => runSettleCallback(pending, operation, outcome));
1836
+ runObjectInvalidation(pending, outcome.request);
1837
+ return release(pending, canRefresh);
2221
1838
  }
2222
- return state;
1839
+ const { type: _type, ...args } = outcome;
1840
+ if (!shouldRollback(pending, args)) return release(pending, false);
1841
+ for (let index = applied.length - 1; index >= 0; index -= 1) runSettleCallback(pending, applied[index], outcome);
1842
+ runObjectRollback(pending, args);
1843
+ return release(pending, canRefresh);
2223
1844
  };
2224
1845
  /**
2225
- * Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request
2226
- * lifecycle, like every other user code running in it - the request and the other changes still settle.
1846
+ * @internal
1847
+ * Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a
1848
+ * mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the
1849
+ * refresh after the mutation supplies current data. Keys that had no data when the change was applied are not
1850
+ * guarded, so a first load is never held back. Manual cache writes don't go through this check.
2227
1851
  */
2228
- var reportFailure = (client, title, extra) => {
2229
- client.logger.error({
2230
- title,
2231
- type: "system",
2232
- extra
2233
- });
2234
- throwOutsideLifecycle(extra.error);
1852
+ var isStaleOptimisticResponse = (client, request, requestId) => {
1853
+ const state = clientStates.get(client);
1854
+ if (!state) return false;
1855
+ const storageKey = scopeKey(request.cacheKey, request.scope);
1856
+ const isMarked = state.staleRequests.delete(requestId);
1857
+ const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;
1858
+ if (isMarked) refreshWhenIdle(client, state, storageKey);
1859
+ return isMarked || isPending;
1860
+ };
1861
+ /** @internal Drops the pending state of the client, its mutations will never settle after clearing it */
1862
+ var resetOptimisticState = (client) => {
1863
+ clientStates.delete(client);
1864
+ };
1865
+ //#endregion
1866
+ //#region src/request/request.utils.ts
1867
+ var scopeKey = (key, scope) => {
1868
+ return scope ? `${scope}__${key}` : key;
1869
+ };
1870
+ var stringifyKey = (value) => {
1871
+ try {
1872
+ if (typeof value === "string") return value;
1873
+ if (value === void 0 || value === null) return "";
1874
+ const data = JSON.stringify(value);
1875
+ if (typeof data !== "string") throw new TypeError();
1876
+ return data;
1877
+ } catch {
1878
+ return "";
1879
+ }
1880
+ };
1881
+ var getProgressValue = ({ loaded, total }) => {
1882
+ if (!loaded || !total) return 0;
1883
+ return Number((loaded * 100 / total).toFixed(0));
1884
+ };
1885
+ var getRequestEta = (startDate, progressDate, { total, loaded }) => {
1886
+ const uploadSpeed = loaded / (+progressDate - +startDate || 1);
1887
+ const totalValue = Math.max(total, loaded);
1888
+ const sizeLeft = totalValue - loaded;
1889
+ const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;
1890
+ return {
1891
+ timeLeft: totalValue === loaded ? 0 : estimatedTimeValue,
1892
+ sizeLeft
1893
+ };
1894
+ };
1895
+ var getProgressData = (requestStartTime, progressDate, progressEvent) => {
1896
+ const { total, loaded } = progressEvent;
1897
+ if (Number.isNaN(total) || Number.isNaN(loaded)) return {
1898
+ progress: 0,
1899
+ timeLeft: 0,
1900
+ sizeLeft: 0,
1901
+ total: 0,
1902
+ loaded: 0,
1903
+ startTimestamp: +requestStartTime
1904
+ };
1905
+ const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);
1906
+ return {
1907
+ progress: getProgressValue(progressEvent),
1908
+ timeLeft,
1909
+ sizeLeft,
1910
+ total,
1911
+ loaded,
1912
+ startTimestamp: +requestStartTime
1913
+ };
2235
1914
  };
2236
- var readEntry = (client, storageKey) => {
2237
- return client.cache.get(storageKey);
1915
+ var getSimpleKey = (request) => {
1916
+ return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;
2238
1917
  };
2239
1918
  /**
2240
- * Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its
2241
- * timestamps and staleness - an optimistic value doesn't make the entry fresh.
1919
+ * Cache instance for individual request that collects individual requests responses from
1920
+ * the same endpoint (they may differ base on the custom key, endpoint params etc)
1921
+ * @param request
1922
+ * @param useInitialValues
1923
+ * @returns
2242
1924
  */
2243
- var writeData = (request, entry, data) => {
2244
- const entryRequest = request.clone({
2245
- staleTime: entry.staleTime,
2246
- cacheTime: entry.cacheTime
2247
- });
2248
- request.client.cache.set(entryRequest, {
2249
- ...entry,
2250
- data
2251
- });
1925
+ var getRequestKey = (request, useInitialValues) => {
1926
+ return `${stringifyKey(request.method)}_${useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint)}_${useInitialValues ? "" : stringifyKey(request.queryParams)}`;
2252
1927
  };
2253
- /**
2254
- * Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint
2255
- * whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).
2256
- */
2257
- var resolveTargets = (client, operation) => {
2258
- const { target } = operation;
2259
- const targets = /* @__PURE__ */ new Map();
2260
- if (!operation.allVariants) {
2261
- targets.set(scopeKey(target.cacheKey, target.scope), target);
2262
- return targets;
2263
- }
2264
- const prefix = target.cacheKey === getRequestKey(target) ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_` : `${target.cacheKey}_`;
2265
- client.cache.keys().forEach((storageKey) => {
2266
- const entry = client.cache.storage.get(storageKey);
2267
- if (!entry || entry.scope !== target.scope) return;
2268
- if (entry.cacheKey === target.cacheKey) targets.set(storageKey, target);
2269
- else if (entry.cacheKey.startsWith(prefix)) targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey));
2270
- });
2271
- return targets;
1928
+ var getRequestDispatcher = (request, dispatcherType = "auto") => {
1929
+ const { fetchDispatcher, submitDispatcher } = request.client;
1930
+ const isSafeRead = SAFE_HTTP_METHODS.includes(request.method);
1931
+ const isFetchDispatcher = dispatcherType === "auto" && isSafeRead || dispatcherType === "fetch";
1932
+ return [isFetchDispatcher ? fetchDispatcher : submitDispatcher, isFetchDispatcher];
2272
1933
  };
2273
1934
  /**
2274
- * Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:
2275
- * a throw or a promise is reported and the key gets refreshed.
1935
+ * Runs the response mapper of the request. Mapper is user code running in the middle of the response handling,
1936
+ * so its failure is logged and ends up as a failed response carrying the thrown value as the `error`.
1937
+ * Failures are always delivered through a promise, so sync and async mappers fail the same way.
1938
+ * @internal
1939
+ * @param request request with the optional response mapper
1940
+ * @param response response to be mapped
1941
+ * @returns mapped response, promise of it for async and failed mappers, `undefined` when there is no mapper
2276
1942
  */
2277
- var runSettleCallback = (pending, { operation, storageKey, request, previous }, outcome) => {
2278
- const { client } = pending;
2279
- const entry = readEntry(client, storageKey);
2280
- const isCommit = outcome.type === "success";
2281
- const title = isCommit ? "Optimistic commit failed" : "Optimistic rollback failed";
2282
- const run = (data) => {
2283
- if (outcome.type === "success") {
2284
- const response = outcome.response;
2285
- return operation.onCommit?.({
2286
- data,
2287
- response,
2288
- request: outcome.request
2289
- });
2290
- }
2291
- const { type: _type, ...args } = outcome;
2292
- return operation.onRollback?.({
2293
- ...args,
2294
- data,
2295
- previous
2296
- });
2297
- };
2298
- if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) return;
2299
- try {
2300
- const next = run(entry.data);
2301
- if (next instanceof Promise) {
2302
- next.catch((error) => reportFailure(client, title, {
1943
+ var runResponseMapper = (request, response) => {
1944
+ const getFailedResponse = (error) => {
1945
+ request.client.logger.error({
1946
+ title: "Response mapper failed",
1947
+ type: "system",
1948
+ extra: {
2303
1949
  error,
2304
- storageKey
2305
- }));
2306
- throw new TypeError("Optimistic rollback and commit must be synchronous, the returned promise was ignored");
2307
- }
2308
- if (next !== void 0 && next !== entry.data) writeData(request, entry, next);
2309
- } catch (error) {
2310
- reportFailure(client, title, {
2311
- error,
2312
- storageKey,
2313
- request: outcome.request
1950
+ request,
1951
+ response
1952
+ }
2314
1953
  });
2315
- pending.failed.add(storageKey);
2316
- }
2317
- };
2318
- /** Rollback of the hand-written object form - runs once, its failure can't affect the request */
2319
- var runObjectRollback = (pending, args) => {
2320
- const { client, result } = pending;
2321
- const onFailure = (error) => {
2322
- reportFailure(client, "Optimistic rollback failed", {
1954
+ return {
1955
+ ...response,
1956
+ data: null,
2323
1957
  error,
2324
- reason: args.reason,
2325
- request: args.request
2326
- });
1958
+ success: false
1959
+ };
2327
1960
  };
2328
1961
  try {
2329
- Promise.resolve(result.rollback?.(args)).catch(onFailure);
1962
+ const mapping = request.unstable_responseMapper?.(response);
1963
+ return mapping instanceof Promise ? mapping.catch(getFailedResponse) : mapping;
2330
1964
  } catch (error) {
2331
- onFailure(error);
1965
+ return Promise.resolve(getFailedResponse(error));
2332
1966
  }
2333
1967
  };
2334
- var runObjectInvalidation = ({ client, result }, request) => {
2335
- result.invalidate?.forEach((target) => {
1968
+ var mapResponseForSend = async (request, response) => {
1969
+ const mapping = runResponseMapper(request, response);
1970
+ if (mapping instanceof Promise) return await mapping;
1971
+ return mapping || response;
1972
+ };
1973
+ var sendRequest = async (request, options) => {
1974
+ const { client } = request;
1975
+ const { requestManager } = client;
1976
+ const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
1977
+ let mutationContext;
1978
+ let pendingOptimistic;
1979
+ const optimisticSource = options?.optimistic ?? request.optimistic;
1980
+ if (optimisticSource) {
2336
1981
  try {
2337
- client.cache.invalidate(target);
2338
- } catch (error) {
2339
- reportFailure(client, "Optimistic invalidation failed", {
2340
- error,
2341
- target,
2342
- request
1982
+ const result = Array.isArray(optimisticSource) ? optimisticSource : optimisticSource({
1983
+ request,
1984
+ client: request.client,
1985
+ payload: request.payload,
1986
+ params: request.params,
1987
+ queryParams: request.queryParams,
1988
+ optimistic
2343
1989
  });
1990
+ mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);
1991
+ } catch (error) {
1992
+ return {
1993
+ data: null,
1994
+ error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${error instanceof Error ? error.message : error}`),
1995
+ status: null,
1996
+ success: false,
1997
+ extra: client.adapter.defaultExtra,
1998
+ requestTimestamp: Date.now(),
1999
+ responseTimestamp: Date.now()
2000
+ };
2344
2001
  }
2345
- });
2346
- };
2347
- /**
2348
- * `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.
2349
- * A predicate that throws is reported and the change is reverted.
2350
- */
2351
- var shouldRollback = (pending, outcome) => {
2352
- const { rollbackOnError } = pending.result;
2353
- if (outcome.reason !== "error" || rollbackOnError === void 0 || rollbackOnError === true) return true;
2354
- if (rollbackOnError === false) return false;
2355
- try {
2356
- return !!rollbackOnError({
2357
- response: outcome.response,
2358
- request: outcome.request
2002
+ pendingOptimistic = applyOptimistic(client, mutationContext);
2003
+ }
2004
+ return new Promise((resolve) => {
2005
+ let isResolved = false;
2006
+ let isDelivered = false;
2007
+ let isSettled = false;
2008
+ const requestId = dispatcher.add(request);
2009
+ const queryKey = scopeKey(request.queryKey, request.scope);
2010
+ const { $hooks } = request;
2011
+ const getWillBeResent = ({ response, details }) => {
2012
+ if (response.success || details.isCanceled) return false;
2013
+ if (!dispatcher.getRequest(queryKey, requestId)) return false;
2014
+ return details.willRetry || request.offline && details.isOffline;
2015
+ };
2016
+ const mappings = /* @__PURE__ */ new WeakMap();
2017
+ const getMapping = (values) => {
2018
+ if (!mappings.has(values)) mappings.set(values, runResponseMapper(request, values.response));
2019
+ return mappings.get(values);
2020
+ };
2021
+ const unmountSettlement = pendingOptimistic ? requestManager.events.onResponseById(requestId, (values) => {
2022
+ const pending = pendingOptimistic;
2023
+ const willBeResent = getWillBeResent(values);
2024
+ const settle = (response) => {
2025
+ if (isSettled || !response.success && willBeResent) return;
2026
+ isSettled = true;
2027
+ if (values.details.isCanceled) settleOptimistic(pending, {
2028
+ type: "rollback",
2029
+ reason: "abort",
2030
+ response,
2031
+ request
2032
+ });
2033
+ else if (response.success) settleOptimistic(pending, {
2034
+ type: "success",
2035
+ response,
2036
+ request
2037
+ });
2038
+ else settleOptimistic(pending, {
2039
+ type: "rollback",
2040
+ reason: "error",
2041
+ response,
2042
+ request
2043
+ });
2044
+ };
2045
+ const mapping = getMapping(values);
2046
+ if (mapping instanceof Promise) mapping.then(settle);
2047
+ else settle(mapping || values.response);
2048
+ }) : void 0;
2049
+ const beforeSentData = {
2050
+ requestId,
2051
+ request,
2052
+ mutationContext
2053
+ };
2054
+ runUserCode(() => options?.onBeforeSent?.(beforeSentData));
2055
+ runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
2056
+ const unmountRequestStart = requestManager.events.onRequestStartById(requestId, (data) => {
2057
+ const enriched = {
2058
+ ...data,
2059
+ mutationContext
2060
+ };
2061
+ runUserCode(() => options?.onRequestStart?.(enriched));
2062
+ runUserCode(() => $hooks.__emit("onRequestStart", enriched));
2359
2063
  });
2360
- } catch (error) {
2361
- reportFailure(pending.client, "Optimistic rollbackOnError failed", {
2362
- error,
2363
- request: outcome.request
2064
+ const unmountResponseStart = requestManager.events.onResponseStartById(requestId, (data) => {
2065
+ const enriched = {
2066
+ ...data,
2067
+ mutationContext
2068
+ };
2069
+ runUserCode(() => options?.onResponseStart?.(enriched));
2070
+ runUserCode(() => $hooks.__emit("onResponseStart", enriched));
2071
+ });
2072
+ const unmountUpload = requestManager.events.onUploadProgressById(requestId, (data) => {
2073
+ const enriched = {
2074
+ ...data,
2075
+ mutationContext
2076
+ };
2077
+ runUserCode(() => options?.onUploadProgress?.(enriched));
2078
+ runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
2364
2079
  });
2365
- return true;
2366
- }
2367
- };
2368
- var getRunningRequestsOnKey = (client, storageKey) => {
2369
- return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey);
2370
- };
2371
- var hasStaleRequests = (state, storageKey) => {
2372
- return [...state.staleRequests.values()].includes(storageKey);
2373
- };
2374
- /** Refreshes the key once nothing pending or stale is left on it */
2375
- var refreshWhenIdle = (client, state, storageKey) => {
2376
- const keyState = state.keys.get(storageKey);
2377
- if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) return;
2378
- state.keys.delete(storageKey);
2379
- if (keyState.refresh) client.cache.invalidate(keyState.request);
2380
- };
2381
- var release = (pending, refresh) => {
2382
- const { client, targets, failed, guarded } = pending;
2383
- const state = getClientState(client);
2384
- targets.forEach((request, storageKey) => {
2385
- const keyState = state.keys.get(storageKey);
2386
- const shouldRefresh = refresh || failed.has(storageKey);
2387
- if (!guarded.has(storageKey)) {
2388
- if (keyState && shouldRefresh) keyState.refresh = true;
2389
- else if (shouldRefresh) client.cache.invalidate(request);
2390
- return;
2391
- }
2392
- if (!keyState) return;
2393
- keyState.pending -= 1;
2394
- keyState.refresh = keyState.refresh || shouldRefresh;
2395
- keyState.request = request;
2396
- getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {
2397
- state.staleRequests.set(requestId, storageKey);
2080
+ const unmountDownload = requestManager.events.onDownloadProgressById(requestId, (data) => {
2081
+ const enriched = {
2082
+ ...data,
2083
+ mutationContext
2084
+ };
2085
+ runUserCode(() => options?.onDownloadProgress?.(enriched));
2086
+ runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
2398
2087
  });
2399
- refreshWhenIdle(client, state, storageKey);
2400
- });
2401
- };
2402
- /**
2403
- * @internal
2404
- * Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.
2405
- */
2406
- var getOptimisticResult = (value) => {
2407
- if (Array.isArray(value)) return { updates: value };
2408
- return value || {};
2409
- };
2410
- /**
2411
- * @internal
2412
- * Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,
2413
- * the others still apply.
2414
- */
2415
- var applyOptimistic = (client, result) => {
2416
- const pending = {
2417
- client,
2418
- result,
2419
- applied: [],
2420
- targets: /* @__PURE__ */ new Map(),
2421
- guarded: /* @__PURE__ */ new Set(),
2422
- failed: /* @__PURE__ */ new Set()
2423
- };
2424
- const state = getClientState(client);
2425
- result.updates?.forEach((value) => {
2426
- try {
2427
- if (!(value instanceof OptimisticOperation)) throw new TypeError("Optimistic updates accept operations created with optimistic()");
2428
- const operation = value;
2429
- resolveTargets(client, operation).forEach((request, storageKey) => {
2430
- pending.targets.set(storageKey, request);
2431
- const entry = readEntry(client, storageKey);
2432
- if (!entry) return;
2433
- try {
2434
- const next = operation.update(entry.data);
2435
- if (next !== entry.data) writeData(request, entry, next);
2436
- pending.applied.push({
2437
- operation,
2438
- storageKey,
2439
- request,
2440
- previous: entry.data
2441
- });
2442
- pending.guarded.add(storageKey);
2443
- } catch (error) {
2444
- reportFailure(client, "Optimistic update failed", {
2445
- error,
2446
- storageKey
2088
+ const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
2089
+ const { response } = values;
2090
+ const willBeResent = getWillBeResent(values);
2091
+ isResolved = !willBeResent;
2092
+ const enrichedValues = {
2093
+ ...values,
2094
+ mutationContext
2095
+ };
2096
+ const mapping = getMapping(values);
2097
+ const handleResponse = (success, data) => {
2098
+ if (isDelivered || !success && willBeResent) return;
2099
+ isDelivered = true;
2100
+ runUserCode(() => options?.onResponse?.(enrichedValues));
2101
+ runUserCode(() => $hooks.__emit("onResponse", enrichedValues));
2102
+ resolve(data);
2103
+ umountAll();
2104
+ };
2105
+ if (mapping instanceof Promise) (async () => {
2106
+ const responseData = await mapping;
2107
+ const { success } = responseData;
2108
+ handleResponse(success, responseData);
2109
+ })();
2110
+ else {
2111
+ const data = mapping || response;
2112
+ const { success } = data;
2113
+ handleResponse(success, data);
2114
+ }
2115
+ });
2116
+ const unmountRemoveQueueElement = requestManager.events.onRemoveById(requestId, (data) => {
2117
+ if (!isResolved) {
2118
+ isResolved = true;
2119
+ isDelivered = true;
2120
+ if (pendingOptimistic && !isSettled) {
2121
+ isSettled = true;
2122
+ settleOptimistic(pendingOptimistic, {
2123
+ type: "rollback",
2124
+ reason: "removed",
2125
+ request
2447
2126
  });
2448
- pending.failed.add(storageKey);
2449
2127
  }
2450
- });
2451
- } catch (error) {
2452
- reportFailure(client, "Optimistic update failed", {
2453
- error,
2454
- operation: value
2455
- });
2128
+ const enriched = {
2129
+ ...data,
2130
+ mutationContext
2131
+ };
2132
+ runUserCode(() => options?.onRemove?.(enriched));
2133
+ runUserCode(() => $hooks.__emit("onRemove", enriched));
2134
+ resolve({
2135
+ data: null,
2136
+ status: null,
2137
+ success: false,
2138
+ error: getErrorMessage("deleted"),
2139
+ extra: request.client.adapter.defaultExtra,
2140
+ requestTimestamp: Date.now(),
2141
+ responseTimestamp: Date.now()
2142
+ });
2143
+ umountAll();
2144
+ }
2145
+ });
2146
+ function umountAll() {
2147
+ unmountSettlement?.();
2148
+ unmountRequestStart();
2149
+ unmountResponseStart();
2150
+ unmountUpload();
2151
+ unmountDownload();
2152
+ unmountResponse();
2153
+ unmountRemoveQueueElement();
2456
2154
  }
2457
2155
  });
2458
- pending.guarded.forEach((storageKey) => {
2459
- const request = pending.targets.get(storageKey);
2460
- const keyState = state.keys.get(storageKey) ?? {
2461
- pending: 0,
2462
- refresh: false,
2463
- request
2464
- };
2465
- keyState.pending += 1;
2466
- state.keys.set(storageKey, keyState);
2467
- });
2468
- return pending;
2469
- };
2470
- /**
2471
- * @internal
2472
- * Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the
2473
- * rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.
2474
- */
2475
- var settleOptimistic = (pending, outcome) => {
2476
- const { result, applied } = pending;
2477
- const canRefresh = result.revalidate !== false;
2478
- if (outcome.type === "success") {
2479
- applied.forEach((operation) => runSettleCallback(pending, operation, outcome));
2480
- runObjectInvalidation(pending, outcome.request);
2481
- return release(pending, canRefresh);
2482
- }
2483
- const { type: _type, ...args } = outcome;
2484
- if (!shouldRollback(pending, args)) return release(pending, false);
2485
- for (let index = applied.length - 1; index >= 0; index -= 1) runSettleCallback(pending, applied[index], outcome);
2486
- runObjectRollback(pending, args);
2487
- return release(pending, canRefresh);
2488
- };
2489
- /**
2490
- * @internal
2491
- * Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a
2492
- * mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the
2493
- * refresh after the mutation supplies current data. Keys that had no data when the change was applied are not
2494
- * guarded, so a first load is never held back. Manual cache writes don't go through this check.
2495
- */
2496
- var isStaleOptimisticResponse = (client, request, requestId) => {
2497
- const state = clientStates.get(client);
2498
- if (!state) return false;
2499
- const storageKey = scopeKey(request.cacheKey, request.scope);
2500
- const isMarked = state.staleRequests.delete(requestId);
2501
- const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;
2502
- if (isMarked) refreshWhenIdle(client, state, storageKey);
2503
- return isMarked || isPending;
2504
- };
2505
- /** @internal Drops the pending state of the client, its mutations will never settle after clearing it */
2506
- var resetOptimisticState = (client) => {
2507
- clientStates.delete(client);
2508
2156
  };
2509
2157
  //#endregion
2510
- //#region src/plugin/plugin.ts
2158
+ //#region src/request/request.ts
2511
2159
  /**
2512
- * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.
2513
- * Extend this to build devtools, logging, analytics, or custom side-effect plugins.
2160
+ * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.
2161
+ * It is executed at any time via methods like `send` or `exec`.
2162
+ *
2163
+ * We can set it up with options like endpoint, method, headers and more.
2164
+ * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.
2165
+ *
2166
+ * @info We should not use this class directly in the standard development flow.
2167
+ * We can initialize it using the `createRequest` method on the **Client** class.
2168
+ *
2169
+ * @attention The most important thing about the request is that it keeps data in the format that can be dumped.
2170
+ * This is necessary for the persistence and different dispatcher storage types.
2171
+ * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.
2172
+ *
2173
+ * It should be serializable to JSON and deserializable back to the class.
2174
+ * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.
2514
2175
  */
2515
- var Plugin = class {
2516
- name;
2517
- data;
2518
- client = void 0;
2519
- pluginMethods = {};
2520
- constructor(config) {
2521
- this.config = config;
2522
- this.name = config.name;
2523
- if (config.data) this.data = config.data;
2524
- }
2525
- /** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */
2526
- initialize = (client) => {
2176
+ var Request = class Request {
2177
+ endpoint;
2178
+ headers = void 0;
2179
+ auth;
2180
+ method;
2181
+ params;
2182
+ payload;
2183
+ queryParams;
2184
+ options = void 0;
2185
+ cancelable;
2186
+ retry;
2187
+ retryTime;
2188
+ cacheTime;
2189
+ cache;
2190
+ staleTime;
2191
+ queued;
2192
+ offline;
2193
+ abortKey;
2194
+ cacheKey;
2195
+ queryKey;
2196
+ used;
2197
+ deduplicate;
2198
+ deduplicateTime;
2199
+ structuralSharing;
2200
+ scope;
2201
+ /**
2202
+ * Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call
2203
+ * made on this request instance (and its clones), without needing to pass them to `send()` each time.
2204
+ * Useful for cross-cutting concerns like logging, analytics, or toast notifications.
2205
+ *
2206
+ * Each method registers a callback and returns an unsubscribe function.
2207
+ * Multiple listeners per hook are supported.
2208
+ */
2209
+ $hooks = createRequestHooks();
2210
+ isMockerEnabled = false;
2211
+ static OPTIONAL_FIELDS = [
2212
+ "unstable_mock",
2213
+ "unstable_payloadMapper",
2214
+ "unstable_requestMapper",
2215
+ "unstable_responseMapper",
2216
+ "retryOnError",
2217
+ "optimistic"
2218
+ ];
2219
+ unstable_mock = void 0;
2220
+ /** @internal */
2221
+ unstable_payloadMapper = void 0;
2222
+ /** @internal */
2223
+ unstable_requestMapper = void 0;
2224
+ /** @internal */
2225
+ unstable_responseMapper = void 0;
2226
+ /** @internal */
2227
+ retryOnError = void 0;
2228
+ /** @internal */
2229
+ optimistic = void 0;
2230
+ unstable_hasParams = false;
2231
+ unstable_hasPayload = false;
2232
+ unstable_hasQuery = false;
2233
+ unstable_hasMutationContext = void 0;
2234
+ updatedAbortKey;
2235
+ updatedCacheKey;
2236
+ updatedQueryKey;
2237
+ constructor(client, requestOptions, initialRequestConfiguration) {
2527
2238
  this.client = client;
2528
- return this;
2239
+ this.requestOptions = requestOptions;
2240
+ this.initialRequestConfiguration = initialRequestConfiguration;
2241
+ const { endpoint, headers, auth = true, method = client.adapter.defaultMethod, options, cancelable = false, retry = 0, retryTime = 500, cacheTime = Time.MIN * 5, cache = true, staleTime = Time.MIN * 5, queued = false, offline = true, abortKey, cacheKey, queryKey, deduplicate = false, deduplicateTime = null, structuralSharing = true } = {
2242
+ ...this.client.adapter.unstable_getRequestDefaults?.(requestOptions),
2243
+ ...requestOptions
2244
+ };
2245
+ this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;
2246
+ this.headers = initialRequestConfiguration?.headers ?? headers;
2247
+ this.auth = initialRequestConfiguration?.auth ?? auth;
2248
+ this.method = method;
2249
+ this.params = initialRequestConfiguration?.params;
2250
+ this.payload = initialRequestConfiguration?.payload;
2251
+ this.queryParams = initialRequestConfiguration?.queryParams;
2252
+ this.options = initialRequestConfiguration?.options ?? options;
2253
+ this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;
2254
+ this.retry = initialRequestConfiguration?.retry ?? retry;
2255
+ this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;
2256
+ this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;
2257
+ this.cache = initialRequestConfiguration?.cache ?? cache;
2258
+ this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;
2259
+ this.queued = initialRequestConfiguration?.queued ?? queued;
2260
+ this.offline = initialRequestConfiguration?.offline ?? offline;
2261
+ this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);
2262
+ this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);
2263
+ this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);
2264
+ this.used = initialRequestConfiguration?.used ?? false;
2265
+ this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;
2266
+ this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;
2267
+ this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;
2268
+ this.scope = initialRequestConfiguration?.scope ?? null;
2269
+ this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;
2270
+ this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;
2271
+ this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;
2272
+ }
2273
+ /** Set the request headers. Returns a cloned request with the new headers applied. */
2274
+ setHeaders = (headers) => {
2275
+ return this.clone({ headers });
2529
2276
  };
2530
- /** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */
2531
- trigger = (method, data) => {
2532
- const callback = this.pluginMethods[method];
2533
- if (callback) callback(data);
2277
+ /** Set whether authentication interceptors should run for this request. */
2278
+ setAuth = (auth) => {
2279
+ return this.clone({ auth });
2534
2280
  };
2535
- /**
2536
- * Callback that will be executed when plugin is mounted
2537
- */
2538
- onMount = (callback) => {
2539
- this.pluginMethods.onMount = callback;
2540
- return this;
2281
+ /** Set the URL path parameters (e.g., `:userId`). */
2282
+ setParams = (params) => {
2283
+ return this.clone({ params });
2541
2284
  };
2542
- /**
2543
- * Callback that will be executed when plugin is unmounted
2544
- */
2545
- onUnmount = (callback) => {
2546
- this.pluginMethods.onUnmount = callback;
2547
- return this;
2285
+ /** Set the request body payload. Passing `null` removes the payload set before. */
2286
+ setPayload = (payload) => {
2287
+ return this.clone({ payload });
2548
2288
  };
2549
- /**
2550
- * Callback that will be executed when request is created
2551
- */
2552
- onRequestCreate = (callback) => {
2553
- this.pluginMethods.onRequestCreate = callback;
2554
- return this;
2289
+ /** Set the query parameters appended to the URL. */
2290
+ setQueryParams = (queryParams) => {
2291
+ return this.clone({ queryParams });
2555
2292
  };
2556
- /**
2557
- * Callback that will be executed when request gets triggered
2558
- */
2559
- onRequestTrigger = (callback) => {
2560
- this.pluginMethods.onRequestTrigger = callback;
2561
- return this;
2293
+ /** Set adapter-specific options (e.g., axios config, fetch init). */
2294
+ setOptions = (options) => {
2295
+ return this.clone({ options });
2562
2296
  };
2563
2297
  /**
2564
- * Callback that will be executed when request starts
2298
+ * Set a scope identifier for this request.
2299
+ * All keys (cache, queue, abort) are prefixed with this scope, isolating
2300
+ * the request from other scopes. In "server" client mode, setting a scope
2301
+ * also enables caching (which is otherwise disabled to prevent cross-request leaks).
2565
2302
  */
2566
- onRequestStart = (callback) => {
2567
- this.pluginMethods.onRequestStart = callback;
2568
- return this;
2303
+ setScope = (scopeId) => {
2304
+ const cloned = this.clone();
2305
+ cloned.scope = scopeId;
2306
+ return cloned;
2569
2307
  };
2570
- /**
2571
- * Callback that will be executed when response is successful
2572
- */
2573
- onRequestSuccess = (callback) => {
2574
- this.pluginMethods.onRequestSuccess = callback;
2575
- return this;
2308
+ /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */
2309
+ setCancelable = (cancelable) => {
2310
+ return this.clone({ cancelable });
2311
+ };
2312
+ /** Set the number of retry attempts on failure. */
2313
+ setRetry = (retry) => {
2314
+ return this.clone({ retry });
2315
+ };
2316
+ /** Set the delay in milliseconds between retry attempts. */
2317
+ setRetryTime = (retryTime) => {
2318
+ return this.clone({ retryTime });
2576
2319
  };
2577
2320
  /**
2578
- * Callback that will be executed when response is failed
2321
+ * Set a callback that controls whether a failed request should be retried.
2322
+ * Called on each failed attempt before scheduling the next retry.
2323
+ * Return `true` to allow the retry, `false` to stop retrying immediately.
2579
2324
  */
2580
- onRequestError = (callback) => {
2581
- this.pluginMethods.onRequestError = callback;
2582
- return this;
2325
+ setRetryOnError = (callback) => {
2326
+ const cloned = this.clone();
2327
+ cloned.retryOnError = callback;
2328
+ return cloned;
2583
2329
  };
2584
2330
  /**
2585
- * Callback that will be executed when response is finished
2331
+ * Configure optimistic update behavior for this request.
2332
+ * The callback runs before the request is sent and receives `{ request, client, payload, params, queryParams,
2333
+ * optimistic }`. A synchronous callback changes the cache within the `send()` call.
2334
+ *
2335
+ * Return an array of changes built with `optimistic()` - core applies them, runs their `.commit()` on success or
2336
+ * `.rollback()` on final failure, abort or queue removal, and refreshes the targets after the last pending mutation
2337
+ * on them. Or return an object with `updates`, `context` (available in lifecycle callbacks as `mutationContext`),
2338
+ * `rollback` (called once on failure, abort or queue removal), `invalidate` (requests invalidated on success),
2339
+ * `rollbackOnError` and `revalidate`.
2340
+ * Everything runs for every way of sending the request, not only inside of framework hooks.
2341
+ *
2342
+ * @example
2343
+ * toggleTodo.setOptimistic(({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)]);
2586
2344
  */
2587
- onRequestFinished = (callback) => {
2588
- this.pluginMethods.onRequestFinished = callback;
2589
- return this;
2345
+ setOptimistic = (callback) => {
2346
+ const cloned = this.clone();
2347
+ cloned.optimistic = callback;
2348
+ return cloned;
2590
2349
  };
2591
- /** Called when the dispatcher storage is fully cleared */
2592
- onDispatcherCleared = (callback) => {
2593
- this.pluginMethods.onDispatcherCleared = callback;
2350
+ /** Set how long (in ms) the response remains in cache before being garbage collected. */
2351
+ setCacheTime = (cacheTime) => {
2352
+ return this.clone({ cacheTime });
2353
+ };
2354
+ /** Set whether this request should use the cache. */
2355
+ setCache = (cache) => {
2356
+ return this.clone({ cache });
2357
+ };
2358
+ /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */
2359
+ setStaleTime = (staleTime) => {
2360
+ return this.clone({ staleTime });
2361
+ };
2362
+ /** Set whether the request should be queued and executed sequentially rather than immediately. */
2363
+ setQueued = (queued) => {
2364
+ return this.clone({ queued });
2365
+ };
2366
+ /** Override the abort key used to cancel this request. */
2367
+ setAbortKey = (abortKey) => {
2368
+ return this.clone({
2369
+ abortKey,
2370
+ updatedAbortKey: true
2371
+ });
2372
+ };
2373
+ /** Override the cache key used to store/retrieve the response. */
2374
+ setCacheKey = (cacheKey) => {
2375
+ return this.clone({
2376
+ cacheKey,
2377
+ updatedCacheKey: true
2378
+ });
2379
+ };
2380
+ /** Override the query key that identifies this request in the dispatcher queue. */
2381
+ setQueryKey = (queryKey) => {
2382
+ return this.clone({
2383
+ queryKey,
2384
+ updatedQueryKey: true
2385
+ });
2386
+ };
2387
+ /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
2388
+ setDeduplicate = (deduplicate) => {
2389
+ return this.clone({ deduplicate });
2390
+ };
2391
+ /** Set the time window (in ms) during which identical requests are deduplicated. */
2392
+ setDeduplicateTime = (deduplicateTime) => {
2393
+ return this.clone({ deduplicateTime });
2394
+ };
2395
+ /** Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache. */
2396
+ setStructuralSharing = (structuralSharing) => {
2397
+ return this.clone({ structuralSharing });
2398
+ };
2399
+ /** Mark the request as used (prevents automatic refetching in hooks). */
2400
+ setUsed = (used) => {
2401
+ return this.clone({ used });
2402
+ };
2403
+ /** Set whether the request should be stored in the offline queue when there is no network connection. */
2404
+ setOffline = (offline) => {
2405
+ return this.clone({ offline });
2406
+ };
2407
+ /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */
2408
+ setMock = (fn, config = {}) => {
2409
+ this.unstable_mock = {
2410
+ fn,
2411
+ config
2412
+ };
2413
+ this.isMockerEnabled = true;
2594
2414
  return this;
2595
2415
  };
2596
- /** Called when a dispatcher queue has no more pending requests */
2597
- onDispatcherQueueDrained = (callback) => {
2598
- this.pluginMethods.onDispatcherQueueDrained = callback;
2416
+ /** Remove any attached mock handler and disable mocking for this request. */
2417
+ clearMock = () => {
2418
+ this.unstable_mock = void 0;
2419
+ this.isMockerEnabled = false;
2599
2420
  return this;
2600
2421
  };
2601
- /** Called when a dispatcher queue transitions to running, paused, or stopped */
2602
- onDispatcherQueueRunning = (callback) => {
2603
- this.pluginMethods.onDispatcherQueueRunning = callback;
2422
+ /** Enable or disable the mocker for this request without removing the mock handler. */
2423
+ setMockingEnabled = (isMockerEnabled) => {
2424
+ this.isMockerEnabled = isMockerEnabled;
2604
2425
  return this;
2605
2426
  };
2606
- /** Called when a new item is added to a dispatcher queue */
2607
- onDispatcherItemAdded = (callback) => {
2608
- this.pluginMethods.onDispatcherItemAdded = callback;
2609
- return this;
2427
+ /**
2428
+ * Map data before it gets send to the server
2429
+ * @param payloadMapper
2430
+ * @returns
2431
+ */
2432
+ setPayloadMapper = (payloadMapper) => {
2433
+ const cloned = this.clone();
2434
+ cloned.unstable_payloadMapper = payloadMapper;
2435
+ return cloned;
2610
2436
  };
2611
- /** Called when an item is removed from a dispatcher queue */
2612
- onDispatcherItemDeleted = (callback) => {
2613
- this.pluginMethods.onDispatcherItemDeleted = callback;
2614
- return this;
2437
+ /**
2438
+ * Map request before it gets send to the server
2439
+ * @param requestMapper mapper of the request
2440
+ * @returns new request
2441
+ */
2442
+ setRequestMapper = (requestMapper) => {
2443
+ const cloned = this.clone();
2444
+ cloned.unstable_requestMapper = requestMapper;
2445
+ return cloned;
2615
2446
  };
2616
- /** Called when a new dispatcher queue is created */
2617
- onDispatcherQueueCreated = (callback) => {
2618
- this.pluginMethods.onDispatcherQueueCreated = callback;
2619
- return this;
2447
+ /**
2448
+ * Map the response to the new interface
2449
+ * @param responseMapper our mapping callback
2450
+ * @returns new response
2451
+ */
2452
+ setResponseMapper = (responseMapper) => {
2453
+ const cloned = this.clone();
2454
+ cloned.unstable_responseMapper = responseMapper;
2455
+ return cloned;
2620
2456
  };
2621
- /** Called when an entire dispatcher queue is cleared */
2622
- onDispatcherQueueCleared = (callback) => {
2623
- this.pluginMethods.onDispatcherQueueCleared = callback;
2624
- return this;
2457
+ paramsMapper = (params) => {
2458
+ const { endpoint } = this.requestOptions;
2459
+ const stringEndpoint = String(endpoint);
2460
+ const names = params ? Object.keys(params) : [];
2461
+ if (!params || names.length === 0) return stringEndpoint;
2462
+ const [start, ...segments] = stringEndpoint.split(":");
2463
+ return [start, ...segments.map((segment) => {
2464
+ const name = names.reduce((longest, current) => segment.startsWith(current) && current.length > longest.length ? current : longest, "");
2465
+ return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;
2466
+ })].join("");
2625
2467
  };
2626
- /** Called when a cache entry is created or updated */
2627
- onCacheItemChange = (callback) => {
2628
- this.pluginMethods.onCacheItemChange = callback;
2629
- return this;
2468
+ /** Serialize the request configuration into a plain JSON object for persistence or transfer. */
2469
+ toJSON() {
2470
+ return {
2471
+ requestOptions: this.requestOptions,
2472
+ endpoint: this.endpoint,
2473
+ headers: this.headers,
2474
+ auth: this.auth,
2475
+ method: this.method,
2476
+ params: this.params,
2477
+ payload: this.payload,
2478
+ queryParams: this.queryParams,
2479
+ options: this.options,
2480
+ cancelable: this.cancelable,
2481
+ retry: this.retry,
2482
+ retryTime: this.retryTime,
2483
+ cacheTime: this.cacheTime,
2484
+ cache: this.cache,
2485
+ staleTime: this.staleTime,
2486
+ queued: this.queued,
2487
+ offline: this.offline,
2488
+ abortKey: this.abortKey,
2489
+ cacheKey: this.cacheKey,
2490
+ queryKey: this.queryKey,
2491
+ used: this.used,
2492
+ disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,
2493
+ disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,
2494
+ updatedAbortKey: this.updatedAbortKey,
2495
+ updatedCacheKey: this.updatedCacheKey,
2496
+ updatedQueryKey: this.updatedQueryKey,
2497
+ deduplicate: this.deduplicate,
2498
+ deduplicateTime: this.deduplicateTime,
2499
+ structuralSharing: this.structuralSharing,
2500
+ scope: this.scope,
2501
+ isMockerEnabled: this.isMockerEnabled,
2502
+ hasMock: !!this.unstable_mock
2503
+ };
2504
+ }
2505
+ /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */
2506
+ clone(configuration) {
2507
+ const initialRequestConfiguration = {
2508
+ ...this.toJSON(),
2509
+ ...configuration,
2510
+ options: configuration?.options || this.options,
2511
+ abortKey: configuration?.abortKey || (this.updatedAbortKey ? this.abortKey : void 0),
2512
+ cacheKey: configuration?.cacheKey || (this.updatedCacheKey ? this.cacheKey : void 0),
2513
+ queryKey: configuration?.queryKey || (this.updatedQueryKey ? this.queryKey : void 0),
2514
+ updatedAbortKey: !!configuration?.abortKey || this.updatedAbortKey,
2515
+ updatedCacheKey: !!configuration?.cacheKey || this.updatedCacheKey,
2516
+ updatedQueryKey: !!configuration?.queryKey || this.updatedQueryKey,
2517
+ endpoint: this.paramsMapper(configuration?.params || this.params),
2518
+ queryParams: configuration?.queryParams || this.queryParams,
2519
+ payload: configuration?.payload === null ? void 0 : configuration?.payload ?? this.payload,
2520
+ params: configuration?.params || this.params
2521
+ };
2522
+ const cloned = new Request(this.client, this.requestOptions, initialRequestConfiguration);
2523
+ cloned.unstable_payloadMapper = this.unstable_payloadMapper;
2524
+ cloned.unstable_responseMapper = this.unstable_responseMapper;
2525
+ cloned.unstable_requestMapper = this.unstable_requestMapper;
2526
+ cloned.retryOnError = this.retryOnError;
2527
+ cloned.unstable_mock = this.unstable_mock;
2528
+ cloned.isMockerEnabled = this.isMockerEnabled;
2529
+ cloned.optimistic = this.optimistic;
2530
+ cloned.$hooks = createRequestHooks(this.$hooks.__snapshot());
2531
+ return cloned;
2532
+ }
2533
+ /** Abort all in-flight requests sharing this request's abort key. */
2534
+ abort = () => {
2535
+ const { requestManager } = this.client;
2536
+ requestManager.abortByKey(scopeKey(this.abortKey, this.scope));
2537
+ return this.clone();
2630
2538
  };
2631
- /** Called when a cache entry is deleted */
2632
- onCacheItemDelete = (callback) => {
2633
- this.pluginMethods.onCacheItemDelete = callback;
2634
- return this;
2539
+ /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */
2540
+ dehydrate = (config) => {
2541
+ const { response, override = true } = config || {};
2542
+ if (response) return {
2543
+ override,
2544
+ cacheTime: this.cacheTime,
2545
+ staleTime: this.staleTime,
2546
+ cacheKey: this.cacheKey,
2547
+ scope: this.scope,
2548
+ timestamp: Date.now(),
2549
+ hydrated: true,
2550
+ cache: true,
2551
+ response
2552
+ };
2553
+ const cacheData = this.client.cache.get(scopeKey(this.cacheKey, this.scope));
2554
+ if (!cacheData) return;
2555
+ return {
2556
+ override,
2557
+ cacheTime: this.cacheTime,
2558
+ staleTime: this.staleTime,
2559
+ cacheKey: this.cacheKey,
2560
+ scope: this.scope,
2561
+ timestamp: Date.now(),
2562
+ hydrated: true,
2563
+ cache: true,
2564
+ response: {
2565
+ data: cacheData.data,
2566
+ error: cacheData.error,
2567
+ status: cacheData.status,
2568
+ success: cacheData.success,
2569
+ extra: cacheData.extra,
2570
+ requestTimestamp: cacheData.requestTimestamp,
2571
+ responseTimestamp: cacheData.responseTimestamp
2572
+ }
2573
+ };
2635
2574
  };
2636
- /** Called when a cache entry is invalidated */
2637
- onCacheItemInvalidate = (callback) => {
2638
- this.pluginMethods.onCacheItemInvalidate = callback;
2639
- return this;
2575
+ /**
2576
+ * Read the response from cache data
2577
+ *
2578
+ * If it returns error and data at the same time, it means that latest request was failed
2579
+ * and we show previous data from cache together with error received from actual request
2580
+ */
2581
+ read() {
2582
+ const cacheData = this.client.cache.get(scopeKey(this.cacheKey, this.scope));
2583
+ if (cacheData) return {
2584
+ data: cacheData.data,
2585
+ error: cacheData.error,
2586
+ status: cacheData.status,
2587
+ success: cacheData.success,
2588
+ extra: cacheData.extra,
2589
+ requestTimestamp: cacheData.requestTimestamp,
2590
+ responseTimestamp: cacheData.responseTimestamp
2591
+ };
2592
+ }
2593
+ /**
2594
+ * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.
2595
+ * @param options
2596
+ * @disableReturns
2597
+ * @returns
2598
+ * ```tsx
2599
+ * Promise<[Data | null, Error | null, HttpStatus]>
2600
+ * ```
2601
+ */
2602
+ exec = async (options) => {
2603
+ const { adapter, requestManager } = this.client;
2604
+ const request = this.clone(options);
2605
+ const requestId = this.client.unstable_requestIdMapper(this);
2606
+ const scopedAbortKey = scopeKey(this.abortKey, this.scope);
2607
+ requestManager.addAbortController(scopedAbortKey, requestId);
2608
+ const response = await adapter.fetch(request, requestId);
2609
+ requestManager.removeAbortController(scopedAbortKey, requestId);
2610
+ return mapResponseForSend(request, response);
2640
2611
  };
2641
- /** Called when the adapter fetcher is about to execute a request */
2642
- onAdapterFetch = (callback) => {
2643
- this.pluginMethods.onAdapterFetch = callback;
2644
- return this;
2612
+ /**
2613
+ * Method used to perform requests with usage of cache and queues
2614
+ * @param options
2615
+ * @param requestCallback
2616
+ * @disableReturns
2617
+ * @returns
2618
+ * ```tsx
2619
+ * Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>
2620
+ * ```
2621
+ */
2622
+ send = async (options) => {
2623
+ const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, ...configuration } = options || {};
2624
+ const request = this.clone(configuration);
2625
+ const sendRequestOptions = options === void 0 ? void 0 : {
2626
+ ...options,
2627
+ cachePolicy: void 0
2628
+ };
2629
+ if (cachePolicy === "network-only") return sendRequest(request, sendRequestOptions);
2630
+ const cached = request.read();
2631
+ if (cachePolicy === "cache-first") {
2632
+ if (cached) return mapResponseForSend(request, cached);
2633
+ return sendRequest(request, sendRequestOptions);
2634
+ }
2635
+ if (cached) {
2636
+ const resolved = await mapResponseForSend(request, cached);
2637
+ sendRequest(request, sendRequestOptions);
2638
+ return resolved;
2639
+ }
2640
+ return sendRequest(request, sendRequestOptions);
2641
+ };
2642
+ /** Reconstruct a Request instance from a previously serialized JSON representation. */
2643
+ static fromJSON = (client, json) => {
2644
+ return new Request(client, json.requestOptions, json);
2645
2645
  };
2646
2646
  };
2647
2647
  //#endregion