@techstuff-dev/foundation-api-utils 2.1.1 → 2.3.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.
@@ -45,7 +45,7 @@ var errors = process.env.NODE_ENV !== "production" ? [
45
45
  function die(error, ...args) {
46
46
  if (process.env.NODE_ENV !== "production") {
47
47
  const e = errors[error];
48
- const msg = typeof e === "function" ? e.apply(null, args) : e;
48
+ const msg = isFunction$1(e) ? e.apply(null, args) : e;
49
49
  throw new Error(`[Immer] ${msg}`);
50
50
  }
51
51
  throw new Error(
@@ -54,36 +54,49 @@ function die(error, ...args) {
54
54
  }
55
55
 
56
56
  // src/utils/common.ts
57
- var getPrototypeOf = Object.getPrototypeOf;
58
- function isDraft(value) {
59
- return !!value && !!value[DRAFT_STATE];
60
- }
57
+ var O = Object;
58
+ var getPrototypeOf = O.getPrototypeOf;
59
+ var CONSTRUCTOR = "constructor";
60
+ var PROTOTYPE = "prototype";
61
+ var CONFIGURABLE = "configurable";
62
+ var ENUMERABLE = "enumerable";
63
+ var WRITABLE = "writable";
64
+ var VALUE = "value";
65
+ var isDraft = (value) => !!value && !!value[DRAFT_STATE];
61
66
  function isDraftable(value) {
62
67
  if (!value)
63
68
  return false;
64
- return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);
69
+ return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
65
70
  }
66
- var objectCtorString = Object.prototype.constructor.toString();
71
+ var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
72
+ var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
67
73
  function isPlainObject(value) {
68
- if (!value || typeof value !== "object")
74
+ if (!value || !isObjectish(value))
69
75
  return false;
70
76
  const proto = getPrototypeOf(value);
71
- if (proto === null) {
77
+ if (proto === null || proto === O[PROTOTYPE])
72
78
  return true;
73
- }
74
- const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
79
+ const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
75
80
  if (Ctor === Object)
76
81
  return true;
77
- return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
82
+ if (!isFunction$1(Ctor))
83
+ return false;
84
+ let ctorString = cachedCtorStrings.get(Ctor);
85
+ if (ctorString === void 0) {
86
+ ctorString = Function.toString.call(Ctor);
87
+ cachedCtorStrings.set(Ctor, ctorString);
88
+ }
89
+ return ctorString === objectCtorString;
78
90
  }
79
91
  function original(value) {
80
92
  if (!isDraft(value))
81
93
  die(15, value);
82
94
  return value[DRAFT_STATE].base_;
83
95
  }
84
- function each(obj, iter) {
96
+ function each(obj, iter, strict = true) {
85
97
  if (getArchtype(obj) === 0 /* Object */) {
86
- Reflect.ownKeys(obj).forEach((key) => {
98
+ const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);
99
+ keys.forEach((key) => {
87
100
  iter(key, obj[key], obj);
88
101
  });
89
102
  } else {
@@ -92,23 +105,21 @@ function each(obj, iter) {
92
105
  }
93
106
  function getArchtype(thing) {
94
107
  const state = thing[DRAFT_STATE];
95
- return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
108
+ return state ? state.type_ : isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
96
109
  }
97
- function has(thing, prop) {
98
- return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
99
- }
100
- function get(thing, prop) {
101
- return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop];
102
- }
103
- function set(thing, propOrOldValue, value) {
104
- const t = getArchtype(thing);
105
- if (t === 2 /* Map */)
110
+ var has = (thing, prop, type = getArchtype(thing)) => type === 2 /* Map */ ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
111
+ var get = (thing, prop, type = getArchtype(thing)) => (
112
+ // @ts-ignore
113
+ type === 2 /* Map */ ? thing.get(prop) : thing[prop]
114
+ );
115
+ var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
116
+ if (type === 2 /* Map */)
106
117
  thing.set(propOrOldValue, value);
107
- else if (t === 3 /* Set */) {
118
+ else if (type === 3 /* Set */) {
108
119
  thing.add(value);
109
120
  } else
110
121
  thing[propOrOldValue] = value;
111
- }
122
+ };
112
123
  function is(x, y) {
113
124
  if (x === y) {
114
125
  return x !== 0 || 1 / x === 1 / y;
@@ -116,15 +127,23 @@ function is(x, y) {
116
127
  return x !== x && y !== y;
117
128
  }
118
129
  }
119
- function isMap(target) {
120
- return target instanceof Map;
121
- }
122
- function isSet(target) {
123
- return target instanceof Set;
124
- }
125
- function latest(state) {
126
- return state.copy_ || state.base_;
130
+ var isArray = Array.isArray;
131
+ var isMap = (target) => target instanceof Map;
132
+ var isSet = (target) => target instanceof Set;
133
+ var isObjectish = (target) => typeof target === "object";
134
+ var isFunction$1 = (target) => typeof target === "function";
135
+ var isBoolean = (target) => typeof target === "boolean";
136
+ function isArrayIndex(value) {
137
+ const n = +value;
138
+ return Number.isInteger(n) && String(n) === value;
127
139
  }
140
+ var getProxyDraft = (value) => {
141
+ if (!isObjectish(value))
142
+ return null;
143
+ return value?.[DRAFT_STATE];
144
+ };
145
+ var latest = (state) => state.copy_ || state.base_;
146
+ var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
128
147
  function shallowCopy(base, strict) {
129
148
  if (isMap(base)) {
130
149
  return new Map(base);
@@ -132,58 +151,77 @@ function shallowCopy(base, strict) {
132
151
  if (isSet(base)) {
133
152
  return new Set(base);
134
153
  }
135
- if (Array.isArray(base))
136
- return Array.prototype.slice.call(base);
154
+ if (isArray(base))
155
+ return Array[PROTOTYPE].slice.call(base);
137
156
  const isPlain = isPlainObject(base);
138
157
  if (strict === true || strict === "class_only" && !isPlain) {
139
- const descriptors = Object.getOwnPropertyDescriptors(base);
158
+ const descriptors = O.getOwnPropertyDescriptors(base);
140
159
  delete descriptors[DRAFT_STATE];
141
160
  let keys = Reflect.ownKeys(descriptors);
142
161
  for (let i = 0; i < keys.length; i++) {
143
162
  const key = keys[i];
144
163
  const desc = descriptors[key];
145
- if (desc.writable === false) {
146
- desc.writable = true;
147
- desc.configurable = true;
164
+ if (desc[WRITABLE] === false) {
165
+ desc[WRITABLE] = true;
166
+ desc[CONFIGURABLE] = true;
148
167
  }
149
168
  if (desc.get || desc.set)
150
169
  descriptors[key] = {
151
- configurable: true,
152
- writable: true,
170
+ [CONFIGURABLE]: true,
171
+ [WRITABLE]: true,
153
172
  // could live with !!desc.set as well here...
154
- enumerable: desc.enumerable,
155
- value: base[key]
173
+ [ENUMERABLE]: desc[ENUMERABLE],
174
+ [VALUE]: base[key]
156
175
  };
157
176
  }
158
- return Object.create(getPrototypeOf(base), descriptors);
177
+ return O.create(getPrototypeOf(base), descriptors);
159
178
  } else {
160
179
  const proto = getPrototypeOf(base);
161
180
  if (proto !== null && isPlain) {
162
181
  return { ...base };
163
182
  }
164
- const obj = Object.create(proto);
165
- return Object.assign(obj, base);
183
+ const obj = O.create(proto);
184
+ return O.assign(obj, base);
166
185
  }
167
186
  }
168
187
  function freeze(obj, deep = false) {
169
188
  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
170
189
  return obj;
171
190
  if (getArchtype(obj) > 1) {
172
- obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
191
+ O.defineProperties(obj, {
192
+ set: dontMutateMethodOverride,
193
+ add: dontMutateMethodOverride,
194
+ clear: dontMutateMethodOverride,
195
+ delete: dontMutateMethodOverride
196
+ });
173
197
  }
174
- Object.freeze(obj);
198
+ O.freeze(obj);
175
199
  if (deep)
176
- Object.entries(obj).forEach(([key, value]) => freeze(value, true));
200
+ each(
201
+ obj,
202
+ (_key, value) => {
203
+ freeze(value, true);
204
+ },
205
+ false
206
+ );
177
207
  return obj;
178
208
  }
179
209
  function dontMutateFrozenCollections() {
180
210
  die(2);
181
211
  }
212
+ var dontMutateMethodOverride = {
213
+ [VALUE]: dontMutateFrozenCollections
214
+ };
182
215
  function isFrozen(obj) {
183
- return Object.isFrozen(obj);
216
+ if (obj === null || !isObjectish(obj))
217
+ return true;
218
+ return O.isFrozen(obj);
184
219
  }
185
220
 
186
221
  // src/utils/plugins.ts
222
+ var PluginMapSet = "MapSet";
223
+ var PluginPatches = "Patches";
224
+ var PluginArrayMethods = "ArrayMethods";
187
225
  var plugins = {};
188
226
  function getPlugin(pluginKey) {
189
227
  const plugin = plugins[pluginKey];
@@ -192,6 +230,7 @@ function getPlugin(pluginKey) {
192
230
  }
193
231
  return plugin;
194
232
  }
233
+ var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
195
234
  function loadPlugin(pluginKey, implementation) {
196
235
  if (!plugins[pluginKey])
197
236
  plugins[pluginKey] = implementation;
@@ -199,23 +238,23 @@ function loadPlugin(pluginKey, implementation) {
199
238
 
200
239
  // src/core/scope.ts
201
240
  var currentScope;
202
- function getCurrentScope() {
203
- return currentScope;
204
- }
205
- function createScope(parent_, immer_) {
206
- return {
207
- drafts_: [],
208
- parent_,
209
- immer_,
210
- // Whenever the modified draft contains a draft from another scope, we
211
- // need to prevent auto-freezing so the unowned draft can be finalized.
212
- canAutoFreeze_: true,
213
- unfinalizedDrafts_: 0
214
- };
215
- }
241
+ var getCurrentScope = () => currentScope;
242
+ var createScope = (parent_, immer_) => ({
243
+ drafts_: [],
244
+ parent_,
245
+ immer_,
246
+ // Whenever the modified draft contains a draft from another scope, we
247
+ // need to prevent auto-freezing so the unowned draft can be finalized.
248
+ canAutoFreeze_: true,
249
+ unfinalizedDrafts_: 0,
250
+ handledSet_: /* @__PURE__ */ new Set(),
251
+ processedForPatches_: /* @__PURE__ */ new Set(),
252
+ mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
253
+ arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
254
+ });
216
255
  function usePatchesInScope(scope, patchListener) {
217
256
  if (patchListener) {
218
- getPlugin("Patches");
257
+ scope.patchPlugin_ = getPlugin(PluginPatches);
219
258
  scope.patches_ = [];
220
259
  scope.inversePatches_ = [];
221
260
  scope.patchListener_ = patchListener;
@@ -231,9 +270,7 @@ function leaveScope(scope) {
231
270
  currentScope = scope.parent_;
232
271
  }
233
272
  }
234
- function enterScope(immer2) {
235
- return currentScope = createScope(currentScope, immer2);
236
- }
273
+ var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
237
274
  function revokeDraft(draft) {
238
275
  const state = draft[DRAFT_STATE];
239
276
  if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
@@ -254,105 +291,166 @@ function processResult(result, scope) {
254
291
  }
255
292
  if (isDraftable(result)) {
256
293
  result = finalize(scope, result);
257
- if (!scope.parent_)
258
- maybeFreeze(scope, result);
259
294
  }
260
- if (scope.patches_) {
261
- getPlugin("Patches").generateReplacementPatches_(
295
+ const { patchPlugin_ } = scope;
296
+ if (patchPlugin_) {
297
+ patchPlugin_.generateReplacementPatches_(
262
298
  baseDraft[DRAFT_STATE].base_,
263
299
  result,
264
- scope.patches_,
265
- scope.inversePatches_
300
+ scope
266
301
  );
267
302
  }
268
303
  } else {
269
- result = finalize(scope, baseDraft, []);
304
+ result = finalize(scope, baseDraft);
270
305
  }
306
+ maybeFreeze(scope, result, true);
271
307
  revokeScope(scope);
272
308
  if (scope.patches_) {
273
309
  scope.patchListener_(scope.patches_, scope.inversePatches_);
274
310
  }
275
311
  return result !== NOTHING ? result : void 0;
276
312
  }
277
- function finalize(rootScope, value, path) {
313
+ function finalize(rootScope, value) {
278
314
  if (isFrozen(value))
279
315
  return value;
280
316
  const state = value[DRAFT_STATE];
281
317
  if (!state) {
282
- each(
283
- value,
284
- (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)
285
- );
286
- return value;
318
+ const finalValue = handleValue(value, rootScope.handledSet_, rootScope);
319
+ return finalValue;
287
320
  }
288
- if (state.scope_ !== rootScope)
321
+ if (!isSameScope(state, rootScope)) {
289
322
  return value;
323
+ }
290
324
  if (!state.modified_) {
291
- maybeFreeze(rootScope, state.base_, true);
292
325
  return state.base_;
293
326
  }
294
327
  if (!state.finalized_) {
295
- state.finalized_ = true;
296
- state.scope_.unfinalizedDrafts_--;
297
- const result = state.copy_;
298
- let resultEach = result;
299
- let isSet2 = false;
300
- if (state.type_ === 3 /* Set */) {
301
- resultEach = new Set(result);
302
- result.clear();
303
- isSet2 = true;
304
- }
305
- each(
306
- resultEach,
307
- (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)
308
- );
309
- maybeFreeze(rootScope, result, false);
310
- if (path && rootScope.patches_) {
311
- getPlugin("Patches").generatePatches_(
312
- state,
313
- path,
314
- rootScope.patches_,
315
- rootScope.inversePatches_
316
- );
328
+ const { callbacks_ } = state;
329
+ if (callbacks_) {
330
+ while (callbacks_.length > 0) {
331
+ const callback = callbacks_.pop();
332
+ callback(rootScope);
333
+ }
317
334
  }
335
+ generatePatchesAndFinalize(state, rootScope);
318
336
  }
319
337
  return state.copy_;
320
338
  }
321
- function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
322
- if (process.env.NODE_ENV !== "production" && childValue === targetObject)
323
- die(5);
324
- if (isDraft(childValue)) {
325
- const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.
326
- !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
327
- const res = finalize(rootScope, childValue, path);
328
- set(targetObject, prop, res);
329
- if (isDraft(res)) {
330
- rootScope.canAutoFreeze_ = false;
331
- } else
339
+ function maybeFreeze(scope, value, deep = false) {
340
+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
341
+ freeze(value, deep);
342
+ }
343
+ }
344
+ function markStateFinalized(state) {
345
+ state.finalized_ = true;
346
+ state.scope_.unfinalizedDrafts_--;
347
+ }
348
+ var isSameScope = (state, rootScope) => state.scope_ === rootScope;
349
+ var EMPTY_LOCATIONS_RESULT = [];
350
+ function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
351
+ const parentCopy = latest(parent);
352
+ const parentType = parent.type_;
353
+ if (originalKey !== void 0) {
354
+ const currentValue = get(parentCopy, originalKey, parentType);
355
+ if (currentValue === draftValue) {
356
+ set(parentCopy, originalKey, finalizedValue, parentType);
332
357
  return;
333
- } else if (targetIsSet) {
334
- targetObject.add(childValue);
358
+ }
359
+ }
360
+ if (!parent.draftLocations_) {
361
+ const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
362
+ each(parentCopy, (key, value) => {
363
+ if (isDraft(value)) {
364
+ const keys = draftLocations.get(value) || [];
365
+ keys.push(key);
366
+ draftLocations.set(value, keys);
367
+ }
368
+ });
369
+ }
370
+ const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;
371
+ for (const location of locations) {
372
+ set(parentCopy, location, finalizedValue, parentType);
335
373
  }
336
- if (isDraftable(childValue) && !isFrozen(childValue)) {
337
- if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
374
+ }
375
+ function registerChildFinalizationCallback(parent, child, key) {
376
+ parent.callbacks_.push(function childCleanup(rootScope) {
377
+ const state = child;
378
+ if (!state || !isSameScope(state, rootScope)) {
338
379
  return;
339
380
  }
340
- finalize(rootScope, childValue);
341
- if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
342
- maybeFreeze(rootScope, childValue);
381
+ rootScope.mapSetPlugin_?.fixSetContents(state);
382
+ const finalizedValue = getFinalValue(state);
383
+ updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);
384
+ generatePatchesAndFinalize(state, rootScope);
385
+ });
386
+ }
387
+ function generatePatchesAndFinalize(state, rootScope) {
388
+ const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 /* Set */ || state.type_ === 1 /* Array */ && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0);
389
+ if (shouldFinalize) {
390
+ const { patchPlugin_ } = rootScope;
391
+ if (patchPlugin_) {
392
+ const basePath = patchPlugin_.getPath(state);
393
+ if (basePath) {
394
+ patchPlugin_.generatePatches_(state, basePath, rootScope);
395
+ }
396
+ }
397
+ markStateFinalized(state);
343
398
  }
344
399
  }
345
- function maybeFreeze(scope, value, deep = false) {
346
- if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
347
- freeze(value, deep);
400
+ function handleCrossReference(target, key, value) {
401
+ const { scope_ } = target;
402
+ if (isDraft(value)) {
403
+ const state = value[DRAFT_STATE];
404
+ if (isSameScope(state, scope_)) {
405
+ state.callbacks_.push(function crossReferenceCleanup() {
406
+ prepareCopy(target);
407
+ const finalizedValue = getFinalValue(state);
408
+ updateDraftInParent(target, value, finalizedValue, key);
409
+ });
410
+ }
411
+ } else if (isDraftable(value)) {
412
+ target.callbacks_.push(function nestedDraftCleanup() {
413
+ const targetCopy = latest(target);
414
+ if (get(targetCopy, key, target.type_) === value) {
415
+ if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {
416
+ handleValue(
417
+ get(target.copy_, key, target.type_),
418
+ scope_.handledSet_,
419
+ scope_
420
+ );
421
+ }
422
+ }
423
+ });
348
424
  }
349
425
  }
426
+ function handleValue(target, handledSet, rootScope) {
427
+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
428
+ return target;
429
+ }
430
+ if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {
431
+ return target;
432
+ }
433
+ handledSet.add(target);
434
+ each(target, (key, value) => {
435
+ if (isDraft(value)) {
436
+ const state = value[DRAFT_STATE];
437
+ if (isSameScope(state, rootScope)) {
438
+ const updatedValue = getFinalValue(state);
439
+ set(target, key, updatedValue, target.type_);
440
+ markStateFinalized(state);
441
+ }
442
+ } else if (isDraftable(value)) {
443
+ handleValue(value, handledSet, rootScope);
444
+ }
445
+ });
446
+ return target;
447
+ }
350
448
 
351
449
  // src/core/proxy.ts
352
450
  function createProxyProxy(base, parent) {
353
- const isArray = Array.isArray(base);
451
+ const baseIsArray = isArray(base);
354
452
  const state = {
355
- type_: isArray ? 1 /* Array */ : 0 /* Object */,
453
+ type_: baseIsArray ? 1 /* Array */ : 0 /* Object */,
356
454
  // Track which produce call this is associated with.
357
455
  scope_: parent ? parent.scope_ : getCurrentScope(),
358
456
  // True for both shallow and deep changes.
@@ -360,7 +458,8 @@ function createProxyProxy(base, parent) {
360
458
  // Used during finalization.
361
459
  finalized_: false,
362
460
  // Track which properties have been assigned (true) or deleted (false).
363
- assigned_: {},
461
+ // actually instantiated in `prepareCopy()`
462
+ assigned_: void 0,
364
463
  // The parent draft state.
365
464
  parent_: parent,
366
465
  // The base state.
@@ -372,34 +471,50 @@ function createProxyProxy(base, parent) {
372
471
  copy_: null,
373
472
  // Called by the `produce` function.
374
473
  revoke_: null,
375
- isManual_: false
474
+ isManual_: false,
475
+ // `callbacks` actually gets assigned in `createProxy`
476
+ callbacks_: void 0
376
477
  };
377
478
  let target = state;
378
479
  let traps = objectTraps;
379
- if (isArray) {
480
+ if (baseIsArray) {
380
481
  target = [state];
381
482
  traps = arrayTraps;
382
483
  }
383
484
  const { revoke, proxy } = Proxy.revocable(target, traps);
384
485
  state.draft_ = proxy;
385
486
  state.revoke_ = revoke;
386
- return proxy;
487
+ return [proxy, state];
387
488
  }
388
489
  var objectTraps = {
389
490
  get(state, prop) {
390
491
  if (prop === DRAFT_STATE)
391
492
  return state;
493
+ let arrayPlugin = state.scope_.arrayMethodsPlugin_;
494
+ const isArrayWithStringProp = state.type_ === 1 /* Array */ && typeof prop === "string";
495
+ if (isArrayWithStringProp) {
496
+ if (arrayPlugin?.isArrayOperationMethod(prop)) {
497
+ return arrayPlugin.createMethodInterceptor(state, prop);
498
+ }
499
+ }
392
500
  const source = latest(state);
393
- if (!has(source, prop)) {
501
+ if (!has(source, prop, state.type_)) {
394
502
  return readPropFromProto(state, source, prop);
395
503
  }
396
504
  const value = source[prop];
397
505
  if (state.finalized_ || !isDraftable(value)) {
398
506
  return value;
399
507
  }
508
+ if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(
509
+ state.operationMethod
510
+ ) && isArrayIndex(prop)) {
511
+ return value;
512
+ }
400
513
  if (value === peek(state.base_, prop)) {
401
514
  prepareCopy(state);
402
- return state.copy_[prop] = createProxy(value, state);
515
+ const childKey = state.type_ === 1 /* Array */ ? +prop : prop;
516
+ const childDraft = createProxy(state.scope_, value, state, childKey);
517
+ return state.copy_[childKey] = childDraft;
403
518
  }
404
519
  return value;
405
520
  },
@@ -420,10 +535,10 @@ var objectTraps = {
420
535
  const currentState = current2?.[DRAFT_STATE];
421
536
  if (currentState && currentState.base_ === value) {
422
537
  state.copy_[prop] = value;
423
- state.assigned_[prop] = false;
538
+ state.assigned_.set(prop, false);
424
539
  return true;
425
540
  }
426
- if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
541
+ if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))
427
542
  return true;
428
543
  prepareCopy(state);
429
544
  markChanged(state);
@@ -433,16 +548,17 @@ var objectTraps = {
433
548
  Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
434
549
  return true;
435
550
  state.copy_[prop] = value;
436
- state.assigned_[prop] = true;
551
+ state.assigned_.set(prop, true);
552
+ handleCrossReference(state, prop, value);
437
553
  return true;
438
554
  },
439
555
  deleteProperty(state, prop) {
556
+ prepareCopy(state);
440
557
  if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
441
- state.assigned_[prop] = false;
442
- prepareCopy(state);
558
+ state.assigned_.set(prop, false);
443
559
  markChanged(state);
444
560
  } else {
445
- delete state.assigned_[prop];
561
+ state.assigned_.delete(prop);
446
562
  }
447
563
  if (state.copy_) {
448
564
  delete state.copy_[prop];
@@ -457,10 +573,10 @@ var objectTraps = {
457
573
  if (!desc)
458
574
  return desc;
459
575
  return {
460
- writable: true,
461
- configurable: state.type_ !== 1 /* Array */ || prop !== "length",
462
- enumerable: desc.enumerable,
463
- value: owner[prop]
576
+ [WRITABLE]: true,
577
+ [CONFIGURABLE]: state.type_ !== 1 /* Array */ || prop !== "length",
578
+ [ENUMERABLE]: desc[ENUMERABLE],
579
+ [VALUE]: owner[prop]
464
580
  };
465
581
  },
466
582
  defineProperty() {
@@ -476,8 +592,9 @@ var objectTraps = {
476
592
  var arrayTraps = {};
477
593
  each(objectTraps, (key, fn) => {
478
594
  arrayTraps[key] = function() {
479
- arguments[0] = arguments[0][0];
480
- return fn.apply(this, arguments);
595
+ const args = arguments;
596
+ args[0] = args[0][0];
597
+ return fn.apply(this, args);
481
598
  };
482
599
  });
483
600
  arrayTraps.deleteProperty = function(state, prop) {
@@ -497,7 +614,7 @@ function peek(draft, prop) {
497
614
  }
498
615
  function readPropFromProto(state, source, prop) {
499
616
  const desc = getDescriptorFromProto(source, prop);
500
- return desc ? `value` in desc ? desc.value : (
617
+ return desc ? VALUE in desc ? desc[VALUE] : (
501
618
  // This is a very special case, if the prop is a getter defined by the
502
619
  // prototype, we should invoke it with the draft as context!
503
620
  desc.get?.call(state.draft_)
@@ -525,6 +642,7 @@ function markChanged(state) {
525
642
  }
526
643
  function prepareCopy(state) {
527
644
  if (!state.copy_) {
645
+ state.assigned_ = /* @__PURE__ */ new Map();
528
646
  state.copy_ = shallowCopy(
529
647
  state.base_,
530
648
  state.scope_.immer_.useStrictShallowCopy_
@@ -537,6 +655,7 @@ var Immer2 = class {
537
655
  constructor(config) {
538
656
  this.autoFreeze_ = true;
539
657
  this.useStrictShallowCopy_ = false;
658
+ this.useStrictIteration_ = false;
540
659
  /**
541
660
  * The `produce` function takes a value and a "recipe function" (whose
542
661
  * return value often depends on the base state). The recipe function is
@@ -557,7 +676,7 @@ var Immer2 = class {
557
676
  * @returns {any} a new state, or the initial state if nothing was modified
558
677
  */
559
678
  this.produce = (base, recipe, patchListener) => {
560
- if (typeof base === "function" && typeof recipe !== "function") {
679
+ if (isFunction$1(base) && !isFunction$1(recipe)) {
561
680
  const defaultBase = recipe;
562
681
  recipe = base;
563
682
  const self = this;
@@ -565,14 +684,14 @@ var Immer2 = class {
565
684
  return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
566
685
  };
567
686
  }
568
- if (typeof recipe !== "function")
687
+ if (!isFunction$1(recipe))
569
688
  die(6);
570
- if (patchListener !== void 0 && typeof patchListener !== "function")
689
+ if (patchListener !== void 0 && !isFunction$1(patchListener))
571
690
  die(7);
572
691
  let result;
573
692
  if (isDraftable(base)) {
574
693
  const scope = enterScope(this);
575
- const proxy = createProxy(base, void 0);
694
+ const proxy = createProxy(scope, base, void 0);
576
695
  let hasError = true;
577
696
  try {
578
697
  result = recipe(proxy);
@@ -585,7 +704,7 @@ var Immer2 = class {
585
704
  }
586
705
  usePatchesInScope(scope, patchListener);
587
706
  return processResult(result, scope);
588
- } else if (!base || typeof base !== "object") {
707
+ } else if (!base || !isObjectish(base)) {
589
708
  result = recipe(base);
590
709
  if (result === void 0)
591
710
  result = base;
@@ -596,7 +715,10 @@ var Immer2 = class {
596
715
  if (patchListener) {
597
716
  const p = [];
598
717
  const ip = [];
599
- getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
718
+ getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
719
+ patches_: p,
720
+ inversePatches_: ip
721
+ });
600
722
  patchListener(p, ip);
601
723
  }
602
724
  return result;
@@ -604,7 +726,7 @@ var Immer2 = class {
604
726
  die(1, base);
605
727
  };
606
728
  this.produceWithPatches = (base, recipe) => {
607
- if (typeof base === "function") {
729
+ if (isFunction$1(base)) {
608
730
  return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
609
731
  }
610
732
  let patches, inversePatches;
@@ -614,10 +736,12 @@ var Immer2 = class {
614
736
  });
615
737
  return [result, patches, inversePatches];
616
738
  };
617
- if (typeof config?.autoFreeze === "boolean")
739
+ if (isBoolean(config?.autoFreeze))
618
740
  this.setAutoFreeze(config.autoFreeze);
619
- if (typeof config?.useStrictShallowCopy === "boolean")
741
+ if (isBoolean(config?.useStrictShallowCopy))
620
742
  this.setUseStrictShallowCopy(config.useStrictShallowCopy);
743
+ if (isBoolean(config?.useStrictIteration))
744
+ this.setUseStrictIteration(config.useStrictIteration);
621
745
  }
622
746
  createDraft(base) {
623
747
  if (!isDraftable(base))
@@ -625,7 +749,7 @@ var Immer2 = class {
625
749
  if (isDraft(base))
626
750
  base = current(base);
627
751
  const scope = enterScope(this);
628
- const proxy = createProxy(base, void 0);
752
+ const proxy = createProxy(scope, base, void 0);
629
753
  proxy[DRAFT_STATE].isManual_ = true;
630
754
  leaveScope(scope);
631
755
  return proxy;
@@ -654,6 +778,18 @@ var Immer2 = class {
654
778
  setUseStrictShallowCopy(value) {
655
779
  this.useStrictShallowCopy_ = value;
656
780
  }
781
+ /**
782
+ * Pass false to use faster iteration that skips non-enumerable properties
783
+ * but still handles symbols for compatibility.
784
+ *
785
+ * By default, strict iteration is enabled (includes all own properties).
786
+ */
787
+ setUseStrictIteration(value) {
788
+ this.useStrictIteration_ = value;
789
+ }
790
+ shouldUseStrictIteration() {
791
+ return this.useStrictIteration_;
792
+ }
657
793
  applyPatches(base, patches) {
658
794
  let i;
659
795
  for (i = patches.length - 1; i >= 0; i--) {
@@ -666,7 +802,7 @@ var Immer2 = class {
666
802
  if (i > -1) {
667
803
  patches = patches.slice(i + 1);
668
804
  }
669
- const applyPatchesImpl = getPlugin("Patches").applyPatches_;
805
+ const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
670
806
  if (isDraft(base)) {
671
807
  return applyPatchesImpl(base, patches);
672
808
  }
@@ -676,10 +812,23 @@ var Immer2 = class {
676
812
  );
677
813
  }
678
814
  };
679
- function createProxy(value, parent) {
680
- const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
681
- const scope = parent ? parent.scope_ : getCurrentScope();
815
+ function createProxy(rootScope, value, parent, key) {
816
+ const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
817
+ const scope = parent?.scope_ ?? getCurrentScope();
682
818
  scope.drafts_.push(draft);
819
+ state.callbacks_ = parent?.callbacks_ ?? [];
820
+ state.key_ = key;
821
+ if (parent && key !== void 0) {
822
+ registerChildFinalizationCallback(parent, state, key);
823
+ } else {
824
+ state.callbacks_.push(function rootDraftCleanup(rootScope2) {
825
+ rootScope2.mapSetPlugin_?.fixSetContents(state);
826
+ const { patchPlugin_ } = rootScope2;
827
+ if (state.modified_ && patchPlugin_) {
828
+ patchPlugin_.generatePatches_(state, [], rootScope2);
829
+ }
830
+ });
831
+ }
683
832
  return draft;
684
833
  }
685
834
 
@@ -694,17 +843,23 @@ function currentImpl(value) {
694
843
  return value;
695
844
  const state = value[DRAFT_STATE];
696
845
  let copy;
846
+ let strict = true;
697
847
  if (state) {
698
848
  if (!state.modified_)
699
849
  return state.base_;
700
850
  state.finalized_ = true;
701
851
  copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
852
+ strict = state.scope_.immer_.shouldUseStrictIteration();
702
853
  } else {
703
854
  copy = shallowCopy(value, true);
704
855
  }
705
- each(copy, (key, childValue) => {
706
- set(copy, key, currentImpl(childValue));
707
- });
856
+ each(
857
+ copy,
858
+ (key, childValue) => {
859
+ set(copy, key, currentImpl(childValue));
860
+ },
861
+ strict
862
+ );
708
863
  if (state) {
709
864
  state.finalized_ = false;
710
865
  }
@@ -726,27 +881,86 @@ function enablePatches() {
726
881
  "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
727
882
  );
728
883
  }
884
+ function getPath(state, path = []) {
885
+ if ("key_" in state && state.key_ !== void 0) {
886
+ const parentCopy = state.parent_.copy_ ?? state.parent_.base_;
887
+ const proxyDraft = getProxyDraft(get(parentCopy, state.key_));
888
+ const valueAtKey = get(parentCopy, state.key_);
889
+ if (valueAtKey === void 0) {
890
+ return null;
891
+ }
892
+ if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) {
893
+ return null;
894
+ }
895
+ if (proxyDraft != null && proxyDraft.base_ !== state.base_) {
896
+ return null;
897
+ }
898
+ const isSet2 = state.parent_.type_ === 3 /* Set */;
899
+ let key;
900
+ if (isSet2) {
901
+ const setParent = state.parent_;
902
+ key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);
903
+ } else {
904
+ key = state.key_;
905
+ }
906
+ if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) {
907
+ return null;
908
+ }
909
+ path.push(key);
910
+ }
911
+ if (state.parent_) {
912
+ return getPath(state.parent_, path);
913
+ }
914
+ path.reverse();
915
+ try {
916
+ resolvePath(state.copy_, path);
917
+ } catch (e) {
918
+ return null;
919
+ }
920
+ return path;
921
+ }
922
+ function resolvePath(base, path) {
923
+ let current2 = base;
924
+ for (let i = 0; i < path.length - 1; i++) {
925
+ const key = path[i];
926
+ current2 = get(current2, key);
927
+ if (!isObjectish(current2) || current2 === null) {
928
+ throw new Error(`Cannot resolve path at '${path.join("/")}'`);
929
+ }
930
+ }
931
+ return current2;
932
+ }
729
933
  const REPLACE = "replace";
730
934
  const ADD = "add";
731
935
  const REMOVE = "remove";
732
- function generatePatches_(state, basePath, patches, inversePatches) {
936
+ function generatePatches_(state, basePath, scope) {
937
+ if (state.scope_.processedForPatches_.has(state)) {
938
+ return;
939
+ }
940
+ state.scope_.processedForPatches_.add(state);
941
+ const { patches_, inversePatches_ } = scope;
733
942
  switch (state.type_) {
734
943
  case 0 /* Object */:
735
944
  case 2 /* Map */:
736
945
  return generatePatchesFromAssigned(
737
946
  state,
738
947
  basePath,
739
- patches,
740
- inversePatches
948
+ patches_,
949
+ inversePatches_
741
950
  );
742
951
  case 1 /* Array */:
743
- return generateArrayPatches(state, basePath, patches, inversePatches);
952
+ return generateArrayPatches(
953
+ state,
954
+ basePath,
955
+ patches_,
956
+ inversePatches_
957
+ );
744
958
  case 3 /* Set */:
745
959
  return generateSetPatches(
746
960
  state,
747
961
  basePath,
748
- patches,
749
- inversePatches
962
+ patches_,
963
+ inversePatches_
750
964
  );
751
965
  }
752
966
  }
@@ -757,20 +971,28 @@ function enablePatches() {
757
971
  [base_, copy_] = [copy_, base_];
758
972
  [patches, inversePatches] = [inversePatches, patches];
759
973
  }
974
+ const allReassigned = state.allIndicesReassigned_ === true;
760
975
  for (let i = 0; i < base_.length; i++) {
761
- if (assigned_[i] && copy_[i] !== base_[i]) {
976
+ const copiedItem = copy_[i];
977
+ const baseItem = base_[i];
978
+ const isAssigned = allReassigned || assigned_?.get(i.toString());
979
+ if (isAssigned && copiedItem !== baseItem) {
980
+ const childState = copiedItem?.[DRAFT_STATE];
981
+ if (childState && childState.modified_) {
982
+ continue;
983
+ }
762
984
  const path = basePath.concat([i]);
763
985
  patches.push({
764
986
  op: REPLACE,
765
987
  path,
766
988
  // Need to maybe clone it, as it can in fact be the original value
767
989
  // due to the base/copy inversion at the start of this function
768
- value: clonePatchValueIfNeeded(copy_[i])
990
+ value: clonePatchValueIfNeeded(copiedItem)
769
991
  });
770
992
  inversePatches.push({
771
993
  op: REPLACE,
772
994
  path,
773
- value: clonePatchValueIfNeeded(base_[i])
995
+ value: clonePatchValueIfNeeded(baseItem)
774
996
  });
775
997
  }
776
998
  }
@@ -793,15 +1015,17 @@ function enablePatches() {
793
1015
  }
794
1016
  }
795
1017
  function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
796
- const { base_, copy_ } = state;
1018
+ const { base_, copy_, type_ } = state;
797
1019
  each(state.assigned_, (key, assignedValue) => {
798
- const origValue = get(base_, key);
799
- const value = get(copy_, key);
1020
+ const origValue = get(base_, key, type_);
1021
+ const value = get(copy_, key, type_);
800
1022
  const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
801
1023
  if (origValue === value && op === REPLACE)
802
1024
  return;
803
1025
  const path = basePath.concat(key);
804
- patches.push(op === REMOVE ? { op, path } : { op, path, value });
1026
+ patches.push(
1027
+ op === REMOVE ? { op, path } : { op, path, value: clonePatchValueIfNeeded(value) }
1028
+ );
805
1029
  inversePatches.push(
806
1030
  op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }
807
1031
  );
@@ -844,13 +1068,14 @@ function enablePatches() {
844
1068
  i++;
845
1069
  });
846
1070
  }
847
- function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {
848
- patches.push({
1071
+ function generateReplacementPatches_(baseValue, replacement, scope) {
1072
+ const { patches_, inversePatches_ } = scope;
1073
+ patches_.push({
849
1074
  op: REPLACE,
850
1075
  path: [],
851
1076
  value: replacement === NOTHING ? void 0 : replacement
852
1077
  });
853
- inversePatches.push({
1078
+ inversePatches_.push({
854
1079
  op: REPLACE,
855
1080
  path: [],
856
1081
  value: baseValue
@@ -866,12 +1091,12 @@ function enablePatches() {
866
1091
  if (typeof p !== "string" && typeof p !== "number") {
867
1092
  p = "" + p;
868
1093
  }
869
- if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === "constructor"))
1094
+ if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === CONSTRUCTOR))
870
1095
  die(errorOffset + 3);
871
- if (typeof base === "function" && p === "prototype")
1096
+ if (isFunction$1(base) && p === PROTOTYPE)
872
1097
  die(errorOffset + 3);
873
1098
  base = get(base, p);
874
- if (typeof base !== "object")
1099
+ if (!isObjectish(base))
875
1100
  die(errorOffset + 2, path.join("/"));
876
1101
  }
877
1102
  const type = getArchtype(base);
@@ -918,7 +1143,7 @@ function enablePatches() {
918
1143
  function deepClonePatchValue(obj) {
919
1144
  if (!isDraftable(obj))
920
1145
  return obj;
921
- if (Array.isArray(obj))
1146
+ if (isArray(obj))
922
1147
  return obj.map(deepClonePatchValue);
923
1148
  if (isMap(obj))
924
1149
  return new Map(
@@ -939,24 +1164,21 @@ function enablePatches() {
939
1164
  } else
940
1165
  return obj;
941
1166
  }
942
- loadPlugin("Patches", {
1167
+ loadPlugin(PluginPatches, {
943
1168
  applyPatches_,
944
1169
  generatePatches_,
945
- generateReplacementPatches_
1170
+ generateReplacementPatches_,
1171
+ getPath
946
1172
  });
947
1173
  }
948
1174
 
949
1175
  // src/immer.ts
950
1176
  var immer = new Immer2();
951
1177
  immer.produce;
952
- var produceWithPatches = immer.produceWithPatches.bind(
1178
+ var produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(
953
1179
  immer
954
1180
  );
955
- immer.setAutoFreeze.bind(immer);
956
- immer.setUseStrictShallowCopy.bind(immer);
957
- var applyPatches = immer.applyPatches.bind(immer);
958
- immer.createDraft.bind(immer);
959
- immer.finishDraft.bind(immer);
1181
+ var applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);
960
1182
 
961
1183
  // src/getDotPath/getDotPath.ts
962
1184
 
@@ -1299,20 +1521,24 @@ var createStructuredSelector = Object.assign(
1299
1521
  );
1300
1522
 
1301
1523
  // src/query/core/apiState.ts
1302
- var QueryStatus = /* @__PURE__ */ ((QueryStatus2) => {
1303
- QueryStatus2["uninitialized"] = "uninitialized";
1304
- QueryStatus2["pending"] = "pending";
1305
- QueryStatus2["fulfilled"] = "fulfilled";
1306
- QueryStatus2["rejected"] = "rejected";
1307
- return QueryStatus2;
1524
+ var QueryStatus = /* @__PURE__ */ ((QueryStatus7) => {
1525
+ QueryStatus7["uninitialized"] = "uninitialized";
1526
+ QueryStatus7["pending"] = "pending";
1527
+ QueryStatus7["fulfilled"] = "fulfilled";
1528
+ QueryStatus7["rejected"] = "rejected";
1529
+ return QueryStatus7;
1308
1530
  })(QueryStatus || {});
1531
+ var STATUS_UNINITIALIZED = "uninitialized" /* uninitialized */;
1532
+ var STATUS_PENDING = "pending" /* pending */;
1533
+ var STATUS_FULFILLED = "fulfilled" /* fulfilled */;
1534
+ var STATUS_REJECTED = "rejected" /* rejected */;
1309
1535
  function getRequestStatusFlags(status) {
1310
1536
  return {
1311
1537
  status,
1312
- isUninitialized: status === "uninitialized" /* uninitialized */,
1313
- isLoading: status === "pending" /* pending */,
1314
- isSuccess: status === "fulfilled" /* fulfilled */,
1315
- isError: status === "rejected" /* rejected */
1538
+ isUninitialized: status === STATUS_UNINITIALIZED,
1539
+ isLoading: status === STATUS_PENDING,
1540
+ isSuccess: status === STATUS_FULFILLED,
1541
+ isError: status === STATUS_REJECTED
1316
1542
  };
1317
1543
  }
1318
1544
 
@@ -1333,8 +1559,15 @@ function copyWithStructuralSharing(oldObj, newObj) {
1333
1559
  return isSameObject ? oldObj : mergeObj;
1334
1560
  }
1335
1561
 
1336
- // src/query/utils/flatten.ts
1337
- var flatten = (arr) => [].concat(...arr);
1562
+ // src/query/utils/filterMap.ts
1563
+ function filterMap(array, predicate, mapper) {
1564
+ return array.reduce((acc, item, i) => {
1565
+ if (predicate(item, i)) {
1566
+ acc.push(mapper(item, i));
1567
+ }
1568
+ return acc;
1569
+ }, []).flat();
1570
+ }
1338
1571
 
1339
1572
  // src/query/utils/isAbsoluteUrl.ts
1340
1573
  function isAbsoluteUrl(url) {
@@ -1388,6 +1621,33 @@ function getOrInsertComputed(map, key, compute) {
1388
1621
  }
1389
1622
  var createNewMap = () => /* @__PURE__ */ new Map();
1390
1623
 
1624
+ // src/query/utils/signals.ts
1625
+ var timeoutSignal = (milliseconds) => {
1626
+ const abortController = new AbortController();
1627
+ setTimeout(() => {
1628
+ const message = "signal timed out";
1629
+ const name = "TimeoutError";
1630
+ abortController.abort(
1631
+ // some environments (React Native, Node) don't have DOMException
1632
+ typeof DOMException !== "undefined" ? new DOMException(message, name) : Object.assign(new Error(message), {
1633
+ name
1634
+ })
1635
+ );
1636
+ }, milliseconds);
1637
+ return abortController.signal;
1638
+ };
1639
+ var anySignal = (...signals) => {
1640
+ for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);
1641
+ const abortController = new AbortController();
1642
+ for (const signal of signals) {
1643
+ signal.addEventListener("abort", () => abortController.abort(signal.reason), {
1644
+ signal: abortController.signal,
1645
+ once: true
1646
+ });
1647
+ }
1648
+ return abortController.signal;
1649
+ };
1650
+
1391
1651
  // src/query/fetchBaseQuery.ts
1392
1652
  var defaultFetchFn = (...args) => fetch(...args);
1393
1653
  var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
@@ -1444,15 +1704,9 @@ function fetchBaseQuery({
1444
1704
  } = typeof arg == "string" ? {
1445
1705
  url: arg
1446
1706
  } : arg;
1447
- let abortController, signal = api.signal;
1448
- if (timeout) {
1449
- abortController = new AbortController();
1450
- api.signal.addEventListener("abort", abortController.abort);
1451
- signal = abortController.signal;
1452
- }
1453
1707
  let config = {
1454
1708
  ...baseFetchOptions,
1455
- signal,
1709
+ signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,
1456
1710
  ...rest
1457
1711
  };
1458
1712
  headers = new Headers(stripUndefined(headers));
@@ -1493,23 +1747,17 @@ function fetchBaseQuery({
1493
1747
  meta = {
1494
1748
  request: requestClone
1495
1749
  };
1496
- let response, timedOut = false, timeoutId = abortController && setTimeout(() => {
1497
- timedOut = true;
1498
- abortController.abort();
1499
- }, timeout);
1750
+ let response;
1500
1751
  try {
1501
1752
  response = await fetchFn(request);
1502
1753
  } catch (e) {
1503
1754
  return {
1504
1755
  error: {
1505
- status: timedOut ? "TIMEOUT_ERROR" : "FETCH_ERROR",
1756
+ status: (e instanceof Error || typeof DOMException !== "undefined" && e instanceof DOMException) && e.name === "TimeoutError" ? "TIMEOUT_ERROR" : "FETCH_ERROR",
1506
1757
  error: String(e)
1507
1758
  },
1508
1759
  meta
1509
1760
  };
1510
- } finally {
1511
- if (timeoutId) clearTimeout(timeoutId);
1512
- abortController?.signal.removeEventListener("abort", abortController.abort);
1513
1761
  }
1514
1762
  const responseClone = response.clone();
1515
1763
  meta.response = responseClone;
@@ -1571,30 +1819,35 @@ var HandledError = class {
1571
1819
  };
1572
1820
 
1573
1821
  // src/query/core/setupListeners.ts
1574
- var onFocus = /* @__PURE__ */ createAction("__rtkq/focused");
1575
- var onFocusLost = /* @__PURE__ */ createAction("__rtkq/unfocused");
1576
- var onOnline = /* @__PURE__ */ createAction("__rtkq/online");
1577
- var onOffline = /* @__PURE__ */ createAction("__rtkq/offline");
1822
+ var INTERNAL_PREFIX = "__rtkq/";
1823
+ var ONLINE = "online";
1824
+ var OFFLINE = "offline";
1825
+ var FOCUSED = "focused";
1826
+ var onFocus = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${FOCUSED}`);
1827
+ var onFocusLost = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);
1828
+ var onOnline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${ONLINE}`);
1829
+ var onOffline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${OFFLINE}`);
1578
1830
 
1579
1831
  // src/query/endpointDefinitions.ts
1832
+ var ENDPOINT_QUERY$1 = "query" /* query */;
1833
+ var ENDPOINT_MUTATION$1 = "mutation" /* mutation */;
1834
+ var ENDPOINT_INFINITEQUERY$1 = "infinitequery" /* infinitequery */;
1580
1835
  function isQueryDefinition$1(e) {
1581
- return e.type === "query" /* query */;
1836
+ return e.type === ENDPOINT_QUERY$1;
1582
1837
  }
1583
1838
  function isMutationDefinition$1(e) {
1584
- return e.type === "mutation" /* mutation */;
1839
+ return e.type === ENDPOINT_MUTATION$1;
1585
1840
  }
1586
1841
  function isInfiniteQueryDefinition$1(e) {
1587
- return e.type === "infinitequery" /* infinitequery */;
1842
+ return e.type === ENDPOINT_INFINITEQUERY$1;
1588
1843
  }
1589
1844
  function isAnyQueryDefinition(e) {
1590
1845
  return isQueryDefinition$1(e) || isInfiniteQueryDefinition$1(e);
1591
1846
  }
1592
1847
  function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
1593
- if (isFunction(description)) {
1594
- return description(result, error, queryArg, meta).filter(isNotNullish).map(expandTagDescription).map(assertTagTypes);
1595
- }
1596
- if (Array.isArray(description)) {
1597
- return description.map(expandTagDescription).map(assertTagTypes);
1848
+ const finalDescription = isFunction(description) ? description(result, error, queryArg, meta) : description;
1849
+ if (finalDescription) {
1850
+ return filterMap(finalDescription, isNotNullish, (tag) => assertTagTypes(expandTagDescription(tag)));
1598
1851
  }
1599
1852
  return [];
1600
1853
  }
@@ -1612,6 +1865,9 @@ function asSafePromise(promise, fallback) {
1612
1865
  return promise.catch(fallback);
1613
1866
  }
1614
1867
 
1868
+ // src/query/apiTypes.ts
1869
+ var getEndpointDefinition = (context, endpointName) => context.endpointDefinitions[endpointName];
1870
+
1615
1871
  // src/query/core/buildInitiate.ts
1616
1872
  var forceQueryFnSymbol = Symbol("forceQueryFn");
1617
1873
  var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
@@ -1642,7 +1898,7 @@ function buildInitiate({
1642
1898
  };
1643
1899
  function getRunningQueryThunk(endpointName, queryArgs) {
1644
1900
  return (dispatch) => {
1645
- const endpointDefinition = context.endpointDefinitions[endpointName];
1901
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
1646
1902
  const queryCacheKey = serializeQueryArgs({
1647
1903
  queryArgs,
1648
1904
  endpointDefinition,
@@ -1689,7 +1945,7 @@ You must add the middleware for RTK-Query to function correctly!`);
1689
1945
  let thunk;
1690
1946
  const commonThunkArgs = {
1691
1947
  ...rest,
1692
- type: "query",
1948
+ type: ENDPOINT_QUERY$1,
1693
1949
  subscribe,
1694
1950
  forceRefetch,
1695
1951
  subscriptionOptions,
@@ -1703,14 +1959,16 @@ You must add the middleware for RTK-Query to function correctly!`);
1703
1959
  } else {
1704
1960
  const {
1705
1961
  direction,
1706
- initialPageParam
1962
+ initialPageParam,
1963
+ refetchCachedPages
1707
1964
  } = rest;
1708
1965
  thunk = infiniteQueryThunk({
1709
1966
  ...commonThunkArgs,
1710
1967
  // Supply these even if undefined. This helps with a field existence
1711
1968
  // check over in `buildSlice.ts`
1712
1969
  direction,
1713
- initialPageParam
1970
+ initialPageParam,
1971
+ refetchCachedPages
1714
1972
  });
1715
1973
  }
1716
1974
  const selector = api.endpoints[endpointName].select(arg);
@@ -1749,9 +2007,10 @@ You must add the middleware for RTK-Query to function correctly!`);
1749
2007
  }
1750
2008
  return result.data;
1751
2009
  },
1752
- refetch: () => dispatch(queryAction(arg, {
2010
+ refetch: (options) => dispatch(queryAction(arg, {
1753
2011
  subscribe: false,
1754
- forceRefetch: true
2012
+ forceRefetch: true,
2013
+ ...options
1755
2014
  })),
1756
2015
  unsubscribe() {
1757
2016
  if (subscribe) dispatch(unsubscribeQueryResult({
@@ -1926,7 +2185,7 @@ function buildThunks({
1926
2185
  inversePatches: [],
1927
2186
  undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))
1928
2187
  };
1929
- if (currentState.status === "uninitialized" /* uninitialized */) {
2188
+ if (currentState.status === STATUS_UNINITIALIZED) {
1930
2189
  return ret;
1931
2190
  }
1932
2191
  let newValue;
@@ -1983,6 +2242,7 @@ function buildThunks({
1983
2242
  metaSchema,
1984
2243
  skipSchemaValidation = globalSkipSchemaValidation
1985
2244
  } = endpointDefinition;
2245
+ const isQuery = arg.type === ENDPOINT_QUERY$1;
1986
2246
  try {
1987
2247
  let transformResponse = defaultTransformResponse;
1988
2248
  const baseQueryApi = {
@@ -1993,10 +2253,10 @@ function buildThunks({
1993
2253
  extra,
1994
2254
  endpoint: arg.endpointName,
1995
2255
  type: arg.type,
1996
- forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0,
1997
- queryCacheKey: arg.type === "query" ? arg.queryCacheKey : void 0
2256
+ forced: isQuery ? isForcedQuery(arg, getState()) : void 0,
2257
+ queryCacheKey: isQuery ? arg.queryCacheKey : void 0
1998
2258
  };
1999
- const forceQueryFn = arg.type === "query" ? arg[forceQueryFnSymbol] : void 0;
2259
+ const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : void 0;
2000
2260
  let finalQueryReturnValue;
2001
2261
  const fetchPage = async (data, param, maxPages, previous) => {
2002
2262
  if (param == null && data.pages.length) {
@@ -2085,13 +2345,14 @@ function buildThunks({
2085
2345
  data: transformedResponse
2086
2346
  };
2087
2347
  }
2088
- if (arg.type === "query" && "infiniteQueryOptions" in endpointDefinition) {
2348
+ if (isQuery && "infiniteQueryOptions" in endpointDefinition) {
2089
2349
  const {
2090
2350
  infiniteQueryOptions
2091
2351
  } = endpointDefinition;
2092
2352
  const {
2093
2353
  maxPages = Infinity
2094
2354
  } = infiniteQueryOptions;
2355
+ const refetchCachedPages = arg.refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;
2095
2356
  let result;
2096
2357
  const blankData = {
2097
2358
  pages: [],
@@ -2121,9 +2382,11 @@ function buildThunks({
2121
2382
  data: result.data.pages[0]
2122
2383
  };
2123
2384
  }
2124
- for (let i = 1; i < totalPages; i++) {
2125
- const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
2126
- result = await fetchPage(result.data, param, maxPages);
2385
+ if (refetchCachedPages) {
2386
+ for (let i = 1; i < totalPages; i++) {
2387
+ const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
2388
+ result = await fetchPage(result.data, param, maxPages);
2389
+ }
2127
2390
  }
2128
2391
  }
2129
2392
  finalQueryReturnValue = result;
@@ -2173,7 +2436,7 @@ function buildThunks({
2173
2436
  endpoint: arg.endpointName,
2174
2437
  arg: arg.originalArgs,
2175
2438
  type: arg.type,
2176
- queryCacheKey: arg.type === "query" ? arg.queryCacheKey : void 0
2439
+ queryCacheKey: isQuery ? arg.queryCacheKey : void 0
2177
2440
  };
2178
2441
  endpointDefinition.onSchemaFailure?.(caughtError, info);
2179
2442
  onSchemaFailure?.(caughtError, info);
@@ -2332,6 +2595,13 @@ function getPreviousPageParam(options, {
2332
2595
  function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
2333
2596
  return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
2334
2597
  }
2598
+
2599
+ // src/query/utils/getCurrent.ts
2600
+ function getCurrent(value) {
2601
+ return isDraft(value) ? current(value) : value;
2602
+ }
2603
+
2604
+ // src/query/core/buildSlice.ts
2335
2605
  function updateQuerySubstateIfExists(state, queryCacheKey, update) {
2336
2606
  const substate = state[queryCacheKey];
2337
2607
  if (substate) {
@@ -2365,11 +2635,11 @@ function buildSlice({
2365
2635
  const resetApiState = createAction(`${reducerPath}/resetApiState`);
2366
2636
  function writePendingCacheEntry(draft, arg, upserting, meta) {
2367
2637
  draft[arg.queryCacheKey] ??= {
2368
- status: "uninitialized" /* uninitialized */,
2638
+ status: STATUS_UNINITIALIZED,
2369
2639
  endpointName: arg.endpointName
2370
2640
  };
2371
2641
  updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
2372
- substate.status = "pending" /* pending */;
2642
+ substate.status = STATUS_PENDING;
2373
2643
  substate.requestId = upserting && substate.requestId ? (
2374
2644
  // for `upsertQuery` **updates**, keep the current `requestId`
2375
2645
  substate.requestId
@@ -2393,7 +2663,7 @@ function buildSlice({
2393
2663
  const {
2394
2664
  merge
2395
2665
  } = definitions[meta.arg.endpointName];
2396
- substate.status = "fulfilled" /* fulfilled */;
2666
+ substate.status = STATUS_FULFILLED;
2397
2667
  if (merge) {
2398
2668
  if (substate.data !== void 0) {
2399
2669
  const {
@@ -2470,7 +2740,7 @@ function buildSlice({
2470
2740
  } = entry;
2471
2741
  const endpointDefinition = definitions[endpointName];
2472
2742
  const queryDescription = {
2473
- type: "query",
2743
+ type: ENDPOINT_QUERY$1,
2474
2744
  endpointName,
2475
2745
  originalArgs: entry.arg,
2476
2746
  queryCacheKey: serializeQueryArgs({
@@ -2536,7 +2806,7 @@ function buildSlice({
2536
2806
  updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
2537
2807
  if (condition) ; else {
2538
2808
  if (substate.requestId !== requestId) return;
2539
- substate.status = "rejected" /* rejected */;
2809
+ substate.status = STATUS_REJECTED;
2540
2810
  substate.error = payload ?? error;
2541
2811
  }
2542
2812
  });
@@ -2547,7 +2817,7 @@ function buildSlice({
2547
2817
  for (const [key, entry] of Object.entries(queries)) {
2548
2818
  if (
2549
2819
  // do not rehydrate entries that were currently in flight.
2550
- entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */
2820
+ entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED
2551
2821
  ) {
2552
2822
  draft[key] = entry;
2553
2823
  }
@@ -2583,7 +2853,7 @@ function buildSlice({
2583
2853
  if (!arg.track) return;
2584
2854
  draft[getMutationCacheKey(meta)] = {
2585
2855
  requestId,
2586
- status: "pending" /* pending */,
2856
+ status: STATUS_PENDING,
2587
2857
  endpointName: arg.endpointName,
2588
2858
  startedTimeStamp
2589
2859
  };
@@ -2594,7 +2864,7 @@ function buildSlice({
2594
2864
  if (!meta.arg.track) return;
2595
2865
  updateMutationSubstateIfExists(draft, meta, (substate) => {
2596
2866
  if (substate.requestId !== meta.requestId) return;
2597
- substate.status = "fulfilled" /* fulfilled */;
2867
+ substate.status = STATUS_FULFILLED;
2598
2868
  substate.data = payload;
2599
2869
  substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
2600
2870
  });
@@ -2606,7 +2876,7 @@ function buildSlice({
2606
2876
  if (!meta.arg.track) return;
2607
2877
  updateMutationSubstateIfExists(draft, meta, (substate) => {
2608
2878
  if (substate.requestId !== meta.requestId) return;
2609
- substate.status = "rejected" /* rejected */;
2879
+ substate.status = STATUS_REJECTED;
2610
2880
  substate.error = payload ?? error;
2611
2881
  });
2612
2882
  }).addMatcher(hasRehydrationInfo, (draft, action) => {
@@ -2616,7 +2886,7 @@ function buildSlice({
2616
2886
  for (const [key, entry] of Object.entries(mutations)) {
2617
2887
  if (
2618
2888
  // do not rehydrate entries that were currently in flight.
2619
- (entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
2889
+ (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
2620
2890
  key !== entry?.requestId
2621
2891
  ) {
2622
2892
  draft[key] = entry;
@@ -2701,19 +2971,19 @@ function buildSlice({
2701
2971
  }
2702
2972
  });
2703
2973
  function removeCacheKeyFromTags(draft, queryCacheKey) {
2704
- const existingTags = draft.keys[queryCacheKey] ?? [];
2974
+ const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);
2705
2975
  for (const tag of existingTags) {
2706
2976
  const tagType = tag.type;
2707
2977
  const tagId = tag.id ?? "__internal_without_id";
2708
2978
  const tagSubscriptions = draft.tags[tagType]?.[tagId];
2709
2979
  if (tagSubscriptions) {
2710
- draft.tags[tagType][tagId] = tagSubscriptions.filter((qc) => qc !== queryCacheKey);
2980
+ draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter((qc) => qc !== queryCacheKey);
2711
2981
  }
2712
2982
  }
2713
2983
  delete draft.keys[queryCacheKey];
2714
2984
  }
2715
- function writeProvidedTagsForQueries(draft, actions2) {
2716
- const providedByEntries = actions2.map((action) => {
2985
+ function writeProvidedTagsForQueries(draft, actions3) {
2986
+ const providedByEntries = actions3.map((action) => {
2717
2987
  const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
2718
2988
  const {
2719
2989
  queryCacheKey
@@ -2786,7 +3056,7 @@ function buildSlice({
2786
3056
  config: configSlice.reducer
2787
3057
  });
2788
3058
  const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
2789
- const actions = {
3059
+ const actions2 = {
2790
3060
  ...configSlice.actions,
2791
3061
  ...querySlice.actions,
2792
3062
  ...subscriptionSlice.actions,
@@ -2797,14 +3067,14 @@ function buildSlice({
2797
3067
  };
2798
3068
  return {
2799
3069
  reducer,
2800
- actions
3070
+ actions: actions2
2801
3071
  };
2802
3072
  }
2803
3073
 
2804
3074
  // src/query/core/buildSelectors.ts
2805
3075
  var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
2806
3076
  var initialSubState = {
2807
- status: "uninitialized" /* uninitialized */
3077
+ status: STATUS_UNINITIALIZED
2808
3078
  };
2809
3079
  var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, () => {
2810
3080
  });
@@ -2919,7 +3189,8 @@ function buildSelectors({
2919
3189
  function selectInvalidatedBy(state, tags) {
2920
3190
  const apiState = state[reducerPath];
2921
3191
  const toInvalidate = /* @__PURE__ */ new Set();
2922
- for (const tag of tags.filter(isNotNullish).map(expandTagDescription)) {
3192
+ const finalTags = filterMap(tags, isNotNullish, expandTagDescription);
3193
+ for (const tag of finalTags) {
2923
3194
  const provided = apiState.provided.tags[tag.type];
2924
3195
  if (!provided) {
2925
3196
  continue;
@@ -2929,23 +3200,23 @@ function buildSelectors({
2929
3200
  provided[tag.id]
2930
3201
  ) : (
2931
3202
  // no id: invalidate all queries that provide this type
2932
- flatten(Object.values(provided))
3203
+ Object.values(provided).flat()
2933
3204
  )) ?? [];
2934
3205
  for (const invalidate of invalidateSubscriptions) {
2935
3206
  toInvalidate.add(invalidate);
2936
3207
  }
2937
3208
  }
2938
- return flatten(Array.from(toInvalidate.values()).map((queryCacheKey) => {
3209
+ return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {
2939
3210
  const querySubState = apiState.queries[queryCacheKey];
2940
- return querySubState ? [{
3211
+ return querySubState ? {
2941
3212
  queryCacheKey,
2942
3213
  endpointName: querySubState.endpointName,
2943
3214
  originalArgs: querySubState.originalArgs
2944
- }] : [];
2945
- }));
3215
+ } : [];
3216
+ });
2946
3217
  }
2947
3218
  function selectCachedArgsForQuery(state, queryName) {
2948
- return Object.values(selectQueries(state)).filter((entry) => entry?.endpointName === queryName && entry.status !== "uninitialized" /* uninitialized */).map((entry) => entry.originalArgs);
3219
+ return filterMap(Object.values(selectQueries(state)), (entry) => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, (entry) => entry.originalArgs);
2949
3220
  }
2950
3221
  function getHasNextPage(options, data, queryArg) {
2951
3222
  if (!data) return false;
@@ -3046,9 +3317,9 @@ function buildCreateApi(...modules) {
3046
3317
  if (endpoints) {
3047
3318
  for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
3048
3319
  if (typeof partialDefinition === "function") {
3049
- partialDefinition(context.endpointDefinitions[endpointName]);
3320
+ partialDefinition(getEndpointDefinition(context, endpointName));
3050
3321
  } else {
3051
- Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
3322
+ Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);
3052
3323
  }
3053
3324
  }
3054
3325
  }
@@ -3060,15 +3331,15 @@ function buildCreateApi(...modules) {
3060
3331
  const evaluatedEndpoints = inject.endpoints({
3061
3332
  query: (x) => ({
3062
3333
  ...x,
3063
- type: "query" /* query */
3334
+ type: ENDPOINT_QUERY$1
3064
3335
  }),
3065
3336
  mutation: (x) => ({
3066
3337
  ...x,
3067
- type: "mutation" /* mutation */
3338
+ type: ENDPOINT_MUTATION$1
3068
3339
  }),
3069
3340
  infiniteQuery: (x) => ({
3070
3341
  ...x,
3071
- type: "infinitequery" /* infinitequery */
3342
+ type: ENDPOINT_INFINITEQUERY$1
3072
3343
  })
3073
3344
  });
3074
3345
  for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
@@ -3114,6 +3385,8 @@ function buildCreateApi(...modules) {
3114
3385
  function safeAssign$1(target, ...args) {
3115
3386
  return Object.assign(target, ...args);
3116
3387
  }
3388
+
3389
+ // src/query/core/buildMiddleware/batchActions.ts
3117
3390
  var buildBatchedActionsHandler = ({
3118
3391
  api,
3119
3392
  queryThunk,
@@ -3314,7 +3587,7 @@ var buildCacheCollectionHandler = ({
3314
3587
  }
3315
3588
  }
3316
3589
  function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
3317
- const endpointDefinition = context.endpointDefinitions[endpointName];
3590
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
3318
3591
  const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
3319
3592
  if (keepUnusedDataFor === Infinity) {
3320
3593
  return;
@@ -3361,6 +3634,11 @@ var buildCacheLifecycleHandler = ({
3361
3634
  const isMutationThunk = isAsyncThunkAction(mutationThunk);
3362
3635
  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);
3363
3636
  const lifecycleMap = {};
3637
+ const {
3638
+ removeQueryResult,
3639
+ removeMutationResult,
3640
+ cacheEntriesUpserted
3641
+ } = api.internalActions;
3364
3642
  function resolveLifecycleEntry(cacheKey, data, meta) {
3365
3643
  const lifecycle = lifecycleMap[cacheKey];
3366
3644
  if (lifecycle?.valueResolved) {
@@ -3378,6 +3656,17 @@ var buildCacheLifecycleHandler = ({
3378
3656
  lifecycle.cacheEntryRemoved();
3379
3657
  }
3380
3658
  }
3659
+ function getActionMetaFields(action) {
3660
+ const {
3661
+ arg,
3662
+ requestId
3663
+ } = action.meta;
3664
+ const {
3665
+ endpointName,
3666
+ originalArgs
3667
+ } = arg;
3668
+ return [endpointName, originalArgs, requestId];
3669
+ }
3381
3670
  const handler = (action, mwApi, stateBefore) => {
3382
3671
  const cacheKey = getCacheKey(action);
3383
3672
  function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
@@ -3388,8 +3677,9 @@ var buildCacheLifecycleHandler = ({
3388
3677
  }
3389
3678
  }
3390
3679
  if (queryThunk.pending.match(action)) {
3391
- checkForNewCacheKey(action.meta.arg.endpointName, cacheKey, action.meta.requestId, action.meta.arg.originalArgs);
3392
- } else if (api.internalActions.cacheEntriesUpserted.match(action)) {
3680
+ const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
3681
+ checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);
3682
+ } else if (cacheEntriesUpserted.match(action)) {
3393
3683
  for (const {
3394
3684
  queryDescription,
3395
3685
  value
@@ -3405,11 +3695,12 @@ var buildCacheLifecycleHandler = ({
3405
3695
  } else if (mutationThunk.pending.match(action)) {
3406
3696
  const state = mwApi.getState()[reducerPath].mutations[cacheKey];
3407
3697
  if (state) {
3408
- handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
3698
+ const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
3699
+ handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);
3409
3700
  }
3410
3701
  } else if (isFulfilledThunk(action)) {
3411
3702
  resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);
3412
- } else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {
3703
+ } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {
3413
3704
  removeLifecycleEntry(cacheKey);
3414
3705
  } else if (api.util.resetApiState.match(action)) {
3415
3706
  for (const cacheKey2 of Object.keys(lifecycleMap)) {
@@ -3422,12 +3713,12 @@ var buildCacheLifecycleHandler = ({
3422
3713
  if (isMutationThunk(action)) {
3423
3714
  return action.meta.arg.fixedCacheKey ?? action.meta.requestId;
3424
3715
  }
3425
- if (api.internalActions.removeQueryResult.match(action)) return action.payload.queryCacheKey;
3426
- if (api.internalActions.removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
3716
+ if (removeQueryResult.match(action)) return action.payload.queryCacheKey;
3717
+ if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
3427
3718
  return "";
3428
3719
  }
3429
3720
  function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
3430
- const endpointDefinition = context.endpointDefinitions[endpointName];
3721
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
3431
3722
  const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
3432
3723
  if (!onCacheEntryAdded) return;
3433
3724
  const lifecycle = {};
@@ -3502,9 +3793,16 @@ var buildInvalidationByTagsHandler = ({
3502
3793
  removeQueryResult
3503
3794
  } = api.internalActions;
3504
3795
  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));
3505
- const isQueryEnd = isAnyOf(isFulfilled(mutationThunk, queryThunk), isRejected(mutationThunk, queryThunk));
3796
+ const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));
3506
3797
  let pendingTagInvalidations = [];
3798
+ let pendingRequestCount = 0;
3507
3799
  const handler = (action, mwApi) => {
3800
+ if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {
3801
+ pendingRequestCount++;
3802
+ }
3803
+ if (isQueryEnd(action)) {
3804
+ pendingRequestCount = Math.max(0, pendingRequestCount - 1);
3805
+ }
3508
3806
  if (isThunkActionWithTags(action)) {
3509
3807
  invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
3510
3808
  } else if (isQueryEnd(action)) {
@@ -3513,23 +3811,14 @@ var buildInvalidationByTagsHandler = ({
3513
3811
  invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
3514
3812
  }
3515
3813
  };
3516
- function hasPendingRequests(state) {
3517
- const {
3518
- queries,
3519
- mutations
3520
- } = state;
3521
- for (const cacheRecord of [queries, mutations]) {
3522
- for (const key in cacheRecord) {
3523
- if (cacheRecord[key]?.status === "pending" /* pending */) return true;
3524
- }
3525
- }
3526
- return false;
3814
+ function hasPendingRequests() {
3815
+ return pendingRequestCount > 0;
3527
3816
  }
3528
3817
  function invalidateTags(newTags, mwApi) {
3529
3818
  const rootState = mwApi.getState();
3530
3819
  const state = rootState[reducerPath];
3531
3820
  pendingTagInvalidations.push(...newTags);
3532
- if (state.config.invalidationBehavior === "delayed" && hasPendingRequests(state)) {
3821
+ if (state.config.invalidationBehavior === "delayed" && hasPendingRequests()) {
3533
3822
  return;
3534
3823
  }
3535
3824
  const tags = pendingTagInvalidations;
@@ -3548,7 +3837,7 @@ var buildInvalidationByTagsHandler = ({
3548
3837
  mwApi.dispatch(removeQueryResult({
3549
3838
  queryCacheKey
3550
3839
  }));
3551
- } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
3840
+ } else if (querySubState.status !== STATUS_UNINITIALIZED) {
3552
3841
  mwApi.dispatch(refetchQuery(querySubState));
3553
3842
  }
3554
3843
  }
@@ -3611,7 +3900,7 @@ var buildPollingHandler = ({
3611
3900
  const state = api2.getState()[reducerPath];
3612
3901
  const querySubState = state.queries[queryCacheKey];
3613
3902
  const subscriptions = currentSubscriptions.get(queryCacheKey);
3614
- if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) return;
3903
+ if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;
3615
3904
  const {
3616
3905
  lowestPollingInterval,
3617
3906
  skipPollingIfUnfocused
@@ -3642,7 +3931,7 @@ var buildPollingHandler = ({
3642
3931
  const state = api2.getState()[reducerPath];
3643
3932
  const querySubState = state.queries[queryCacheKey];
3644
3933
  const subscriptions = currentSubscriptions.get(queryCacheKey);
3645
- if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) {
3934
+ if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
3646
3935
  return;
3647
3936
  }
3648
3937
  const {
@@ -3714,7 +4003,7 @@ var buildQueryLifecycleHandler = ({
3714
4003
  originalArgs
3715
4004
  }
3716
4005
  } = action.meta;
3717
- const endpointDefinition = context.endpointDefinitions[endpointName];
4006
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
3718
4007
  const onQueryStarted = endpointDefinition?.onQueryStarted;
3719
4008
  if (onQueryStarted) {
3720
4009
  const lifecycle = {};
@@ -3799,7 +4088,7 @@ var buildWindowEventHandler = ({
3799
4088
  api2.dispatch(removeQueryResult({
3800
4089
  queryCacheKey
3801
4090
  }));
3802
- } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
4091
+ } else if (querySubState.status !== STATUS_UNINITIALIZED) {
3803
4092
  api2.dispatch(refetchQuery(querySubState));
3804
4093
  }
3805
4094
  }
@@ -3821,7 +4110,7 @@ function buildMiddleware(input) {
3821
4110
  const {
3822
4111
  apiUid
3823
4112
  } = context;
3824
- const actions = {
4113
+ const actions2 = {
3825
4114
  invalidateTags: createAction(`${reducerPath}/invalidateTags`)
3826
4115
  };
3827
4116
  const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
@@ -3874,7 +4163,7 @@ function buildMiddleware(input) {
3874
4163
  };
3875
4164
  return {
3876
4165
  middleware,
3877
- actions
4166
+ actions: actions2
3878
4167
  };
3879
4168
  function refetchQuery(querySubState) {
3880
4169
  return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
@@ -4076,7 +4365,7 @@ var coreModule = ({
4076
4365
  // src/query/core/index.ts
4077
4366
  /* @__PURE__ */ buildCreateApi(coreModule());
4078
4367
 
4079
- // src/query/react/index.ts
4368
+ // src/query/react/rtkqImports.ts
4080
4369
 
4081
4370
  // src/query/utils/capitalize.ts
4082
4371
  function capitalize(str) {
@@ -4093,14 +4382,17 @@ function countObjectKeys(obj) {
4093
4382
  }
4094
4383
 
4095
4384
  // src/query/endpointDefinitions.ts
4385
+ var ENDPOINT_QUERY = "query" /* query */;
4386
+ var ENDPOINT_MUTATION = "mutation" /* mutation */;
4387
+ var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
4096
4388
  function isQueryDefinition(e) {
4097
- return e.type === "query" /* query */;
4389
+ return e.type === ENDPOINT_QUERY;
4098
4390
  }
4099
4391
  function isMutationDefinition(e) {
4100
- return e.type === "mutation" /* mutation */;
4392
+ return e.type === ENDPOINT_MUTATION;
4101
4393
  }
4102
4394
  function isInfiniteQueryDefinition(e) {
4103
- return e.type === "infinitequery" /* infinitequery */;
4395
+ return e.type === ENDPOINT_INFINITEQUERY;
4104
4396
  }
4105
4397
 
4106
4398
  // src/query/tsHelpers.ts
@@ -4110,6 +4402,8 @@ function safeAssign(target, ...args) {
4110
4402
 
4111
4403
  // src/query/react/constants.ts
4112
4404
  var UNINITIALIZED_VALUE = Symbol();
4405
+
4406
+ // src/query/react/useSerializedStableValue.ts
4113
4407
  function useStableQueryArgs(queryArgs) {
4114
4408
  const cache = useRef(queryArgs);
4115
4409
  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);
@@ -4120,6 +4414,8 @@ function useStableQueryArgs(queryArgs) {
4120
4414
  }, [copy]);
4121
4415
  return copy;
4122
4416
  }
4417
+
4418
+ // src/query/react/useShallowStableValue.ts
4123
4419
  function useShallowStableValue(value) {
4124
4420
  const cache = useRef(value);
4125
4421
  useEffect(() => {
@@ -4144,6 +4440,8 @@ var noPendingQueryStateSelector = (selected) => {
4144
4440
  isUninitialized: false,
4145
4441
  isFetching: true,
4146
4442
  isLoading: selected.data !== void 0 ? false : true,
4443
+ // This is the one place where we still have to use `QueryStatus` as an enum,
4444
+ // since it's the only reference in the React package and not in the core.
4147
4445
  status: QueryStatus.pending
4148
4446
  };
4149
4447
  }
@@ -4173,6 +4471,8 @@ function buildHooks({
4173
4471
  context
4174
4472
  }) {
4175
4473
  const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect;
4474
+ const unsubscribePromiseRef = (ref) => ref.current?.unsubscribe?.();
4475
+ const endpointDefinitions = context.endpointDefinitions;
4176
4476
  return {
4177
4477
  buildQueryHooks,
4178
4478
  buildInfiniteQueryHooks,
@@ -4184,7 +4484,7 @@ function buildHooks({
4184
4484
  const {
4185
4485
  endpointName
4186
4486
  } = lastResult;
4187
- const endpointDefinition = context.endpointDefinitions[endpointName];
4487
+ const endpointDefinition = endpointDefinitions[endpointName];
4188
4488
  if (queryArgs !== skipToken && serializeQueryArgs({
4189
4489
  queryArgs: lastResult.originalArgs,
4190
4490
  endpointDefinition,
@@ -4215,7 +4515,7 @@ function buildHooks({
4215
4515
  const {
4216
4516
  endpointName
4217
4517
  } = lastResult;
4218
- const endpointDefinition = context.endpointDefinitions[endpointName];
4518
+ const endpointDefinition = endpointDefinitions[endpointName];
4219
4519
  if (queryArgs !== skipToken && serializeQueryArgs({
4220
4520
  queryArgs: lastResult.originalArgs,
4221
4521
  endpointDefinition,
@@ -4282,6 +4582,8 @@ function buildHooks({
4282
4582
  });
4283
4583
  const initialPageParam = rest.initialPageParam;
4284
4584
  const stableInitialPageParam = useShallowStableValue(initialPageParam);
4585
+ const refetchCachedPages = rest.refetchCachedPages;
4586
+ const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);
4285
4587
  const promiseRef = useRef(void 0);
4286
4588
  let {
4287
4589
  queryCacheKey,
@@ -4313,15 +4615,16 @@ function buildHooks({
4313
4615
  const promise = dispatch(initiate(stableArg, {
4314
4616
  subscriptionOptions: stableSubscriptionOptions,
4315
4617
  forceRefetch: refetchOnMountOrArgChange,
4316
- ...isInfiniteQueryDefinition(context.endpointDefinitions[endpointName]) ? {
4317
- initialPageParam: stableInitialPageParam
4618
+ ...isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {
4619
+ initialPageParam: stableInitialPageParam,
4620
+ refetchCachedPages: stableRefetchCachedPages
4318
4621
  } : {}
4319
4622
  }));
4320
4623
  promiseRef.current = promise;
4321
4624
  } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
4322
4625
  lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
4323
4626
  }
4324
- }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, endpointName]);
4627
+ }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);
4325
4628
  return [promiseRef, dispatch, initiate, stableSubscriptionOptions];
4326
4629
  }
4327
4630
  function buildUseQueryState(endpointName, preSelector) {
@@ -4368,7 +4671,7 @@ function buildHooks({
4368
4671
  function usePromiseRefUnsubscribeOnUnmount(promiseRef) {
4369
4672
  useEffect(() => {
4370
4673
  return () => {
4371
- promiseRef.current?.unsubscribe?.();
4674
+ unsubscribePromiseRef(promiseRef);
4372
4675
  promiseRef.current = void 0;
4373
4676
  };
4374
4677
  }, [promiseRef]);
@@ -4419,7 +4722,7 @@ function buildHooks({
4419
4722
  const trigger = useCallback(function(arg2, preferCacheValue = false) {
4420
4723
  let promise;
4421
4724
  batch(() => {
4422
- promiseRef.current?.unsubscribe();
4725
+ unsubscribePromiseRef(promiseRef);
4423
4726
  promiseRef.current = promise = dispatch(initiate(arg2, {
4424
4727
  subscriptionOptions: subscriptionOptionsRef.current,
4425
4728
  forceRefetch: !preferCacheValue
@@ -4437,7 +4740,7 @@ function buildHooks({
4437
4740
  }, [dispatch]);
4438
4741
  useEffect(() => {
4439
4742
  return () => {
4440
- promiseRef?.current?.unsubscribe();
4743
+ unsubscribePromiseRef(promiseRef);
4441
4744
  };
4442
4745
  }, []);
4443
4746
  useEffect(() => {
@@ -4492,10 +4795,12 @@ function buildHooks({
4492
4795
  usePossiblyImmediateEffect(() => {
4493
4796
  subscriptionOptionsRef.current = stableSubscriptionOptions;
4494
4797
  }, [stableSubscriptionOptions]);
4798
+ const hookRefetchCachedPages = options.refetchCachedPages;
4799
+ const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);
4495
4800
  const trigger = useCallback(function(arg2, direction) {
4496
4801
  let promise;
4497
4802
  batch(() => {
4498
- promiseRef.current?.unsubscribe();
4803
+ unsubscribePromiseRef(promiseRef);
4499
4804
  promiseRef.current = promise = dispatch(initiate(arg2, {
4500
4805
  subscriptionOptions: subscriptionOptionsRef.current,
4501
4806
  direction
@@ -4505,7 +4810,13 @@ function buildHooks({
4505
4810
  }, [promiseRef, dispatch, initiate]);
4506
4811
  usePromiseRefUnsubscribeOnUnmount(promiseRef);
4507
4812
  const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);
4508
- const refetch = useCallback(() => refetchOrErrorIfUnmounted(promiseRef), [promiseRef]);
4813
+ const refetch = useCallback((options2) => {
4814
+ if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(38) : "Cannot refetch a query that has not been started yet.");
4815
+ const mergedOptions = {
4816
+ refetchCachedPages: options2?.refetchCachedPages ?? stableHookRefetchCachedPages
4817
+ };
4818
+ return promiseRef.current.refetch(mergedOptions);
4819
+ }, [promiseRef, stableHookRefetchCachedPages]);
4509
4820
  return useMemo(() => {
4510
4821
  const fetchNextPage = () => {
4511
4822
  return trigger(stableArg, "forward");
@@ -5932,7 +6243,7 @@ const contentApi = createApi({
5932
6243
  const { useGetDataQuery, useLazyGetDataQuery, useGetDataByIdQuery, useLazyGetDataByIdQuery, } = contentApi;
5933
6244
 
5934
6245
  // Dynamic baseQuery that resolves URL at request time and unwraps standard responses
5935
- const dynamicBaseQuery = async (args, api, extraOptions) => {
6246
+ const dynamicBaseQuery$1 = async (args, api, extraOptions) => {
5936
6247
  // Resolve base URL at request time, not module load time
5937
6248
  const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_PAYMENTS_PREFIX
5938
6249
  ? process.env.NEXT_PUBLIC_API_PAYMENTS_PREFIX
@@ -5958,7 +6269,7 @@ const dynamicBaseQuery = async (args, api, extraOptions) => {
5958
6269
  };
5959
6270
  const paymentApi = createApi({
5960
6271
  reducerPath: 'paymentApi',
5961
- baseQuery: dynamicBaseQuery,
6272
+ baseQuery: dynamicBaseQuery$1,
5962
6273
  tagTypes: ['UserSubscription', 'Plans', 'TaxRates', 'PromoCodes'],
5963
6274
  // keepUnusedDataFor: 300,
5964
6275
  endpoints: (builder) => ({
@@ -6000,6 +6311,73 @@ const paymentApi = createApi({
6000
6311
  // Export hooks for usage in functional components.
6001
6312
  const { useCheckUserSubscriptionQuery, useLazyCheckUserSubscriptionQuery, useGetPaymentPlansQuery, useLazyGetPaymentPlansQuery, useGetTaxRatesQuery, useLazyGetTaxRatesQuery, useCheckPromoCodeQuery, useLazyCheckPromoCodeQuery, } = paymentApi;
6002
6313
 
6314
+ // Dynamic baseQuery that resolves URL at request time and unwraps standard responses
6315
+ const dynamicBaseQuery = async (args, api, extraOptions) => {
6316
+ // Resolve base URL at request time, not module load time
6317
+ const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_PAYMENTS_PREFIX
6318
+ ? process.env.NEXT_PUBLIC_API_PAYMENTS_PREFIX
6319
+ : (API_PAYMENTS_PREFIX || '');
6320
+ const baseQuery = createUnwrappingBaseQuery({
6321
+ baseUrl,
6322
+ prepareHeaders: async (headers) => {
6323
+ headers.set('Content-Type', 'application/json');
6324
+ // Try to add accessToken to headers, but don't fail if unavailable
6325
+ try {
6326
+ const session = await Auth.currentSession();
6327
+ const idToken = session.getIdToken().getJwtToken(); // ID token
6328
+ const accessToken = session.getAccessToken().getJwtToken(); // Access token
6329
+ if (accessToken && idToken) {
6330
+ headers.set('accesstoken', accessToken);
6331
+ headers.set('idtoken', idToken);
6332
+ }
6333
+ }
6334
+ catch (error) {
6335
+ // Authentication not available - this is OK for public endpoints like getProducts
6336
+ console.log('Auth not available for products API request');
6337
+ }
6338
+ return headers;
6339
+ },
6340
+ credentials: 'include',
6341
+ });
6342
+ return baseQuery(args, api, extraOptions);
6343
+ };
6344
+ const productsApi = createApi({
6345
+ reducerPath: 'productsApi',
6346
+ baseQuery: dynamicBaseQuery,
6347
+ tagTypes: ['Products', 'Product'],
6348
+ endpoints: (builder) => ({
6349
+ /**
6350
+ * Get all products
6351
+ * Optional partnerId parameter for filtering
6352
+ */
6353
+ getProducts: builder.query({
6354
+ query: (params) => {
6355
+ const queryString = params?.partnerId ? `?partnerId=${params.partnerId}` : '';
6356
+ return `/payment/products${queryString}`;
6357
+ },
6358
+ providesTags: (result) => result
6359
+ ? [
6360
+ ...result.products.map(({ id }) => ({ type: 'Product', id })),
6361
+ { type: 'Products', id: 'LIST' },
6362
+ ]
6363
+ : [{ type: 'Products', id: 'LIST' }],
6364
+ }),
6365
+ /**
6366
+ * Purchase a product
6367
+ */
6368
+ purchaseProduct: builder.mutation({
6369
+ query: (body) => ({
6370
+ url: '/payment/product-purchase',
6371
+ method: 'POST',
6372
+ body,
6373
+ }),
6374
+ invalidatesTags: [{ type: 'Products', id: 'LIST' }],
6375
+ }),
6376
+ }),
6377
+ });
6378
+ // Export hooks for usage in functional components
6379
+ const { useGetProductsQuery, useLazyGetProductsQuery, usePurchaseProductMutation, } = productsApi;
6380
+
6003
6381
  // Create dynamic baseQuery that resolves URL at request time
6004
6382
  const createOrdersBaseQuery = () => {
6005
6383
  const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_ORDERS_PREFIX
@@ -6057,7 +6435,7 @@ const ordersApi = createApi({
6057
6435
  // keepUnusedDataFor: 300,
6058
6436
  endpoints: (builder) => ({
6059
6437
  /**
6060
- * USER API.
6438
+ * Legacy order search endpoint.
6061
6439
  */
6062
6440
  fetchOrders: builder.query({
6063
6441
  query: (ids) => ({
@@ -6068,10 +6446,27 @@ const ordersApi = createApi({
6068
6446
  },
6069
6447
  }),
6070
6448
  }),
6449
+ /**
6450
+ * Get all partnership orders for a customer from Stripe.
6451
+ */
6452
+ getOrders: builder.query({
6453
+ query: ({ customerId }) => ({
6454
+ url: `${process.env.NEXT_PUBLIC_PAYMENTS_URL}/v1/payment/orders`,
6455
+ params: { customerId },
6456
+ }),
6457
+ providesTags: ['Orders'],
6458
+ }),
6459
+ /**
6460
+ * Get a single partnership order by ID from Stripe.
6461
+ */
6462
+ getOrder: builder.query({
6463
+ query: (orderId) => `${process.env.NEXT_PUBLIC_PAYMENTS_URL}/v1/payment/orders/${orderId}`,
6464
+ providesTags: (_result, _error, orderId) => [{ type: 'Orders', id: orderId }],
6465
+ }),
6071
6466
  }),
6072
6467
  });
6073
6468
  // Export hooks for usage in functional components.
6074
- const { useFetchOrdersQuery, useLazyFetchOrdersQuery } = ordersApi;
6469
+ const { useFetchOrdersQuery, useLazyFetchOrdersQuery, useGetOrdersQuery, useGetOrderQuery, } = ordersApi;
6075
6470
 
6076
6471
  const initialState = {
6077
6472
  addedItems: [],
@@ -6225,5 +6620,5 @@ const selectCartItemsIds = createSelector$1([selectMediaInCart], (items) => {
6225
6620
  });
6226
6621
  cartSlice.reducer;
6227
6622
 
6228
- export { formatAuthSession as $, emptyCart as A, toggleCart as B, selectMediaInCart as C, selectCartTotal as D, selectCartNetTotal as E, selectCartTaxRate as F, selectCartTaxAmount as G, selectCartCount as H, selectCartStatus as I, selectPromoCode as J, selectCartItems as K, selectCartItemsIds as L, formatUserPayload as M, formatPromos as N, formatWorkout as O, formatShortform as P, formatFaqs as Q, formatPages as R, formatSettings as S, formatPress as T, formatGuests as U, formatVideos as V, formatSections as W, formatSchedule as X, formatChallenges as Y, formatChallengeDays as Z, formatSecondsToISO8601Duration as _, authApi as a, formatFedaratedSession as a0, formatSocialAuthSession as a1, formatConfig as a2, formatSectionPanels as a3, formatSectionItems as a4, formatTaxonomies as a5, formatSeries as a6, formatSeasons as a7, formatLongform as a8, formatMediaItem as a9, isWeb as aa, isReactNative as ab, getPlatform as ac, runOnPlatform as ad, onlyUnique as ae, applyCoupon as af, applyTax as ag, toCamelCaseObject as ah, createUnwrappingBaseQuery as ai, useResetPasswordAuthMutation as b, contentApi as c, useRegisterMutation as d, useVerifyUserQuery as e, useLazyVerifyUserQuery as f, useGetUserInfoQuery as g, useLazyGetUserInfoQuery as h, useUpdateUserInfoMutation as i, useForgottenPasswordMutation as j, useVerifyUserAttributesQuery as k, useLazyVerifyUserAttributesQuery as l, useVerifyUserResendQuery as m, useLazyVerifyUserResendQuery as n, ordersApi as o, paymentApi as p, useUpdateUserMutation as q, cartSlice as r, setTaxRate as s, resetTaxRate as t, useResetPasswordMutation as u, setPromoCode as v, removePromoCode as w, addToCart as x, updateCart as y, removeFromCart as z };
6229
- //# sourceMappingURL=slice-DpwJIX84.js.map
6623
+ export { formatPress as $, cartSlice as A, setTaxRate as B, resetTaxRate as C, setPromoCode as D, removePromoCode as E, addToCart as F, updateCart as G, removeFromCart as H, emptyCart as I, toggleCart as J, selectMediaInCart as K, selectCartTotal as L, selectCartNetTotal as M, selectCartTaxRate as N, selectCartTaxAmount as O, selectCartCount as P, selectCartStatus as Q, selectPromoCode as R, selectCartItems as S, selectCartItemsIds as T, formatUserPayload as U, formatPromos as V, formatWorkout as W, formatShortform as X, formatFaqs as Y, formatPages as Z, formatSettings as _, authApi as a, formatGuests as a0, formatVideos as a1, formatSections as a2, formatSchedule as a3, formatChallenges as a4, formatChallengeDays as a5, formatSecondsToISO8601Duration as a6, formatAuthSession as a7, formatFedaratedSession as a8, formatSocialAuthSession as a9, formatConfig as aa, formatSectionPanels as ab, formatSectionItems as ac, formatTaxonomies as ad, formatSeries as ae, formatSeasons as af, formatLongform as ag, formatMediaItem as ah, isWeb as ai, isReactNative as aj, getPlatform as ak, runOnPlatform as al, onlyUnique as am, applyCoupon as an, applyTax as ao, toCamelCaseObject as ap, createUnwrappingBaseQuery as aq, productsApi as b, contentApi as c, useResetPasswordAuthMutation as d, useRegisterMutation as e, useVerifyUserQuery as f, useLazyVerifyUserQuery as g, useGetUserInfoQuery as h, useLazyGetUserInfoQuery as i, useUpdateUserInfoMutation as j, useForgottenPasswordMutation as k, useVerifyUserAttributesQuery as l, useLazyVerifyUserAttributesQuery as m, useVerifyUserResendQuery as n, ordersApi as o, paymentApi as p, useLazyVerifyUserResendQuery as q, useUpdateUserMutation as r, useGetProductsQuery as s, useLazyGetProductsQuery as t, useResetPasswordMutation as u, usePurchaseProductMutation as v, useFetchOrdersQuery as w, useLazyFetchOrdersQuery as x, useGetOrdersQuery as y, useGetOrderQuery as z };
6624
+ //# sourceMappingURL=slice-BD3oWPrI.js.map