@jsb188/graphql 1.1.11 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +205 -0
  3. package/cache/config.ts +65 -28
  4. package/cache/index.helpers.ts +96 -0
  5. package/cache/index.ts +364 -808
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/optimistic-ui-runtime.ts +46 -0
  8. package/cache/optimistic-ui.ts +401 -0
  9. package/cache/persist.ts +107 -22
  10. package/cache/realtime-fence.ts +47 -0
  11. package/cache/realtime-live.ts +17 -0
  12. package/cache/store.ts +22 -64
  13. package/cache/value.helpers.ts +17 -0
  14. package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
  15. package/{drafts/index.ts → client/draft-persistence.ts} +13 -39
  16. package/client/index.ts +4 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +122 -232
  19. package/client/storage-asset.ts +58 -0
  20. package/gql/fragments/accountAuthFragments.ts +0 -4
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +156 -0
  23. package/gql/fragments/aiChatFragments.ts +35 -11
  24. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  25. package/gql/fragments/audienceFragments.ts +76 -0
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +49 -21
  28. package/gql/fragments/emailOutreachFragments.ts +281 -0
  29. package/gql/fragments/fieldDocFragments.ts +222 -40
  30. package/gql/fragments/inboundContactFragments.ts +2 -0
  31. package/gql/fragments/libraryFragments.ts +120 -0
  32. package/gql/fragments/logFragments.ts +93 -2
  33. package/gql/fragments/organizationFragments.ts +12 -0
  34. package/gql/fragments/qrCodeFragments.ts +29 -0
  35. package/gql/fragments/scheduleFragments.ts +574 -145
  36. package/gql/fragments/sheetFragments.ts +86 -424
  37. package/gql/fragments/storageFragments.ts +25 -1
  38. package/gql/fragments/workWaitFragments.ts +13 -0
  39. package/gql/fragments/workflowFragments.ts +32 -4
  40. package/gql/mutations/agentMemoryMutations.ts +32 -0
  41. package/gql/mutations/agentNoteMutations.ts +64 -0
  42. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  43. package/gql/mutations/aiChatMutations.ts +34 -4
  44. package/gql/mutations/audienceMutations.ts +58 -0
  45. package/gql/mutations/authMutations.ts +24 -28
  46. package/gql/mutations/billingMutations.ts +24 -0
  47. package/gql/mutations/contactMutations.ts +23 -0
  48. package/gql/mutations/dataTableMutations.ts +18 -75
  49. package/gql/mutations/emailMutations.ts +22 -0
  50. package/gql/mutations/emailOutreachMutations.ts +139 -0
  51. package/gql/mutations/fieldDocMutations.ts +162 -13
  52. package/gql/mutations/index.ts +10 -5
  53. package/gql/mutations/organizationMutations.ts +6 -0
  54. package/gql/mutations/qrCodeMutations.ts +20 -0
  55. package/gql/mutations/scheduleMutations.ts +389 -417
  56. package/gql/mutations/sheetMutations.ts +62 -118
  57. package/gql/mutations/storageMutations.ts +1 -1
  58. package/gql/mutations/workflowMutations.ts +94 -0
  59. package/gql/queries/agentMemoryQueries.ts +12 -2
  60. package/gql/queries/agentNoteQueries.ts +86 -0
  61. package/gql/queries/aiChatQueries.ts +63 -12
  62. package/gql/queries/audienceQueries.ts +104 -0
  63. package/gql/queries/authQueries.ts +20 -4
  64. package/gql/queries/billingQueries.ts +114 -9
  65. package/gql/queries/dataTableQueries.ts +43 -75
  66. package/gql/queries/emailOutreachQueries.ts +282 -0
  67. package/gql/queries/emailQueries.ts +48 -64
  68. package/gql/queries/emailReplyReportQueries.ts +127 -0
  69. package/gql/queries/fieldDocQueries.ts +128 -98
  70. package/gql/queries/inboundContactQueries.ts +15 -4
  71. package/gql/queries/index.ts +5 -3
  72. package/gql/queries/libraryQueries.ts +112 -0
  73. package/gql/queries/logQueries.ts +86 -12
  74. package/gql/queries/organizationQueries.ts +44 -12
  75. package/gql/queries/qrCodeQueries.ts +27 -0
  76. package/gql/queries/scheduleQueries.ts +401 -278
  77. package/gql/queries/sheetQueries.ts +94 -165
  78. package/gql/queries/storageQueries.ts +11 -4
  79. package/gql/queries/workflowQueries.ts +61 -12
  80. package/gql/reactivity.ts +98 -0
  81. package/gql/recordReads.ts +171 -0
  82. package/hooks/index.helpers.ts +52 -0
  83. package/hooks/index.ts +920 -715
  84. package/hooks/use-agentMemory-mtn.ts +29 -31
  85. package/hooks/use-agentMemory-qry.ts +15 -3
  86. package/hooks/use-agentNote-mtn.ts +89 -0
  87. package/hooks/use-agentNote-qry.ts +162 -0
  88. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  89. package/hooks/use-agentNote-recovery.ts +57 -0
  90. package/hooks/use-aiChat-mtn.ts +104 -115
  91. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  92. package/hooks/use-aiChat-qry.ts +254 -387
  93. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  94. package/hooks/use-audience-mtn.ts +170 -0
  95. package/hooks/use-audience-qry.helpers.ts +39 -0
  96. package/hooks/use-audience-qry.ts +245 -0
  97. package/hooks/use-auth-mtn.ts +30 -1
  98. package/hooks/use-billing-mtn.ts +31 -0
  99. package/hooks/use-billing-qry.ts +76 -0
  100. package/hooks/use-dataTable-mtn.ts +23 -115
  101. package/hooks/use-dataTable-qry.ts +69 -914
  102. package/hooks/use-email-mtn.ts +26 -0
  103. package/hooks/use-email-qry.helpers.ts +37 -0
  104. package/hooks/use-email-qry.ts +44 -174
  105. package/hooks/use-emailOutreach-mtn.ts +211 -0
  106. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  107. package/hooks/use-emailOutreach-qry.ts +367 -0
  108. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  109. package/hooks/use-fieldDoc-mtn.ts +244 -32
  110. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  111. package/hooks/use-fieldDoc-qry.ts +134 -102
  112. package/hooks/use-inboundContact-qry.ts +7 -9
  113. package/hooks/use-library-qry.ts +233 -0
  114. package/hooks/use-log-mtn.ts +25 -12
  115. package/hooks/use-log-qry.ts +99 -46
  116. package/hooks/use-organization-qry.ts +16 -60
  117. package/hooks/use-qrCode-mtn.ts +40 -0
  118. package/hooks/use-qrCode-qry.ts +78 -0
  119. package/hooks/use-schedule-mtn.ts +231 -348
  120. package/hooks/use-schedule-qry.ts +208 -139
  121. package/hooks/use-schedule-reactive.ts +218 -0
  122. package/hooks/use-sheet-mtn.ts +91 -199
  123. package/hooks/use-sheet-qry.ts +88 -237
  124. package/hooks/use-storage-qry.ts +84 -61
  125. package/hooks/use-workflow-mtn.ts +84 -23
  126. package/hooks/use-workflow-qry.ts +60 -61
  127. package/libs/ai-chat-link-events.ts +78 -0
  128. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  129. package/libs/ai-chat-outgoing.ts +11 -0
  130. package/libs/ai-chat-outgoing.types.ts +25 -0
  131. package/libs/ai-chat-run-realtime.ts +20 -0
  132. package/libs/ai-chat-submission-realtime.ts +150 -0
  133. package/libs/data-changes.helpers.ts +161 -0
  134. package/libs/data-changes.ts +382 -0
  135. package/libs/fragment-realtime-sequence.ts +55 -0
  136. package/libs/open-sheet.ts +138 -0
  137. package/libs/record-read.ts +327 -0
  138. package/libs/sheet-command-batch.ts +45 -0
  139. package/libs/sheet-realtime-packet.ts +53 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/emailPreference.ts +69 -0
  142. package/loaders/rest.ts +12 -0
  143. package/package.json +77 -25
  144. package/schedule.d.ts +1183 -0
  145. package/sse.helpers.ts +19 -0
  146. package/sse.ts +26 -115
  147. package/types.d.ts +48 -25
  148. package/cache/index.test.ts +0 -881
  149. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  150. package/client/data-table-realtime-subscriptions.ts +0 -955
  151. package/client/data-table-realtime.test.ts +0 -792
  152. package/client/data-table-realtime.ts +0 -1218
  153. package/client/fragment-realtime-sequence.ts +0 -52
  154. package/client/open-sheet.ts +0 -137
  155. package/client/request-managed-session.test.ts +0 -574
  156. package/client/request-no-store.test.ts +0 -157
  157. package/client/sse-ticket.test.ts +0 -26
  158. package/deno.lock +0 -170
  159. package/deno.test.json +0 -10
  160. package/gql/fragments/agentDocFragments.ts +0 -46
  161. package/gql/fragments/billingFragments.ts +0 -14
  162. package/gql/fragments/campaignFragments.ts +0 -277
  163. package/gql/mutations/agentDocMutations.ts +0 -177
  164. package/gql/mutations/campaignMutations.ts +0 -215
  165. package/gql/queries/agentDocQueries.ts +0 -120
  166. package/gql/queries/appQueries.ts +0 -14
  167. package/gql/queries/campaignQueries.ts +0 -127
  168. package/hooks/use-agentDoc-mtn.ts +0 -285
  169. package/hooks/use-agentDoc-qry.ts +0 -208
  170. package/hooks/use-app-qry.ts +0 -22
  171. package/hooks/use-campaign-mtn.ts +0 -377
  172. package/hooks/use-campaign-qry.ts +0 -257
  173. package/loaders/campaign.ts +0 -137
  174. package/tsconfig.json +0 -13
package/hooks/index.ts CHANGED
@@ -1,43 +1,25 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
- import type {
3
- ServerErrorObj,
4
- SimpleErrorType,
5
- } from '@jsb188/app/types/app.d.ts';
6
- import {
7
- getAuthToken,
8
- managedAccessTokensShareBinding,
9
- normalizeServerError,
10
- } from '@jsb188/app/utils/api.ts';
11
- import { delay, makeVariablesKey } from '@jsb188/app/utils/logic.ts';
12
- import {
13
- queryCacheKeyMatchesResetTarget,
14
- type QueryResetTarget,
15
- } from '@jsb188/app/utils/queryReset.ts';
16
- import {
17
- isServerErrorGQL,
18
- isTransientServerError,
19
- } from '@jsb188/graphql/utils';
2
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d.ts';
3
+ import { getAuthToken, managedAccessTokensShareBinding, normalizeServerError } from '@jsb188/app/utils/api.ts';
4
+ import { graphQLValuesEqual } from '../cache/value.helpers.ts';
5
+ import { delay, makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
6
+ import { queryCacheKeyMatchesResetTarget, type QueryResetTarget } from '@jsb188/app/utils/queryReset.ts';
7
+ import { isServerErrorGQL, isTransientServerError } from '@jsb188/graphql/utils';
8
+ import { useConnectedToServerValue, useOptimisticConnectedToServerValue, useScreenIsFocusedValue } from '@jsb188/react/states';
9
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
20
10
  import {
21
- useConnectedToServerValue,
22
- useOptimisticConnectedToServerValue,
23
- useScreenIsFocusedValue,
24
- } from '@jsb188/react/states';
25
- import {
26
- useCallback,
27
- useEffect,
28
- useLayoutEffect,
29
- useMemo,
30
- useRef,
31
- useState,
32
- useSyncExternalStore,
33
- } from 'react';
34
- import { QUERY_EXPIRE_TIMES } from '../cache/config.ts';
35
- import { EAGER_QUERY_MAP } from '../gql/eagerQueryMap.ts';
11
+ claimQueryActivation,
12
+ getQueryActivation,
13
+ isQueryDataStale,
14
+ type QueryActivation,
15
+ startQueryRequestTimeout,
16
+ } from './index.helpers.ts';
36
17
  import {
37
18
  checkDataCompleteness,
38
19
  clearQueryResetStatus,
39
20
  fetchCachedData,
40
21
  getFragmentVersionStamp,
22
+ getGraphQLCacheEpoch,
41
23
  getNextQueryLastUpdatedCount,
42
24
  getQueryLastFetchedAt,
43
25
  getQueryRefreshTime,
@@ -45,13 +27,18 @@ import {
45
27
  loadFragment,
46
28
  removeStaleCache,
47
29
  } from '../cache/index.ts';
30
+ import { releaseMountedQueryKey, retainMountedQueryKey } from '../cache/mounted-queries.ts';
31
+ import { beginOptimisticUITransaction } from '../cache/optimistic-ui.ts';
32
+ import { getRealtimeLiveSince } from '../cache/realtime-live.ts';
48
33
  import { graphqlRequest } from '../client/request.ts';
34
+ import { EAGER_QUERY_MAP } from '../gql/eagerQueryMap.ts';
49
35
  import type {
50
36
  AnyModalPopUpFn,
51
37
  GraphQLHandlers,
52
38
  GraphQLQueryOptions,
53
39
  OnCompletedGQLFn,
54
40
  OnErrorGQLFn,
41
+ OptimisticUI,
55
42
  UpdateDataObserverArgs,
56
43
  UpdateObserversFn,
57
44
  } from '../types.d.ts';
@@ -60,10 +47,12 @@ import type {
60
47
  * Types; mutation
61
48
  */
62
49
 
63
- export type GraphQLMutationFn = (
64
- graphqlOptions?: GraphQLRequestOptions,
65
- triedCount?: number,
66
- ) => Promise<any>;
50
+ export type GraphQLMutationFn = (graphqlOptions?: GraphQLMutationRequestOptions, triedCount?: number) => Promise<any>;
51
+
52
+ export type GraphQLMutationRequestOptions = {
53
+ optimisticUI?: OptimisticUI;
54
+ variables?: Record<string, any> | null;
55
+ };
67
56
 
68
57
  type GraphQLMutationOptions = Partial<{
69
58
  checkMountedBeforeCallback: boolean;
@@ -99,20 +88,26 @@ type GraphQLMutation = [
99
88
  */
100
89
 
101
90
  type GraphQLRequestOptions = {
91
+ signal?: AbortSignal;
102
92
  variables?: Record<string, any> | null;
103
93
  };
104
94
 
105
95
  type GraphQLQueryResult = {
106
96
  data: any | null;
107
97
  variables?: Record<string, any> | null;
108
- loading: boolean;
98
+ loading: boolean | null;
109
99
  error: ServerErrorObj | null;
110
- refetch: () => void;
100
+ refetch: () => Promise<any>;
111
101
  fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
112
102
  queryName: string;
113
103
  queryKey: string;
114
104
  refreshTime: string;
115
105
  resetOnlyTime: string;
106
+ // The newest RESET_ONLY generation satisfied by the displayed result; paged
107
+ // lists key their dataset on it so a manual refresh rebuilds from page one.
108
+ acknowledgedResetOnlyTime: string;
109
+ // A RESET_ONLY invalidation is waiting for the user to refresh this displayed result.
110
+ stale: boolean;
116
111
  variablesKey: string;
117
112
  updatedCount: number;
118
113
  updateObservers: UpdateObserversFn;
@@ -124,8 +119,10 @@ type GraphQLQueryResult = {
124
119
  type GraphQLQueryValues = {
125
120
  data: any;
126
121
  variables?: Record<string, any> | null;
127
- loading: boolean;
122
+ loading: boolean | null;
128
123
  error: ServerErrorObj | null;
124
+ lastResetOnlyQueryKey: string;
125
+ lastResetOnlyTime: string;
129
126
  lastUpdatedCount: number;
130
127
  lastRefreshTriggerTime: string;
131
128
  };
@@ -142,10 +139,37 @@ type GraphQLQueryOutput = {
142
139
 
143
140
  const QRY_TRACKER = new Map();
144
141
  const QRY_PROMISES = new Map<string, Promise<any>>();
145
- const FRAGMENT_OBSERVER_LISTENERS = new Map<
146
- string,
147
- Set<(fragmentIds: string[]) => void>
148
- >();
142
+ const QRY_PROMISE_RESET_ONLY_SEQUENCES = new Map<string, number>();
143
+ const QUERY_RESET_ONLY_ACKNOWLEDGMENTS = new Map<string, number>();
144
+ const QUERY_RESET_ONLY_EVENTS = new Map<string, QueryObserverEventObj>();
145
+ const FORCE_QUERY_REFRESH = {
146
+ events: new Map<string, QueryObserverEventObj>(),
147
+ acknowledged: new Map<string, number>(),
148
+ pending: new Map<string, number>(),
149
+ };
150
+ const FRAGMENT_OBSERVER_LISTENERS = new Map<string, Set<(fragmentIds: string[]) => void>>();
151
+
152
+ /**
153
+ * Stale query registry. A mounted useQuery() whose displayed result is retained
154
+ * while a RESET_ONLY invalidation waits for the user registers here, keyed by the
155
+ * hook instance, so one app-level notice can offer to refresh every stale query.
156
+ */
157
+
158
+ type StaleQueryEntry = {
159
+ queryKey: string;
160
+ refetch: () => Promise<any>;
161
+ sequence: number;
162
+ };
163
+
164
+ type StaleQueriesSnapshot = {
165
+ count: number;
166
+ // Increments on every registration, removal and newer invalidation generation.
167
+ version: number;
168
+ };
169
+
170
+ const STALE_QUERIES = new Map<string, StaleQueryEntry>();
171
+ const STALE_QUERY_LISTENERS = new Set<() => void>();
172
+ let STALE_QUERIES_SNAPSHOT: StaleQueriesSnapshot = { count: 0, version: 0 };
149
173
 
150
174
  /**
151
175
  * Keyed query observer registry. Each mounted useQuery() subscribes with a
@@ -163,11 +187,11 @@ type QueryObserverEventObj = {
163
187
  target?: QueryResetTarget | null;
164
188
  forceRefetch: boolean;
165
189
  resetOnly: boolean;
190
+ // A reset-only event caused by this tab's own request: refetch instead of showing the notice
191
+ selfRefresh?: boolean;
166
192
  };
167
193
 
168
- const QUERY_OBSERVER_LISTENERS = new Set<
169
- (event: QueryObserverEventObj) => void
170
- >();
194
+ const QUERY_OBSERVER_LISTENERS = new Set<(event: QueryObserverEventObj) => void>();
171
195
 
172
196
  // The last published event is retained so a hook mounting later still sees
173
197
  // it on first render; this is what lets a freshly mounted query pick up a
@@ -187,30 +211,40 @@ const FILE_CONSTANTS = {
187
211
  transientRetryMaximumMs: 10000,
188
212
  };
189
213
 
214
+ let queryRuntimeCacheEpoch = getGraphQLCacheEpoch();
215
+
216
+ /*
217
+ * A new login/cache scope must never join a request or acknowledge an
218
+ * invalidation belonging to the previous normalized cache lifetime.
219
+ */
220
+ function synchronizeQueryRuntimeEpoch() {
221
+ const epoch = getGraphQLCacheEpoch();
222
+ if (queryRuntimeCacheEpoch === epoch) return;
223
+ queryRuntimeCacheEpoch = epoch;
224
+ QRY_TRACKER.clear();
225
+ QRY_PROMISES.clear();
226
+ QRY_PROMISE_RESET_ONLY_SEQUENCES.clear();
227
+ QUERY_RESET_ONLY_ACKNOWLEDGMENTS.clear();
228
+ QUERY_RESET_ONLY_EVENTS.clear();
229
+ FORCE_QUERY_REFRESH.events.clear();
230
+ FORCE_QUERY_REFRESH.acknowledged.clear();
231
+ FORCE_QUERY_REFRESH.pending.clear();
232
+ LAST_QUERY_OBSERVER_EVENT = { ...LAST_QUERY_OBSERVER_EVENT, name: '', target: null, forceRefetch: false, resetOnly: false };
233
+ }
234
+
190
235
  /**
191
236
  * Check whether one query's cached data is older than its freshness window
192
237
  * (options.persistTime, falling back to the query's expire time). Data that
193
238
  * never came from the network in this session or persisted snapshot is
194
- * always stale.
239
+ * always stale, and so is data fetched before realtime delivery last resumed
240
+ * after a gap (it may have missed changes).
195
241
  */
196
242
 
197
- function queryDataIsStale(
198
- queryName: string,
199
- queryKey: string,
200
- persistTime?: number,
201
- ): boolean {
202
- const lastFetchedAt = getQueryLastFetchedAt(queryKey);
203
-
204
- if (!lastFetchedAt) {
205
- return true;
206
- }
207
-
208
- const freshnessWindow =
209
- typeof persistTime === 'number'
210
- ? persistTime
211
- : QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
212
-
213
- return Date.now() - lastFetchedAt > freshnessWindow;
243
+ function queryDataIsStale(queryName: string, queryKey: string, persistTime?: number): boolean {
244
+ const fetchedAt = getQueryLastFetchedAt(queryKey);
245
+ if (isQueryDataStale(queryName, fetchedAt, persistTime)) return true;
246
+ // persistTime: Infinity marks immutable data (log revisions); a gap cannot have changed it
247
+ return persistTime !== Infinity && fetchedAt !== undefined && fetchedAt < getRealtimeLiveSince();
214
248
  }
215
249
 
216
250
  /**
@@ -221,30 +255,88 @@ function makeQueryHookId() {
221
255
  }
222
256
 
223
257
  /**
224
- * Return GraphQL result data wrapped under its operation name.
258
+ * Preserve every selected root field from a successful operation's response, including additional roots and aliases.
225
259
  */
226
- function getQueryDataFromAPIResult(queryName: string, apiResult: any) {
227
- if (
228
- !apiResult ||
229
- apiResult.aborted ||
230
- apiResult.error ||
231
- apiResult[queryName] === undefined
232
- ) {
260
+ function getQueryDataFromAPIResult(query: any, apiResult: any) {
261
+ const operation = query.definitions.find((definition: any) => definition.kind === 'OperationDefinition');
262
+ const queryName = operation?.name?.value;
263
+ if (!apiResult || apiResult.aborted || apiResult.error || apiResult[queryName] === undefined) {
233
264
  return null;
234
265
  }
235
266
 
236
- return {
237
- [queryName]: apiResult[queryName],
238
- };
267
+ const data: Record<string, any> = {};
268
+ for (const selection of operation.selectionSet.selections) {
269
+ const name = selection.alias?.value || selection.name?.value;
270
+ if (name && apiResult[name] !== undefined) data[name] = apiResult[name];
271
+ }
272
+ return data;
273
+ }
274
+
275
+ /*
276
+ * Wait for a shared query result while allowing one caller to cancel only its own wait.
277
+ */
278
+ function waitForSharedQueryOrAbort(pendingQuery: Promise<any>, externalSignal: AbortSignal): Promise<any> {
279
+ if (externalSignal.aborted) {
280
+ return Promise.resolve({ aborted: true });
281
+ }
282
+
283
+ return new Promise((resolve, reject) => {
284
+ let settled = false;
285
+
286
+ /*
287
+ * Claim this wait's single settlement and detach its cancellation listener.
288
+ */
289
+ const beginSettlement = () => {
290
+ if (settled) {
291
+ return false;
292
+ }
293
+
294
+ settled = true;
295
+ externalSignal.removeEventListener('abort', onAbort);
296
+ return true;
297
+ };
298
+
299
+ /*
300
+ * Resolve this caller as cancelled without aborting the shared request owner.
301
+ */
302
+ const onAbort = () => {
303
+ if (beginSettlement()) {
304
+ resolve({ aborted: true });
305
+ }
306
+ };
307
+
308
+ /*
309
+ * Forward the shared query result when this caller still owns its wait.
310
+ */
311
+ const onPendingResolved = (apiResult: any) => {
312
+ if (beginSettlement()) {
313
+ resolve(apiResult);
314
+ }
315
+ };
316
+
317
+ /*
318
+ * Preserve a shared query rejection when cancellation did not settle first.
319
+ */
320
+ const onPendingRejected = (error: unknown) => {
321
+ if (beginSettlement()) {
322
+ reject(error);
323
+ }
324
+ };
325
+
326
+ externalSignal.addEventListener('abort', onAbort, { once: true });
327
+ // Close the narrow race between the initial check and listener registration.
328
+ if (externalSignal.aborted) {
329
+ onAbort();
330
+ }
331
+ void pendingQuery.then(onPendingResolved, onPendingRejected);
332
+ });
239
333
  }
240
334
 
241
335
  /**
242
336
  * Convert reactive fragment observe entries into exact fragment observer keys.
243
337
  */
244
338
 
245
- function getReactiveFragmentObserveKeys(
246
- observe: Array<string | [string, string | null]>,
247
- ) {
339
+ function getReactiveFragmentObserveKeys(observe: Array<string | [string, string | null]>) {
248
340
  return observe
249
341
  .map((key) => {
250
342
  return Array.isArray(key) ? key[0] : key;
@@ -256,10 +348,7 @@ function getReactiveFragmentObserveKeys(
256
348
  * Subscribe to exact fragment observer keys.
257
349
  */
258
350
 
259
- function subscribeFragmentObserverKeys(
260
- fragmentIds: string[],
261
- listener: (fragmentIds: string[]) => void,
262
- ) {
351
+ function subscribeFragmentObserverKeys(fragmentIds: string[], listener: (fragmentIds: string[]) => void) {
263
352
  for (const fragmentId of fragmentIds) {
264
353
  const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId) || new Set();
265
354
  listeners.add(listener);
@@ -285,10 +374,7 @@ function subscribeFragmentObserverKeys(
285
374
  * Returns the unsubscribe function.
286
375
  */
287
376
 
288
- export function observeReactiveFragments(
289
- fragmentIds: string[],
290
- listener: (fragmentIds: string[]) => void,
291
- ) {
377
+ export function observeReactiveFragments(fragmentIds: string[], listener: (fragmentIds: string[]) => void) {
292
378
  return subscribeFragmentObserverKeys(fragmentIds, listener);
293
379
  }
294
380
 
@@ -315,14 +401,10 @@ function notifyFragmentObserverListeners(fragmentIds: string[]) {
315
401
  * Observe only the exact fragment keys needed by one reactive fragment hook.
316
402
  */
317
403
 
318
- function useFragmentKeyObserver(
319
- observe: Array<string | [string, string | null]>,
320
- ) {
321
- const observeStr = getReactiveFragmentObserveKeys(observe).join(',');
322
- const observeKeys = useMemo(
323
- () => observeStr.split(',').filter(Boolean),
324
- [observeStr],
325
- );
404
+ function useFragmentKeyObserver(observe: Array<string | [string, string | null]>) {
405
+ const observeStr = JSON.stringify(getReactiveFragmentObserveKeys(observe));
406
+ const observeKeys = useMemo<string[]>(() => JSON.parse(observeStr), [observeStr]);
407
+ const pending = useRef({ count: 0, keys: new Map<string, number>() });
326
408
  const [fragmentObserver, setFragmentObserver] = useState({
327
409
  count: 0,
328
410
  list: [] as string[],
@@ -330,13 +412,19 @@ function useFragmentKeyObserver(
330
412
 
331
413
  useEffect(() => {
332
414
  return subscribeFragmentObserverKeys(observeKeys, (fragmentIds) => {
333
- setFragmentObserver((prev) => ({
334
- count: prev.count + 1,
335
- list: fragmentIds,
336
- }));
415
+ const count = ++pending.current.count;
416
+ for (const key of fragmentIds) pending.current.keys.set(key, count);
417
+ setFragmentObserver({ count, list: Array.from(pending.current.keys.keys()) });
337
418
  });
338
419
  }, [observeKeys]);
339
420
 
421
+ // Retire only committed notifications; a newer event may arrive between render and effects.
422
+ useEffect(() => {
423
+ for (const [key, count] of pending.current.keys) {
424
+ if (count <= fragmentObserver.count) pending.current.keys.delete(key);
425
+ }
426
+ }, [fragmentObserver.count]);
427
+
340
428
  return fragmentObserver;
341
429
  }
342
430
 
@@ -356,22 +444,39 @@ function unsetQueryTracker(queryName: string, unique: string | null) {
356
444
  */
357
445
 
358
446
  function getRetryDelay(triedCount: number): number {
359
- return 1500 * Math.pow(2, triedCount);
447
+ return 1500 * 2 ** triedCount;
448
+ }
449
+
450
+ /**
451
+ * Return whether one terminal mutation result must roll optimistic cache state back.
452
+ */
453
+ function mutationResultNeedsOptimisticRollback(apiResult: any) {
454
+ return Boolean(!apiResult || apiResult.aborted || apiResult.error || apiResult.__clientResultRejected);
455
+ }
456
+
457
+ /*
458
+ * Return one local mutation result when another optimistic transaction owns a target.
459
+ */
460
+ function makeOptimisticUIConflictResult() {
461
+ return {
462
+ error: {
463
+ errorCode: 'optimistic_ui_conflict',
464
+ message: 'An optimistic update for this fragment is already in progress.',
465
+ statusCode: 409,
466
+ title: 'Update in progress',
467
+ },
468
+ };
360
469
  }
361
470
 
362
471
  /**
363
472
  * Return a capped, jittered delay for retrying one temporary server failure.
364
473
  */
365
474
  function getTransientRetryDelay(attemptCount: number): number {
366
- const exponentialDelay = Math.min(
367
- FILE_CONSTANTS.transientRetryMaximumMs,
368
- FILE_CONSTANTS.transientRetryBaseMs * 2 ** attemptCount,
369
- );
475
+ const exponentialDelay = Math.min(FILE_CONSTANTS.transientRetryMaximumMs, FILE_CONSTANTS.transientRetryBaseMs * 2 ** attemptCount);
370
476
 
371
477
  return Math.min(
372
478
  FILE_CONSTANTS.transientRetryMaximumMs,
373
- exponentialDelay +
374
- Math.floor(Math.random() * FILE_CONSTANTS.transientRetryJitterMs),
479
+ exponentialDelay + Math.floor(Math.random() * FILE_CONSTANTS.transientRetryJitterMs),
375
480
  );
376
481
  }
377
482
 
@@ -379,17 +484,9 @@ function getTransientRetryDelay(attemptCount: number): number {
379
484
  * Return whether a delayed retry still belongs to the same browser login or
380
485
  * to a refreshed token for that exact managed account session.
381
486
  */
382
- function authContextMatchesRetryToken(
383
- retryToken: string | null,
384
- currentToken: string | null,
385
- ) {
487
+ function authContextMatchesRetryToken(retryToken: string | null, currentToken: string | null) {
386
488
  return (
387
- retryToken === currentToken ||
388
- Boolean(
389
- retryToken &&
390
- currentToken &&
391
- managedAccessTokensShareBinding(retryToken, currentToken),
392
- )
489
+ retryToken === currentToken || Boolean(retryToken && currentToken && managedAccessTokensShareBinding(retryToken, currentToken))
393
490
  );
394
491
  }
395
492
 
@@ -399,20 +496,23 @@ function authContextMatchesRetryToken(
399
496
  */
400
497
 
401
498
  export function updateDataObservers(args: UpdateDataObserverArgs) {
499
+ synchronizeQueryRuntimeEpoch();
402
500
  if (args.queryId) {
403
501
  LAST_QUERY_OBSERVER_EVENT = {
404
- count:
405
- (LAST_QUERY_OBSERVER_EVENT.name === args.queryId
406
- ? LAST_QUERY_OBSERVER_EVENT.count
407
- : 0) + 1,
502
+ count: (LAST_QUERY_OBSERVER_EVENT.name === args.queryId ? LAST_QUERY_OBSERVER_EVENT.count : 0) + 1,
408
503
  eventSequence: (LAST_QUERY_OBSERVER_EVENT.eventSequence || 0) + 1,
409
504
  name: args.queryId as string,
410
505
  target: args.queryTarget || null,
411
506
  forceRefetch: !!args.forceRefetch,
412
507
  resetOnly: !!args.resetOnly,
508
+ selfRefresh: !!args.selfRefresh,
413
509
  };
414
510
 
415
511
  const event = LAST_QUERY_OBSERVER_EVENT;
512
+ if (event.forceRefetch) FORCE_QUERY_REFRESH.events.set(event.name, event);
513
+ if (event.resetOnly) {
514
+ QUERY_RESET_ONLY_EVENTS.set(event.name, event);
515
+ }
416
516
  QUERY_OBSERVER_LISTENERS.forEach((listener) => {
417
517
  listener(event);
418
518
  });
@@ -444,24 +544,26 @@ function queryObserverEventMatchesQuery(
444
544
  event: QueryObserverEventObj,
445
545
  query: any,
446
546
  variablesKey: string,
547
+ includePendingForceRefetch: boolean = true,
447
548
  ): boolean {
448
549
  const eventName = event.name;
449
550
  if (!eventName) {
450
551
  return false;
451
552
  }
452
553
 
453
- const queryDefs = query.definitions.filter(
454
- (d: any) => d.kind === 'OperationDefinition',
455
- );
554
+ const queryDefs = query.definitions.filter((d: any) => d.kind === 'OperationDefinition');
456
555
 
457
556
  // A pending force-refetch reset for this query must always be picked up
458
557
  const firstQueryName = queryDefs?.[0]?.name?.value;
459
- if (firstQueryName && getQueryRefreshTime(firstQueryName, variablesKey)) {
558
+ if (includePendingForceRefetch && firstQueryName && getQueryRefreshTime(firstQueryName, variablesKey)) {
460
559
  return true;
461
560
  }
462
561
 
463
- return queryDefs.some((d: any) => {
464
- const queryName = d.name.value;
562
+ const names = queryDefs.flatMap((definition: any) => [
563
+ definition.name.value,
564
+ ...definition.selectionSet.selections.map((selection: any) => selection.alias?.value || selection.name?.value).filter(Boolean),
565
+ ]);
566
+ return names.some((queryName: string) => {
465
567
  const fullQueryKey = `#${queryName}:${variablesKey}`;
466
568
 
467
569
  if (event.target) {
@@ -476,22 +578,61 @@ function queryObserverEventMatchesQuery(
476
578
  }
477
579
  }
478
580
 
479
- return (
480
- eventName === fullQueryKey ||
481
- eventName === `#${queryName}:` ||
482
- fullQueryKey.startsWith(eventName)
483
- );
581
+ return eventName === fullQueryKey || eventName === `#${queryName}:` || fullQueryKey.startsWith(eventName);
484
582
  });
485
583
  }
486
584
 
585
+ /*
586
+ * Return the newest reset-only event covering one exact query key, or null when there is none.
587
+ * Its eventSequence is the reset-only generation a result must acknowledge.
588
+ */
589
+ function getLatestQueryResetOnlyEvent(query: any, variablesKey: string): QueryObserverEventObj | null {
590
+ let latestEvent: QueryObserverEventObj | null = null;
591
+
592
+ for (const event of QUERY_RESET_ONLY_EVENTS.values()) {
593
+ if (event.eventSequence > (latestEvent?.eventSequence || 0) && queryObserverEventMatchesQuery(event, query, variablesKey, false)) {
594
+ latestEvent = event;
595
+ }
596
+ }
597
+
598
+ return latestEvent;
599
+ }
600
+
601
+ /*
602
+ * Retain forced invalidations until a request started after that event completes.
603
+ * In-flight request sharing must not acknowledge events newer than the request.
604
+ */
605
+ function getLatestQueryForceRefreshSequence(query: any, variablesKey: string) {
606
+ let sequence = 0;
607
+ for (const event of FORCE_QUERY_REFRESH.events.values()) {
608
+ if (event.eventSequence > sequence && queryObserverEventMatchesQuery(event, query, variablesKey, false)) {
609
+ sequence = event.eventSequence;
610
+ }
611
+ }
612
+ return sequence;
613
+ }
614
+
615
+ /*
616
+ * Acknowledge one attempted refresh, including errors, without consuming later events.
617
+ */
618
+ function acknowledgeQueryForceRefresh(queryKey: string, sequence: number) {
619
+ FORCE_QUERY_REFRESH.acknowledged.set(queryKey, Math.max(sequence, FORCE_QUERY_REFRESH.acknowledged.get(queryKey) || 0));
620
+ }
621
+
622
+ /*
623
+ * Record the newest reset-only generation satisfied by one exact query result.
624
+ */
625
+ function acknowledgeQueryResetOnlySequence(queryKey: string, resetOnlySequence: number) {
626
+ if (resetOnlySequence > (QUERY_RESET_ONLY_ACKNOWLEDGMENTS.get(queryKey) || 0)) {
627
+ QUERY_RESET_ONLY_ACKNOWLEDGMENTS.set(queryKey, resetOnlySequence);
628
+ }
629
+ }
630
+
487
631
  /**
488
632
  * Subscribe one query hook to only the observer events that match its query.
489
633
  */
490
634
 
491
- function useQueryObserverEvent(
492
- query: any,
493
- variablesKey: string,
494
- ): QueryObserverEventObj {
635
+ function useQueryObserverEvent(query: any, variablesKey: string): QueryObserverEventObj {
495
636
  const [event, setEvent] = useState(LAST_QUERY_OBSERVER_EVENT);
496
637
 
497
638
  useEffect(() => {
@@ -504,11 +645,14 @@ function useQueryObserverEvent(
504
645
  QUERY_OBSERVER_LISTENERS.add(listener);
505
646
 
506
647
  // Deliver anything published between render and subscription
507
- setEvent((currentEvent: QueryObserverEventObj) =>
508
- currentEvent === LAST_QUERY_OBSERVER_EVENT
509
- ? currentEvent
510
- : LAST_QUERY_OBSERVER_EVENT,
511
- );
648
+ setEvent((currentEvent: QueryObserverEventObj) => {
649
+ const latestEvent = LAST_QUERY_OBSERVER_EVENT;
650
+ if (currentEvent === latestEvent || !queryObserverEventMatchesQuery(latestEvent, query, variablesKey)) {
651
+ return currentEvent;
652
+ }
653
+
654
+ return latestEvent;
655
+ });
512
656
 
513
657
  return () => {
514
658
  QUERY_OBSERVER_LISTENERS.delete(listener);
@@ -522,12 +666,7 @@ function useQueryObserverEvent(
522
666
  * Hook for query changes
523
667
  */
524
668
 
525
- export function useWatchQuery(
526
- query: any,
527
- variablesKey: string,
528
- lastUpdatedCount: number,
529
- loading: boolean,
530
- ) {
669
+ export function useWatchQuery(query: any, variablesKey: string, lastUpdatedCount: number, loading: boolean | null) {
531
670
  const qryObserver = useQueryObserverEvent(query, variablesKey);
532
671
  const [qryReset, setQryReset] = useState({
533
672
  triggerTime: '',
@@ -535,11 +674,13 @@ export function useWatchQuery(
535
674
  refreshTimeActive: '', // This value resets when loading starts
536
675
  });
537
676
 
538
- const queryWatcher = useMemo<[number, boolean, string, string]>(() => {
677
+ const queryWatcher = useMemo<[number, boolean, string, string, boolean]>(() => {
678
+ const latestResetOnlyEvent = getLatestQueryResetOnlyEvent(query, variablesKey);
679
+ const resetOnlyTime = latestResetOnlyEvent ? String(latestResetOnlyEvent.eventSequence) : '';
680
+ const resetOnlySelfRefresh = !!latestResetOnlyEvent?.selfRefresh;
681
+
539
682
  if (qryObserver.name) {
540
- const queryDefs = query.definitions.filter(
541
- (d: any) => d.kind === 'OperationDefinition',
542
- );
683
+ const queryDefs = query.definitions.filter((d: any) => d.kind === 'OperationDefinition');
543
684
  const queryName = queryDefs?.[0]?.name?.value;
544
685
 
545
686
  if (queryName) {
@@ -547,70 +688,40 @@ export function useWatchQuery(
547
688
 
548
689
  if (qryTriggerTime) {
549
690
  clearQueryResetStatus(queryName, variablesKey);
550
- console.dev(
551
- `... (1) Query [${queryName}:${variablesKey}] is being force refetched via observer.`,
552
- );
553
- return [lastUpdatedCount + 1, true, qryTriggerTime, ''];
554
- }
555
- }
556
-
557
- const matchedQry = queryDefs.find((d: any) => {
558
- const queryName = d.name.value;
559
- const fullQueryKey = `#${queryName}:${variablesKey}`;
560
- const queryNameKey = `#${queryName}:`;
561
-
562
- if (qryObserver.target) {
563
- return queryCacheKeyMatchesResetTarget(
564
- fullQueryKey,
565
- qryObserver.target,
566
- );
567
- }
568
-
569
- if (qryObserver.name.startsWith('^')) {
570
- try {
571
- return new RegExp(qryObserver.name).test(fullQueryKey);
572
- } catch (_err) {
573
- return false;
691
+ // Forced events already have a shared refresh sequence. A second, locally consumed
692
+ // timestamp would make another reader refetch again after that sequence completes.
693
+ if (!qryObserver.forceRefetch) {
694
+ console.dev(`... (1) Query [${queryName}:${variablesKey}] is being force refetched via observer.`);
695
+ return [lastUpdatedCount + 1, true, qryTriggerTime, resetOnlyTime, resetOnlySelfRefresh];
574
696
  }
575
697
  }
698
+ }
576
699
 
577
- return (
578
- qryObserver.name === fullQueryKey ||
579
- qryObserver.name === queryNameKey ||
580
- fullQueryKey.startsWith(qryObserver.name)
581
- );
582
- });
700
+ const matchedQry = queryDefs.find((definition: any) =>
701
+ queryObserverEventMatchesQuery(qryObserver, { definitions: [definition] }, variablesKey, false),
702
+ );
583
703
 
584
704
  if (!matchedQry) {
585
- return [lastUpdatedCount, false, '', ''];
705
+ return [lastUpdatedCount, false, '', resetOnlyTime, resetOnlySelfRefresh];
586
706
  }
587
707
 
588
708
  const matchedQueryName = matchedQry.name.value;
589
709
  const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
590
710
  const forceRefetch = !!qryObserver.forceRefetch;
591
- const resetOnlyTime = qryObserver.resetOnly
592
- ? String(qryObserver.eventSequence)
593
- : '';
594
-
595
- let newUpdatedCount =
596
- qryObserver.name === matchedQueryId || forceRefetch
597
- ? qryObserver.count
598
- : 0;
711
+ let newUpdatedCount = qryObserver.name === matchedQueryId || forceRefetch ? qryObserver.count : 0;
599
712
  if (forceRefetch) {
600
713
  newUpdatedCount += 1;
601
714
  }
602
715
 
603
716
  if (forceRefetch) {
604
- console.dev(
605
- `... (2) Query [${matchedQueryId}] is being force refetched via observer.`,
606
- );
717
+ console.dev(`... (2) Query [${matchedQueryId}] is being force refetched via observer.`);
607
718
  }
608
719
 
609
- return [newUpdatedCount, forceRefetch, '', resetOnlyTime];
720
+ return [newUpdatedCount, forceRefetch, '', resetOnlyTime, resetOnlySelfRefresh];
610
721
  }
611
722
 
612
- return [lastUpdatedCount, false, '', ''];
613
- }, [lastUpdatedCount, qryObserver]);
723
+ return [lastUpdatedCount, false, '', resetOnlyTime, resetOnlySelfRefresh];
724
+ }, [lastUpdatedCount, qryObserver, query, variablesKey]);
614
725
 
615
726
  useEffect(() => {
616
727
  if (!loading) {
@@ -641,6 +752,8 @@ export function useWatchQuery(
641
752
  updatedCount: queryWatcher[0],
642
753
  forceRefetch: queryWatcher[1],
643
754
  resetOnlyTime: queryWatcher[3],
755
+ // The newest reset-only event was caused by this tab's own request
756
+ resetOnlySelfRefresh: queryWatcher[4],
644
757
  qryReset,
645
758
  };
646
759
  }
@@ -650,19 +763,12 @@ export function useWatchQuery(
650
763
  * keys. Fragment values win because websocket updates can be newer than the
651
764
  * query result that supplied the document base.
652
765
  */
653
- function getReactiveFragmentData(
654
- data: any,
655
- observe: Array<string | [string, string | null]>,
656
- mainPrioritizedFields?: string[],
657
- ) {
766
+ function getReactiveFragmentData(data: any, observe: Array<string | [string, string | null]>, mainPrioritizedFields?: string[]) {
658
767
  let nextData = data;
659
768
 
660
769
  observe.forEach((key) => {
661
770
  const isMapped = Array.isArray(key);
662
- const fragmentData = loadFragment(
663
- isMapped ? key[0] : key,
664
- mainPrioritizedFields,
665
- );
771
+ const fragmentData = loadFragment(isMapped ? key[0] : key, mainPrioritizedFields);
666
772
 
667
773
  if (!fragmentData) {
668
774
  return;
@@ -698,11 +804,12 @@ export function useReactiveFragment(
698
804
  otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
699
805
  mainPrioritizedFields?: string[],
700
806
  ignoreIDWarning?: boolean,
701
- isTest?: boolean,
807
+ _isTest?: boolean,
702
808
  ) {
703
809
  const fragmentObserver = useFragmentKeyObserver(observe);
704
810
  const frgObsCount = fragmentObserver.count;
705
811
  const dataId = data?.id;
812
+ const observeIdentity = JSON.stringify([observe, mainPrioritizedFields]);
706
813
 
707
814
  // Version stamp of the observed fragments at the last rebuild; notifications
708
815
  // that did not actually change any observed fragment are skipped without a
@@ -711,59 +818,64 @@ export function useReactiveFragment(
711
818
 
712
819
  const [changedData, setChangedData] = useState<any>(() => {
713
820
  return {
821
+ observeIdentity,
714
822
  fragmentUpdatedCount: frgObsCount,
715
823
  queryUpdatedCount: qryObsCount,
824
+ sourceData: data,
716
825
  data: getReactiveFragmentData(data, observe, mainPrioritizedFields),
717
826
  };
718
827
  });
719
828
 
720
- if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
721
- // this is fine because it will only run in development and never truly be conditional
722
- // eslint-disable-next-line react-hooks/rules-of-hooks
723
- useEffect(() => {
724
- if (
725
- // getENVVariable('NODE_ENV') === 'development' &&
726
- dataId &&
727
- changedData.data?.id &&
728
- dataId !== changedData.data?.id
729
- ) {
730
- console.warn(
731
- `WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`,
732
- );
733
- console.warn(
734
- 'This can result in invalid merged data. Use key={id} to avoid this error.',
735
- );
736
- }
737
- }, [changedData.data?.id]);
738
- }
829
+ // Query-only viewer facts can arrive after the owning observer count changed.
830
+ const sourceDataChanged = useMemo(
831
+ () => data !== changedData.sourceData && !graphQLValuesEqual(data, changedData.sourceData),
832
+ [data, changedData.sourceData],
833
+ );
834
+ const observedKeysChanged = observeIdentity !== changedData.observeIdentity;
739
835
 
740
836
  useEffect(() => {
837
+ if (
838
+ getENVVariable('NODE_ENV') === 'development' &&
839
+ !ignoreIDWarning &&
840
+ !observedKeysChanged &&
841
+ dataId &&
842
+ changedData.data?.id &&
843
+ dataId !== changedData.data.id
844
+ ) {
845
+ console.warn('useReactiveFragment received a document that does not match its observed fragment keys.');
846
+ }
847
+ }, [dataId, changedData.data?.id, observeIdentity, ignoreIDWarning]);
848
+
849
+ useEffect(() => {
850
+ if (observedKeysChanged) {
851
+ lastBuildStampRef.current = getFragmentVersionStamp(getReactiveFragmentObserveKeys(observe));
852
+ setChangedData({
853
+ observeIdentity,
854
+ fragmentUpdatedCount: frgObsCount,
855
+ queryUpdatedCount: qryObsCount,
856
+ sourceData: data,
857
+ data: getReactiveFragmentData(data, observe, mainPrioritizedFields),
858
+ });
859
+ return;
860
+ }
741
861
  // NOTE: I tried this with Preact's effect()
742
862
  // But that caused the render to happen 3 times more, I don't know why.
743
863
  // I only solved it by using useEffect()
744
864
  const idsChanged =
745
- !dataId ||
746
- changedData.data?.id !== dataId ||
747
- // This is absolutely needed for the chat clientId system to work properly;
748
- // Otherwise messages will be stuck in "not sent" state.
749
- (changedData.data?.clientId &&
750
- changedData.data?.clientId !== data.clientId);
751
- const queryDataChanged = qryObsCount !== changedData.queryUpdatedCount;
865
+ data &&
866
+ (changedData.data?.id !== dataId ||
867
+ // This is absolutely needed for the chat clientId system to work properly;
868
+ // Otherwise messages will be stuck in "not sent" state.
869
+ (changedData.data?.clientId && changedData.data?.clientId !== data.clientId));
870
+ const queryDataChanged = sourceDataChanged || qryObsCount !== changedData.queryUpdatedCount;
752
871
 
753
872
  const forceReactive = otherCheck?.(changedData.data, fragmentObserver.list);
754
873
 
755
- if (
756
- idsChanged ||
757
- forceReactive ||
758
- ((changedData.data || data) &&
759
- (frgObsCount !== changedData.fragmentUpdatedCount || queryDataChanged))
760
- ) {
874
+ if (idsChanged || forceReactive || frgObsCount !== changedData.fragmentUpdatedCount || queryDataChanged) {
761
875
  // When only a fragment notification arrived, skip the rebuild if none
762
876
  // of the observed fragments actually changed since the last build.
763
877
  if (!idsChanged && !queryDataChanged && !forceReactive) {
764
- const observedStamp = getFragmentVersionStamp(
765
- getReactiveFragmentObserveKeys(observe),
766
- );
878
+ const observedStamp = getFragmentVersionStamp(getReactiveFragmentObserveKeys(observe));
767
879
  if (observedStamp === lastBuildStampRef.current) {
768
880
  return;
769
881
  }
@@ -775,38 +887,27 @@ export function useReactiveFragment(
775
887
  forceReactive ||
776
888
  observe.some((key) => {
777
889
  const isMapped = Array.isArray(key);
778
- return isMapped
779
- ? fragmentObserver.list.includes(key[0])
780
- : fragmentObserver.list.includes(key);
890
+ return isMapped ? fragmentObserver.list.includes(key[0]) : fragmentObserver.list.includes(key);
781
891
  });
782
892
 
783
893
  let newData: any;
784
894
  if (dataUpdated) {
785
- const baseData =
786
- (idsChanged || queryDataChanged) && data
787
- ? data
788
- : data
789
- ? { ...data, ...changedData.data }
790
- : changedData.data;
791
- newData = getReactiveFragmentData(
792
- baseData,
793
- observe,
794
- mainPrioritizedFields,
795
- );
895
+ const baseData = (idsChanged || queryDataChanged) && data ? data : data ? { ...data, ...changedData.data } : changedData.data;
896
+ newData = getReactiveFragmentData(baseData, observe, mainPrioritizedFields);
796
897
  }
797
898
 
798
899
  if (newData) {
799
- lastBuildStampRef.current = getFragmentVersionStamp(
800
- getReactiveFragmentObserveKeys(observe),
801
- );
900
+ lastBuildStampRef.current = getFragmentVersionStamp(getReactiveFragmentObserveKeys(observe));
802
901
  setChangedData({
902
+ observeIdentity,
803
903
  data: newData,
804
904
  fragmentUpdatedCount: frgObsCount,
805
905
  queryUpdatedCount: qryObsCount,
906
+ sourceData: data,
806
907
  });
807
908
  }
808
909
  }
809
- }, [dataId, qryObsCount, frgObsCount]);
910
+ }, [dataId, qryObsCount, frgObsCount, sourceDataChanged, data, observeIdentity]);
810
911
 
811
912
  // This is not needed now, I think
812
913
  // useEffect(() => {
@@ -828,10 +929,8 @@ export function useReactiveFragment(
828
929
  // console.log('2', data);
829
930
  // }
830
931
 
831
- if (data && qryObsCount !== changedData.queryUpdatedCount) {
832
- return (
833
- getReactiveFragmentData(data, observe, mainPrioritizedFields) ?? null
834
- );
932
+ if (observedKeysChanged || (data && (sourceDataChanged || qryObsCount !== changedData.queryUpdatedCount))) {
933
+ return getReactiveFragmentData(data, observe, mainPrioritizedFields) ?? null;
835
934
  }
836
935
 
837
936
  return changedData.data ?? null;
@@ -841,10 +940,7 @@ export function useReactiveFragment(
841
940
  * Merge mapped array data with the latest fragment cache values.
842
941
  */
843
942
 
844
- function getReactiveFragmentMapData(
845
- data: any[] | null,
846
- observe?: string[] | null,
847
- ) {
943
+ function getReactiveFragmentMapData(data: any[] | null, observe?: string[] | null) {
848
944
  if (!data || !observe?.length) {
849
945
  return data;
850
946
  }
@@ -872,20 +968,13 @@ function getReactiveFragmentMapData(
872
968
  * owning query publishes a new same-shape result generation.
873
969
  */
874
970
 
875
- export function useReactiveFragmentMap(
876
- data: any[] | null,
877
- fragmentName_: string,
878
- qryObsCount?: number | boolean,
879
- ) {
971
+ export function useReactiveFragmentMap(data: any[] | null, fragmentName_: string, qryObsCount?: number | boolean) {
880
972
  const fragmentName = `$${fragmentName_}`;
881
- const observeStr = useMemo<string>(
882
- () => data?.map((item) => `${fragmentName}:${item.id}`).join(',') || '',
973
+ const observeStr = useMemo(
974
+ () => JSON.stringify(data?.map((item) => (item?.id == null ? '' : `${fragmentName}:${item.id}`)) || []),
883
975
  [data, fragmentName],
884
976
  );
885
- const observe = useMemo<string[]>(
886
- () => observeStr.split(',').filter(Boolean),
887
- [observeStr],
888
- );
977
+ const observe = useMemo<string[]>(() => JSON.parse(observeStr), [observeStr]);
889
978
  const observeIndex = useMemo<Map<string, number>>(() => {
890
979
  const indexMap = new Map<string, number>();
891
980
 
@@ -897,16 +986,25 @@ export function useReactiveFragmentMap(
897
986
  }, [observe]);
898
987
  const fragmentObserver = useFragmentKeyObserver(observe);
899
988
 
900
- // Version stamp of the observed fragments at the last rebuild; see
901
- // useReactiveFragment() for the rationale.
902
- const lastBuildStampRef = useRef('');
989
+ // Capture versions with this render's notification list. Reading them in the
990
+ // effect could acknowledge a newer update that this render has not consumed.
991
+ const observedStamp = getFragmentVersionStamp(observe);
992
+ const lastBuildStampRef = useRef(observedStamp);
903
993
 
904
- const [changedData, setChangedData] = useState({
994
+ const [changedData, setChangedData] = useState(() => ({
905
995
  count: fragmentObserver.count,
906
996
  lastObserveStr: observeStr,
907
997
  queryUpdatedCount: qryObsCount,
998
+ sourceData: data,
908
999
  data: getReactiveFragmentMapData(data, observe),
909
- });
1000
+ }));
1001
+
1002
+ // A query's observer count can advance before its response is installed.
1003
+ // Rebase a later same-count result too, without looping on equivalent caller arrays.
1004
+ const sourceDataChanged = useMemo(
1005
+ () => data !== changedData.sourceData && !graphQLValuesEqual(data, changedData.sourceData),
1006
+ [data, changedData.sourceData],
1007
+ );
910
1008
 
911
1009
  useEffect(() => {
912
1010
  // NOTE: I tried this with Preact's effect()
@@ -915,11 +1013,12 @@ export function useReactiveFragmentMap(
915
1013
 
916
1014
  const queryDataChanged = qryObsCount !== changedData.queryUpdatedCount;
917
1015
  const observedIdsChanged = changedData.lastObserveStr !== observeStr;
918
- if (queryDataChanged || observedIdsChanged) {
919
- lastBuildStampRef.current = getFragmentVersionStamp(observe);
1016
+ if (queryDataChanged || observedIdsChanged || sourceDataChanged) {
1017
+ lastBuildStampRef.current = observedStamp;
920
1018
  setChangedData({
921
1019
  count: fragmentObserver.count,
922
1020
  data: getReactiveFragmentMapData(data, observe),
1021
+ sourceData: data,
923
1022
  lastObserveStr: observeStr,
924
1023
  queryUpdatedCount: qryObsCount,
925
1024
  });
@@ -931,7 +1030,6 @@ export function useReactiveFragmentMap(
931
1030
 
932
1031
  // Skip the rebuild when none of the observed fragments actually changed
933
1032
  // since the last build (e.g. a deep-equal realtime echo).
934
- const observedStamp = getFragmentVersionStamp(observe);
935
1033
  if (observedStamp === lastBuildStampRef.current) {
936
1034
  return;
937
1035
  }
@@ -977,12 +1075,9 @@ export function useReactiveFragmentMap(
977
1075
  count: fragmentObserver.count,
978
1076
  queryUpdatedCount: qryObsCount,
979
1077
  });
980
- }, [fragmentObserver.count, observeStr, qryObsCount]);
1078
+ }, [fragmentObserver.count, observeStr, qryObsCount, sourceDataChanged, data]);
981
1079
 
982
- if (
983
- changedData.lastObserveStr !== observeStr ||
984
- changedData.queryUpdatedCount !== qryObsCount
985
- ) {
1080
+ if (sourceDataChanged || changedData.lastObserveStr !== observeStr || changedData.queryUpdatedCount !== qryObsCount) {
986
1081
  return getReactiveFragmentMapData(data, observe);
987
1082
  }
988
1083
 
@@ -993,184 +1088,124 @@ export function useReactiveFragmentMap(
993
1088
  * Use mutation
994
1089
  */
995
1090
 
996
- export function useMutation(
997
- mutation: any,
998
- options?: GraphQLMutationOptions,
999
- ): GraphQLMutation {
1000
- const {
1001
- onCompleted,
1002
- onError,
1003
- openModalPopUp,
1004
- initialError,
1005
- checkMountedBeforeCallback,
1006
- cachePolicy,
1007
- } = options || {};
1091
+ export function useMutation(mutation: any, options?: GraphQLMutationOptions): GraphQLMutation {
1092
+ const { onCompleted, onError, openModalPopUp, initialError, checkMountedBeforeCallback } = options || {};
1008
1093
  const updateObservers = useUpdateObservers();
1009
-
1010
- // No need to abort mutations
1011
- // But bring it back if you want ability to "cancel"
1012
- // const controller = useRef();
1013
-
1014
1094
  const tracker = useRef({
1015
1095
  mounted: true,
1016
1096
  timer: null as ReturnType<typeof setTimeout> | null,
1097
+ sequence: 0,
1098
+ pending: 0,
1017
1099
  });
1018
-
1019
- const [mtnValues, setMtnValues] = useState({
1020
- variables: null as Record<string, any> | null,
1100
+ const [mtnValues, setMtnValues] = useState<GraphQLMutationResult>({
1101
+ variables: null,
1021
1102
  saving: false,
1022
1103
  data: null,
1023
- error: initialError || (null as ServerErrorObj | null),
1104
+ error: initialError || null,
1024
1105
  mutationCount: 0,
1025
1106
  });
1026
1107
 
1027
- // Mounted hook
1028
-
1029
1108
  useEffect(() => {
1109
+ tracker.current.mounted = true;
1030
1110
  return () => {
1031
1111
  tracker.current.mounted = false;
1032
- if (tracker.current.timer) {
1033
- clearTimeout(tracker.current.timer);
1034
- }
1112
+ if (tracker.current.timer) clearTimeout(tracker.current.timer);
1035
1113
  };
1036
1114
  }, []);
1037
1115
 
1038
- // Mutate function for the client
1039
-
1040
- const doMutate = async (
1041
- graphqlOptions?: GraphQLRequestOptions,
1042
- triedCount: number = 0,
1043
- ) => {
1044
- // No need to abort mutations
1045
- // if (controller.current) {
1046
- // controller.current.abort();
1047
- // }
1048
-
1049
- // No need to abort mutations
1050
- // controller.current = new AbortController();
1051
-
1052
- setMtnValues({
1053
- ...mtnValues,
1054
- variables: graphqlOptions?.variables || null,
1055
- saving: true,
1056
- });
1057
-
1116
+ /* Run one logical mutation with one optimistic transaction across transport retries. */
1117
+ const doMutate = async (graphqlOptions?: GraphQLMutationRequestOptions, triedCount = 0) => {
1118
+ const optimisticResult = beginOptimisticUITransaction(graphqlOptions?.optimisticUI, updateObservers);
1119
+ if (optimisticResult.status === 'conflict') return makeOptimisticUIConflictResult();
1120
+ const transaction = optimisticResult.transaction;
1121
+ const variables = graphqlOptions?.variables === undefined ? options?.variables : graphqlOptions.variables;
1122
+ const sequence = ++tracker.current.sequence;
1123
+ const requestCacheEpoch = getGraphQLCacheEpoch();
1124
+ const retryAuthToken = getAuthToken();
1058
1125
  const retryCount = options?.retryCount || 0;
1059
- const retryDelay = getRetryDelay(triedCount);
1060
-
1061
- const apiResult = await graphqlRequest(
1062
- mutation,
1063
- graphqlOptions?.variables,
1064
- {
1065
- cachePolicy,
1066
- openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
1067
- onCompleted: (data: any | null, error: ServerErrorObj | null) => {
1068
- if (tracker.current.mounted) {
1069
- setMtnValues({
1070
- ...mtnValues,
1071
- mutationCount: mtnValues.mutationCount + 1,
1072
- saving: false,
1073
- data: data.data || null,
1074
- error,
1075
- });
1076
- }
1077
-
1078
- if (data.data) {
1079
- if (
1080
- onCompleted &&
1081
- (tracker.current.mounted || !checkMountedBeforeCallback)
1082
- ) {
1083
- // Do separate {mounted.current} check from outside
1084
- onCompleted(data.data, error, graphqlOptions?.variables);
1085
- }
1086
- }
1087
- },
1088
- onError: (error: ServerErrorObj | null) => {
1089
- if (tracker.current.mounted) {
1090
- setMtnValues({
1091
- ...mtnValues,
1092
- saving: retryCount > triedCount,
1093
- error,
1094
- });
1095
- }
1096
-
1097
- if (
1098
- onError &&
1099
- retryCount <= triedCount &&
1100
- (tracker.current.mounted || !checkMountedBeforeCallback)
1101
- ) {
1102
- onError(error, graphqlOptions?.variables);
1103
- }
1104
- },
1105
- },
1106
- null, // abort controller is not needed for mutations
1107
- updateObservers,
1108
- );
1109
-
1110
- if (apiResult.aborted) {
1111
- return apiResult;
1112
- }
1126
+ tracker.current.pending += 1;
1127
+ setMtnValues((current) => ({ ...current, variables: variables ?? null, saving: true, error: null }));
1113
1128
 
1114
- if (!apiResult.data && isServerErrorGQL(apiResult)) {
1115
- if (retryCount > triedCount) {
1116
- await delay(retryDelay);
1117
- if (getENVVariable('NODE_ENV') === 'development') {
1118
- console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
1129
+ try {
1130
+ let result: any;
1131
+ let responseData: any = null;
1132
+ for (let attempt = triedCount; ; attempt += 1) {
1133
+ result = await graphqlRequest(
1134
+ mutation,
1135
+ variables,
1136
+ {
1137
+ authToken: options?.authToken,
1138
+ cacheMap: options?.cacheMap,
1139
+ cachePolicy: options?.cachePolicy,
1140
+ openModalPopUp: attempt >= retryCount ? openModalPopUp : null,
1141
+ onCompleted: (response) => {
1142
+ responseData = response?.data ?? null;
1143
+ },
1144
+ onError: () => {},
1145
+ },
1146
+ null,
1147
+ updateObservers,
1148
+ );
1149
+ if (responseData || !isServerErrorGQL(result) || attempt >= retryCount) break;
1150
+ await delay(getRetryDelay(attempt));
1151
+ if (requestCacheEpoch !== getGraphQLCacheEpoch() || !authContextMatchesRetryToken(retryAuthToken, getAuthToken())) {
1152
+ result = { aborted: true };
1153
+ break;
1119
1154
  }
1155
+ }
1120
1156
 
1121
- return doMutate(graphqlOptions, triedCount + 1);
1122
- } else if (getENVVariable('NODE_ENV') === 'development') {
1123
- console.log(
1124
- `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
1125
- );
1157
+ if (mutationResultNeedsOptimisticRollback(result)) transaction?.rollback();
1158
+ else transaction?.commit();
1159
+
1160
+ if (tracker.current.mounted) {
1161
+ setMtnValues((current) => ({
1162
+ ...current,
1163
+ mutationCount: current.mutationCount + (responseData ? 1 : 0),
1164
+ // All calls settle, but a late older response cannot replace the newest call's UI state.
1165
+ ...(sequence === tracker.current.sequence
1166
+ ? {
1167
+ data: responseData ?? current.data,
1168
+ error: result?.error ?? null,
1169
+ }
1170
+ : {}),
1171
+ }));
1126
1172
  }
1173
+ if (tracker.current.mounted || !checkMountedBeforeCallback) {
1174
+ if (result?.error) onError?.(result.error, variables);
1175
+ if (responseData) onCompleted?.(responseData, result?.error ?? null, variables);
1176
+ }
1177
+ return result;
1178
+ } catch (error) {
1179
+ transaction?.rollback();
1180
+ throw error;
1181
+ } finally {
1182
+ tracker.current.pending -= 1;
1183
+ if (tracker.current.mounted) setMtnValues((current) => ({ ...current, saving: tracker.current.pending > 0 }));
1127
1184
  }
1128
-
1129
- return apiResult;
1130
1185
  };
1131
1186
 
1132
1187
  const mtnHandlers: GraphQLHandlers = {
1133
- resetErrors: () => {
1134
- setMtnValues({
1135
- ...mtnValues,
1136
- error: null,
1137
- });
1138
- },
1139
- setError: (errorObj: SimpleErrorType) => {
1140
- setMtnValues({
1141
- ...mtnValues,
1142
- error: {
1143
- statusCode: 200,
1144
- errorCode: 'custom_error',
1145
- ...errorObj,
1146
- },
1147
- });
1148
- },
1149
- refetch: () => {
1150
- const lastVariables = mtnValues.variables;
1151
- return doMutate(lastVariables ? { variables: lastVariables } : undefined);
1152
- },
1153
- setSaving: (nextSaving: boolean, resetInMS?: number) => {
1154
- setMtnValues({
1155
- ...mtnValues,
1156
- saving: nextSaving,
1157
- });
1158
-
1159
- if (nextSaving && resetInMS) {
1160
- if (tracker.current.timer) {
1161
- clearTimeout(tracker.current.timer);
1162
- }
1163
-
1188
+ /* Clear only the error while preserving the latest mutation state. */
1189
+ resetErrors: () => setMtnValues((current) => ({ ...current, error: null })),
1190
+ /* Replace only the error without restoring an earlier result or saving flag. */
1191
+ setError: (errorObj: SimpleErrorType) =>
1192
+ setMtnValues((current) => ({
1193
+ ...current,
1194
+ error: { statusCode: 200, errorCode: 'custom_error', ...errorObj, title: errorObj.title || '' },
1195
+ })),
1196
+ /* Repeat the most recently submitted variables. */
1197
+ refetch: () => doMutate({ variables: mtnValues.variables }),
1198
+ /* A timer can release saving without overwriting results received since it was scheduled. */
1199
+ setSaving: (saving: boolean, resetInMS?: number) => {
1200
+ if (tracker.current.timer) clearTimeout(tracker.current.timer);
1201
+ setMtnValues((current) => ({ ...current, saving }));
1202
+ if (saving && resetInMS) {
1164
1203
  tracker.current.timer = setTimeout(() => {
1165
- setMtnValues({
1166
- ...mtnValues,
1167
- saving: false,
1168
- });
1204
+ if (tracker.current.mounted) setMtnValues((current) => ({ ...current, saving: tracker.current.pending > 0 }));
1169
1205
  }, resetInMS);
1170
1206
  }
1171
1207
  },
1172
1208
  };
1173
-
1174
1209
  return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
1175
1210
  }
1176
1211
 
@@ -1187,23 +1222,37 @@ export function prefetchQuery(
1187
1222
  variables?: Record<string, any> | null,
1188
1223
  options?: {
1189
1224
  authToken?: string | null;
1225
+ persistTime?: number;
1190
1226
  updateObservers?: UpdateObserversFn;
1191
1227
  },
1192
1228
  ): Promise<any> {
1229
+ synchronizeQueryRuntimeEpoch();
1193
1230
  const queryName = query.definitions?.[0]?.name?.value;
1194
- const variablesKey = makeVariablesKey(variables);
1231
+ const variablesKey = makeGraphQLVariablesKey(variables);
1195
1232
  const queryKey = `#${queryName}:${variablesKey}`;
1233
+ const requestForceSequence = getLatestQueryForceRefreshSequence(query, variablesKey);
1234
+ const requestResetOnlySequence = getLatestQueryResetOnlyEvent(query, variablesKey)?.eventSequence || 0;
1235
+ const resetOnlyPending = requestResetOnlySequence > (QUERY_RESET_ONLY_ACKNOWLEDGMENTS.get(queryKey) || 0);
1196
1236
 
1197
1237
  // A complete cached result means there is nothing to warm
1198
1238
  const cachedResult = fetchCachedData(query, variablesKey);
1199
- if (cachedResult) {
1239
+ if (
1240
+ cachedResult &&
1241
+ !queryDataIsStale(queryName, queryKey, options?.persistTime) &&
1242
+ !resetOnlyPending &&
1243
+ requestForceSequence <= (FORCE_QUERY_REFRESH.acknowledged.get(queryKey) || 0)
1244
+ ) {
1200
1245
  return Promise.resolve(cachedResult);
1201
1246
  }
1202
1247
 
1203
1248
  // A mounted hook or another prefetch already owns this request
1204
1249
  const pendingQuery = QRY_PROMISES.get(queryKey);
1205
1250
  if (pendingQuery) {
1206
- return pendingQuery;
1251
+ const pendingResetOnlySequence = QRY_PROMISE_RESET_ONLY_SEQUENCES.get(queryKey) || 0;
1252
+ return pendingResetOnlySequence >= requestResetOnlySequence &&
1253
+ (FORCE_QUERY_REFRESH.pending.get(queryKey) || 0) >= requestForceSequence
1254
+ ? pendingQuery
1255
+ : pendingQuery.then(() => prefetchQuery(query, variables, options));
1207
1256
  }
1208
1257
 
1209
1258
  const queryPromise = graphqlRequest(
@@ -1216,12 +1265,25 @@ export function prefetchQuery(
1216
1265
  options?.updateObservers,
1217
1266
  );
1218
1267
  QRY_PROMISES.set(queryKey, queryPromise);
1268
+ QRY_PROMISE_RESET_ONLY_SEQUENCES.set(queryKey, requestResetOnlySequence);
1269
+ FORCE_QUERY_REFRESH.pending.set(queryKey, requestForceSequence);
1270
+
1271
+ return queryPromise
1272
+ .then((apiResult) => {
1273
+ if (!apiResult?.aborted) acknowledgeQueryForceRefresh(queryKey, requestForceSequence);
1274
+ if (requestResetOnlySequence && getQueryDataFromAPIResult(query, apiResult)) {
1275
+ acknowledgeQueryResetOnlySequence(queryKey, requestResetOnlySequence);
1276
+ }
1219
1277
 
1220
- return queryPromise.finally(() => {
1221
- if (QRY_PROMISES.get(queryKey) === queryPromise) {
1222
- QRY_PROMISES.delete(queryKey);
1223
- }
1224
- });
1278
+ return apiResult;
1279
+ })
1280
+ .finally(() => {
1281
+ if (QRY_PROMISES.get(queryKey) === queryPromise) {
1282
+ QRY_PROMISES.delete(queryKey);
1283
+ QRY_PROMISE_RESET_ONLY_SEQUENCES.delete(queryKey);
1284
+ FORCE_QUERY_REFRESH.pending.delete(queryKey);
1285
+ }
1286
+ });
1225
1287
  }
1226
1288
 
1227
1289
  /**
@@ -1249,7 +1311,7 @@ type EagerQueriesValues = {
1249
1311
  */
1250
1312
 
1251
1313
  function makeEagerQueryKey(instruction: EagerQueryInstruction) {
1252
- return `#${instruction.queryName}:${makeVariablesKey(instruction.variables)}`;
1314
+ return `#${instruction.queryName}:${makeGraphQLVariablesKey(instruction.variables)}`;
1253
1315
  }
1254
1316
 
1255
1317
  /**
@@ -1261,13 +1323,9 @@ function getEagerQuery(queryName: string) {
1261
1323
 
1262
1324
  if (getENVVariable('NODE_ENV') === 'development') {
1263
1325
  if (!query) {
1264
- console.warn(
1265
- `useEagerQueries() has no registered query named "${queryName}". Add it to EAGER_QUERY_MAP.`,
1266
- );
1326
+ console.warn(`useEagerQueries() has no registered query named "${queryName}". Add it to EAGER_QUERY_MAP.`);
1267
1327
  } else {
1268
- const operationName = query.definitions?.find(
1269
- (def: any) => def.kind === 'OperationDefinition',
1270
- )?.name?.value;
1328
+ const operationName = query.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
1271
1329
 
1272
1330
  if (operationName !== queryName) {
1273
1331
  console.warn(
@@ -1327,10 +1385,7 @@ export function prefetchEagerQuery(
1327
1385
  * must still land in the query cache after navigation.
1328
1386
  */
1329
1387
 
1330
- export function useEagerQueries(
1331
- instructions?: EagerQueryInstruction[] | null,
1332
- counter?: number | null,
1333
- ): EagerQueriesValues {
1388
+ export function useEagerQueries(instructions?: EagerQueryInstruction[] | null, counter?: number | null): EagerQueriesValues {
1334
1389
  const updateObservers = useUpdateObservers();
1335
1390
  const tracker = useRef({
1336
1391
  mounted: true,
@@ -1349,9 +1404,7 @@ export function useEagerQueries(
1349
1404
 
1350
1405
  // An empty batch means the caller's source data is not ready yet, so it
1351
1406
  // must not consume the once-only fetch
1352
- const instructionsKey = instructions?.length
1353
- ? instructions.map(makeEagerQueryKey).join('|')
1354
- : '';
1407
+ const instructionsKey = instructions?.length ? instructions.map(makeEagerQueryKey).join('|') : '';
1355
1408
 
1356
1409
  // Mounted hook; only state updates stop on unmount, never the fetches
1357
1410
 
@@ -1439,9 +1492,7 @@ export function useEagerQueries(
1439
1492
  * this hook through its keyed query observer and local request state; React's
1440
1493
  * external-store consistency pass is only needed to bridge SSR hydration.
1441
1494
  */
1442
- function subscribeHydrationSafeQuerySnapshot(
1443
- _onStoreChange: () => void,
1444
- ): () => void {
1495
+ function subscribeHydrationSafeQuerySnapshot(_onStoreChange: () => void): () => void {
1445
1496
  return () => {};
1446
1497
  }
1447
1498
 
@@ -1464,11 +1515,7 @@ function getServerQuerySnapshotReady(): boolean {
1464
1515
  * data until React has completed its hydration consistency check.
1465
1516
  */
1466
1517
  function useHydrationSafeQueryCacheSnapshot(query: any, variablesKey: string) {
1467
- const ready = useSyncExternalStore(
1468
- subscribeHydrationSafeQuerySnapshot,
1469
- getClientQuerySnapshotReady,
1470
- getServerQuerySnapshotReady,
1471
- );
1518
+ const ready = useSyncExternalStore(subscribeHydrationSafeQuerySnapshot, getClientQuerySnapshotReady, getServerQuerySnapshotReady);
1472
1519
  const data = ready ? fetchCachedData(query, variablesKey) : null;
1473
1520
 
1474
1521
  return { data, ready };
@@ -1478,10 +1525,8 @@ function useHydrationSafeQueryCacheSnapshot(query: any, variablesKey: string) {
1478
1525
  * Use query
1479
1526
  */
1480
1527
 
1481
- export function useQuery(
1482
- query: any,
1483
- options?: GraphQLQueryOptions,
1484
- ): GraphQLQueryResult {
1528
+ export function useQuery(query: any, options?: GraphQLQueryOptions): GraphQLQueryResult {
1529
+ synchronizeQueryRuntimeEpoch();
1485
1530
  const {
1486
1531
  authToken,
1487
1532
  onCompleted,
@@ -1493,37 +1538,36 @@ export function useQuery(
1493
1538
  eagerFragmentKeyMap,
1494
1539
  shouldAcceptResult,
1495
1540
  persistTime,
1541
+ revalidateOnMount = true,
1496
1542
  } = options || {};
1497
- const variablesKey = makeVariablesKey(variables);
1543
+ const variablesKey = makeGraphQLVariablesKey(variables);
1498
1544
  const connectedToServer = useConnectedToServerValue();
1499
1545
  const optimisticConnectedToServer = useOptimisticConnectedToServerValue();
1500
1546
  const screenIsFocused = useScreenIsFocusedValue();
1501
1547
  const updateObservers = useUpdateObservers();
1502
1548
 
1503
- // useQuery() assumes query is a single graphql query (and not a multi/chain)
1504
- // Multiple queries can be chained using this hook,
1505
- // but only the first query is used for tracking reactivity.
1549
+ // Track one operation and its shared request key; resets for any selected root also invalidate this operation.
1506
1550
  const queryName = query.definitions?.[0]?.name?.value;
1507
1551
  const queryKey = `#${queryName}:${variablesKey}`;
1552
+ const activation = useRef<QueryActivation>({ queryKey: null, checked: false });
1508
1553
 
1509
1554
  const tracker = useRef({
1510
1555
  unique: makeQueryHookId(),
1511
1556
  abortCtrl: null as AbortController | null,
1512
1557
  activeQueryKey: null as string | null,
1558
+ requestedQueryKey: null as string | null,
1559
+ requestSequence: 0,
1513
1560
  ownQueryObserverCount: 0,
1514
1561
  reconnectedAt: null as number | null,
1515
1562
  transientRetryAttemptCount: 0,
1563
+ // The newest reset-only generation of this hook's own key whose refetch failed; effects do not retry it
1564
+ failedResetOnly: { queryKey: '', sequence: 0 },
1516
1565
  mounted: true,
1517
1566
  init: false,
1518
1567
  });
1519
1568
  const trackedUpdateObservers = useCallback(
1520
1569
  (args: UpdateDataObserverArgs) => {
1521
- if (
1522
- args.queryId &&
1523
- args.queryId === tracker.current.activeQueryKey &&
1524
- !args.forceRefetch &&
1525
- !args.resetOnly
1526
- ) {
1570
+ if (args.queryId && args.queryId === tracker.current.activeQueryKey && !args.forceRefetch && !args.resetOnly) {
1527
1571
  tracker.current.ownQueryObserverCount += 1;
1528
1572
  }
1529
1573
 
@@ -1534,37 +1578,50 @@ export function useQuery(
1534
1578
 
1535
1579
  // check if p.updatedCount is needed
1536
1580
 
1581
+ // Loading stays null until this mounted hook participates in its first network request.
1537
1582
  const [qryValues, setQryValues] = useState<GraphQLQueryValues>({
1538
1583
  data: null as any,
1539
1584
  variables,
1540
- loading: false,
1585
+ loading: null,
1541
1586
  error: null as ServerErrorObj | null,
1587
+ lastResetOnlyQueryKey: '',
1588
+ lastResetOnlyTime: '',
1542
1589
  lastUpdatedCount: 0,
1543
1590
  lastRefreshTriggerTime: '',
1544
1591
  });
1545
1592
 
1546
- const qryValuesVariablesKey = makeVariablesKey(qryValues.variables);
1593
+ const qryValuesVariablesKey = makeGraphQLVariablesKey(qryValues.variables);
1547
1594
 
1548
1595
  const {
1549
1596
  updatedCount,
1550
- forceRefetch,
1551
1597
  resetOnlyTime,
1598
+ resetOnlySelfRefresh,
1552
1599
  qryReset: { triggerTime, refreshTime },
1553
- } = useWatchQuery(
1554
- query,
1555
- variablesKey,
1556
- qryValues.lastUpdatedCount,
1557
- qryValues.loading,
1558
- );
1559
- const { data: cachedQuerySnapshot, ready: queryCacheSnapshotReady } =
1560
- useHydrationSafeQueryCacheSnapshot(query, variablesKey);
1600
+ } = useWatchQuery(query, variablesKey, qryValues.lastUpdatedCount, qryValues.loading);
1601
+ const { data: cachedQuerySnapshot, ready: queryCacheSnapshotReady } = useHydrationSafeQueryCacheSnapshot(query, variablesKey);
1561
1602
  const qryValuesMatchVariables = variablesKey === qryValuesVariablesKey;
1562
- const effectiveQueryData =
1563
- cachedQuerySnapshot || (qryValuesMatchVariables ? qryValues.data : null);
1564
- const effectiveQueryDataIsComplete = checkDataCompleteness(
1565
- effectiveQueryData,
1566
- query,
1603
+ const effectiveQueryData = cachedQuerySnapshot || (qryValuesMatchVariables ? qryValues.data : null);
1604
+ const effectiveQueryDataIsComplete = checkDataCompleteness(effectiveQueryData, query);
1605
+ const resetOnlySequence = Number(resetOnlyTime) || 0;
1606
+ const acknowledgedResetOnlySequence = Math.max(
1607
+ qryValues.lastResetOnlyQueryKey === queryKey ? Number(qryValues.lastResetOnlyTime) || 0 : 0,
1608
+ QUERY_RESET_ONLY_ACKNOWLEDGMENTS.get(queryKey) || 0,
1567
1609
  );
1610
+ const resetOnlyPending = resetOnlySequence > acknowledgedResetOnlySequence;
1611
+ // One automatic refetch per reset-only generation: after it failed, the effects below do not retry it
1612
+ // (a newer event, the notice, explicit refetches and other variables still refetch), so a failing request cannot loop.
1613
+ const failedResetOnly = tracker.current.failedResetOnly;
1614
+ const resetOnlyAutoRefetch =
1615
+ resetOnlyPending && (failedResetOnly.queryKey !== queryKey || resetOnlySequence > failedResetOnly.sequence);
1616
+ // RESET_ONLY never replaces a displayed result: the cached pages are gone, but the
1617
+ // mounted list holds until the user acts on its refresh notice (resetOnlyTime).
1618
+ // Cold mounts and changed filters still fetch because they have no complete matching result.
1619
+ // A reset caused by this tab's own request refetches at once, as if the user had clicked the notice;
1620
+ // after that attempt failed it falls back to the notice, like a failed click.
1621
+ const deferResetOnly =
1622
+ resetOnlyPending && (!resetOnlySelfRefresh || !resetOnlyAutoRefetch) && qryValuesMatchVariables && effectiveQueryDataIsComplete;
1623
+ const forceRefreshPending =
1624
+ getLatestQueryForceRefreshSequence(query, variablesKey) > (FORCE_QUERY_REFRESH.acknowledged.get(queryKey) || 0);
1568
1625
 
1569
1626
  // Query function for the client
1570
1627
  // NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
@@ -1573,22 +1630,51 @@ export function useQuery(
1573
1630
  queryVariables?: any,
1574
1631
  triedCount: number = 0,
1575
1632
  rejectedResultCount: number = 0,
1576
- silentRevalidate?: boolean,
1633
+ externalSignal?: AbortSignal,
1577
1634
  ): Promise<any> => {
1635
+ if (externalSignal?.aborted) {
1636
+ return { aborted: true };
1637
+ }
1638
+
1578
1639
  const qryVariables = queryVariables || variables;
1579
- const qryVariablesKey = makeVariablesKey(qryVariables);
1640
+ const requestCacheEpoch = getGraphQLCacheEpoch();
1641
+ const qryVariablesKey = makeGraphQLVariablesKey(qryVariables);
1580
1642
  const qryQueryKey = `#${queryName}:${qryVariablesKey}`;
1643
+ const requestSequence = ++tracker.current.requestSequence;
1644
+ tracker.current.requestedQueryKey = qryQueryKey;
1645
+ /* Only the newest invocation may replace this hook's displayed request state. */
1646
+ const ownsRequestState = () => tracker.current.mounted && tracker.current.requestSequence === requestSequence;
1647
+ // Cold loads and explicit refreshes also satisfy this activation's entry check.
1648
+ claimQueryActivation(activation.current, qryQueryKey);
1649
+ const requestForceSequence = getLatestQueryForceRefreshSequence(query, qryVariablesKey);
1650
+ const requestResetOnlySequence = getLatestQueryResetOnlyEvent(query, qryVariablesKey)?.eventSequence || 0;
1651
+ const requestResetOnlyTime = qryVariablesKey === variablesKey && requestResetOnlySequence ? String(requestResetOnlySequence) : '';
1581
1652
  const pendingQuery = QRY_PROMISES.get(qryQueryKey);
1582
1653
 
1583
1654
  if (pendingQuery) {
1584
- if (!silentRevalidate) {
1585
- setQryValues((currentValues: GraphQLQueryValues) => ({
1586
- ...currentValues,
1587
- loading: true,
1588
- }));
1589
- }
1655
+ const pendingForceSequence = FORCE_QUERY_REFRESH.pending.get(qryQueryKey) || 0;
1656
+ const pendingResetOnlySequence = QRY_PROMISE_RESET_ONLY_SEQUENCES.get(qryQueryKey) || 0;
1657
+ const pendingResetOnlyTime =
1658
+ qryVariablesKey === variablesKey && pendingResetOnlySequence ? String(pendingResetOnlySequence) : '';
1659
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1660
+ ...currentValues,
1661
+ loading: true,
1662
+ }));
1663
+
1664
+ const pendingWait = externalSignal ? waitForSharedQueryOrAbort(pendingQuery, externalSignal) : pendingQuery;
1665
+ return pendingWait.then((apiResult) => {
1666
+ if (requestCacheEpoch !== getGraphQLCacheEpoch()) return { aborted: true };
1667
+ if (!ownsRequestState()) return apiResult;
1668
+ if (externalSignal?.aborted) {
1669
+ if (tracker.current.mounted && !tracker.current.activeQueryKey) {
1670
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1671
+ ...currentValues,
1672
+ loading: false,
1673
+ }));
1674
+ }
1675
+ return { aborted: true };
1676
+ }
1590
1677
 
1591
- return pendingQuery.then((apiResult) => {
1592
1678
  if (apiResult?.aborted) {
1593
1679
  if (!tracker.current.mounted) {
1594
1680
  return apiResult;
@@ -1599,6 +1685,8 @@ export function useQuery(
1599
1685
  // otherwise retrigger this silent stale-cache revalidation.
1600
1686
  if (QRY_PROMISES.get(qryQueryKey) === pendingQuery) {
1601
1687
  QRY_PROMISES.delete(qryQueryKey);
1688
+ QRY_PROMISE_RESET_ONLY_SEQUENCES.delete(qryQueryKey);
1689
+ FORCE_QUERY_REFRESH.pending.delete(qryQueryKey);
1602
1690
  QRY_TRACKER.delete(qryQueryKey);
1603
1691
  }
1604
1692
 
@@ -1607,21 +1695,36 @@ export function useQuery(
1607
1695
  loading: false,
1608
1696
  }));
1609
1697
 
1610
- return doQuery(
1611
- queryVariables,
1612
- triedCount,
1613
- rejectedResultCount,
1614
- silentRevalidate,
1615
- );
1698
+ return doQuery(queryVariables, triedCount, rejectedResultCount, externalSignal);
1616
1699
  }
1617
1700
 
1618
1701
  if (!tracker.current.mounted) {
1619
1702
  return apiResult;
1620
1703
  }
1621
1704
 
1705
+ // A shared request can be rejected because its owning reader retired.
1706
+ // Give a still-active consumer one attempt under its committed scope
1707
+ // before acknowledging the refresh that the owner could not deliver.
1708
+ if (
1709
+ apiResult?.__clientResultRejected &&
1710
+ rejectedResultCount === 0 &&
1711
+ !queryRuntimeRef.current.skip &&
1712
+ queryRuntimeRef.current.queryKey === qryQueryKey
1713
+ ) {
1714
+ return queryRuntimeRef.current.doQuery(queryVariables, triedCount, rejectedResultCount + 1, externalSignal);
1715
+ }
1716
+
1717
+ acknowledgeQueryForceRefresh(qryQueryKey, pendingForceSequence);
1622
1718
  const cachedResult = fetchCachedData(query, qryVariablesKey);
1623
- const data =
1624
- cachedResult || getQueryDataFromAPIResult(queryName, apiResult);
1719
+ const apiResultData = getQueryDataFromAPIResult(query, apiResult);
1720
+ const data = cachedResult || apiResultData;
1721
+ const completedResetOnlyTime = apiResultData && !apiResult?.error ? pendingResetOnlyTime : '';
1722
+ if (apiResult?.error && pendingResetOnlyTime) {
1723
+ tracker.current.failedResetOnly = { queryKey: qryQueryKey, sequence: pendingResetOnlySequence };
1724
+ }
1725
+ if (pendingResetOnlySequence && apiResultData && !apiResult?.error) {
1726
+ acknowledgeQueryResetOnlySequence(qryQueryKey, pendingResetOnlySequence);
1727
+ }
1625
1728
 
1626
1729
  setQryValues((currentValues: GraphQLQueryValues) => ({
1627
1730
  ...currentValues,
@@ -1629,13 +1732,10 @@ export function useQuery(
1629
1732
  data: data || currentValues.data,
1630
1733
  loading: false,
1631
1734
  error: apiResult?.error || null,
1632
- lastUpdatedCount: getNextQueryLastUpdatedCount(
1633
- currentValues.lastUpdatedCount,
1634
- updatedCount,
1635
- 0,
1636
- ),
1637
- lastRefreshTriggerTime:
1638
- triggerTime || currentValues.lastRefreshTriggerTime,
1735
+ lastUpdatedCount: getNextQueryLastUpdatedCount(currentValues.lastUpdatedCount, updatedCount, 0),
1736
+ lastResetOnlyTime: completedResetOnlyTime || currentValues.lastResetOnlyTime,
1737
+ lastResetOnlyQueryKey: completedResetOnlyTime ? qryQueryKey : currentValues.lastResetOnlyQueryKey,
1738
+ lastRefreshTriggerTime: triggerTime || currentValues.lastRefreshTriggerTime,
1639
1739
  }));
1640
1740
 
1641
1741
  return apiResult;
@@ -1663,17 +1763,28 @@ export function useQuery(
1663
1763
  }
1664
1764
 
1665
1765
  tracker.current.abortCtrl = new AbortController();
1766
+ const queryAbortController = tracker.current.abortCtrl;
1767
+ const clearRequestTimeout = startQueryRequestTimeout(queryAbortController, options?.requestTimeoutMs);
1768
+ /*
1769
+ * Forward this caller's cancellation only to the network request it owns.
1770
+ */
1771
+ const onExternalAbort = () => {
1772
+ queryAbortController.abort(externalSignal?.reason);
1773
+ };
1774
+ if (externalSignal) {
1775
+ externalSignal.addEventListener('abort', onExternalAbort, { once: true });
1776
+ // Close the narrow race between the initial check and listener registration.
1777
+ if (externalSignal.aborted) {
1778
+ onExternalAbort();
1779
+ }
1780
+ }
1666
1781
  tracker.current.activeQueryKey = qryQueryKey;
1667
1782
  tracker.current.ownQueryObserverCount = 0;
1668
1783
 
1669
- if (!silentRevalidate) {
1670
- // Background stale-while-revalidate keeps loading=false so consumers
1671
- // keep rendering the served cached data without spinners
1672
- setQryValues((currentValues: GraphQLQueryValues) => ({
1673
- ...currentValues,
1674
- loading: true,
1675
- }));
1676
- }
1784
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1785
+ ...currentValues,
1786
+ loading: true,
1787
+ }));
1677
1788
 
1678
1789
  const retryCount = options?.retryCount || 0;
1679
1790
  const retryDelay = getRetryDelay(triedCount);
@@ -1686,33 +1797,35 @@ export function useQuery(
1686
1797
  qryVariables,
1687
1798
  {
1688
1799
  authToken: authToken || undefined,
1689
- openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
1800
+ openModalPopUp: triedCount >= retryCount ? openModalPopUp : null,
1690
1801
  cacheMap,
1691
1802
  onCompleted: (data: any | null, error: ServerErrorObj | null) => {
1692
1803
  if (data.data) {
1693
1804
  const ownQueryObserverCount = tracker.current.ownQueryObserverCount;
1694
- const completedData =
1695
- fetchCachedData(query, qryVariablesKey) || data.data;
1805
+ const completedData = fetchCachedData(query, qryVariablesKey) || data.data;
1806
+ const completedResetOnlyTime = error ? '' : requestResetOnlyTime;
1696
1807
  tracker.current.ownQueryObserverCount = 0;
1808
+ acknowledgeQueryForceRefresh(qryQueryKey, requestForceSequence);
1809
+ if (requestResetOnlySequence && !error) {
1810
+ acknowledgeQueryResetOnlySequence(qryQueryKey, requestResetOnlySequence);
1811
+ }
1697
1812
 
1698
- setQryValues((currentValues: GraphQLQueryValues) => ({
1699
- ...currentValues,
1700
- variables: qryVariables,
1701
- // Prime and retain the validated normalized snapshot while the
1702
- // network result is already off the navigation-critical path.
1703
- data: completedData,
1704
- loading: false,
1705
- error,
1706
- lastUpdatedCount: getNextQueryLastUpdatedCount(
1707
- currentValues.lastUpdatedCount,
1708
- updatedCount,
1709
- ownQueryObserverCount,
1710
- ),
1711
- lastRefreshTriggerTime:
1712
- triggerTime || currentValues.lastRefreshTriggerTime,
1713
- }));
1714
-
1715
- if (onCompleted) {
1813
+ if (ownsRequestState())
1814
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1815
+ ...currentValues,
1816
+ variables: qryVariables,
1817
+ // Prime and retain the validated normalized snapshot while the
1818
+ // network result is already off the navigation-critical path.
1819
+ data: completedData,
1820
+ loading: false,
1821
+ error,
1822
+ lastUpdatedCount: getNextQueryLastUpdatedCount(currentValues.lastUpdatedCount, updatedCount, ownQueryObserverCount),
1823
+ lastResetOnlyTime: completedResetOnlyTime || currentValues.lastResetOnlyTime,
1824
+ lastResetOnlyQueryKey: completedResetOnlyTime ? qryQueryKey : currentValues.lastResetOnlyQueryKey,
1825
+ lastRefreshTriggerTime: triggerTime || currentValues.lastRefreshTriggerTime,
1826
+ }));
1827
+
1828
+ if (onCompleted && tracker.current.mounted && tracker.current.requestedQueryKey === qryQueryKey) {
1716
1829
  onCompleted(data.data, error, qryVariables);
1717
1830
  }
1718
1831
 
@@ -1720,53 +1833,75 @@ export function useQuery(
1720
1833
  tracker.current.reconnectedAt = Date.now();
1721
1834
  }
1722
1835
 
1723
- tracker.current.activeQueryKey = null;
1836
+ if (tracker.current.abortCtrl === queryAbortController) tracker.current.activeQueryKey = null;
1724
1837
  unsetQueryTracker(qryQueryKey, tracker.current.unique);
1725
1838
  },
1726
1839
  onError: (error: ServerErrorObj | null) => {
1727
- tracker.current.activeQueryKey = null;
1728
- tracker.current.ownQueryObserverCount = 0;
1840
+ acknowledgeQueryForceRefresh(qryQueryKey, requestForceSequence);
1841
+ if (requestResetOnlyTime) tracker.current.failedResetOnly = { queryKey: qryQueryKey, sequence: requestResetOnlySequence };
1842
+ if (tracker.current.abortCtrl === queryAbortController) {
1843
+ tracker.current.activeQueryKey = null;
1844
+ tracker.current.ownQueryObserverCount = 0;
1845
+ }
1729
1846
 
1730
- setQryValues((currentValues: GraphQLQueryValues) => ({
1731
- ...currentValues,
1732
- variables: qryVariables,
1733
- loading: retryCount > triedCount,
1734
- error,
1735
- lastUpdatedCount: getNextQueryLastUpdatedCount(
1736
- currentValues.lastUpdatedCount,
1737
- updatedCount,
1738
- 0,
1739
- ),
1740
- lastRefreshTriggerTime:
1741
- triggerTime || currentValues.lastRefreshTriggerTime,
1742
- }));
1847
+ // A failed attempt settles loading without acknowledging the displayed stale result.
1848
+ if (ownsRequestState())
1849
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1850
+ ...currentValues,
1851
+ variables: qryVariables,
1852
+ loading: retryCount > triedCount,
1853
+ error,
1854
+ lastUpdatedCount: getNextQueryLastUpdatedCount(currentValues.lastUpdatedCount, updatedCount, 0),
1855
+ lastRefreshTriggerTime: triggerTime || currentValues.lastRefreshTriggerTime,
1856
+ }));
1743
1857
 
1744
- if (onError && retryCount <= triedCount) {
1858
+ if (onError && retryCount <= triedCount && ownsRequestState()) {
1745
1859
  onError(error, qryVariables);
1746
1860
  }
1747
1861
 
1748
1862
  unsetQueryTracker(qryQueryKey, tracker.current.unique);
1749
1863
  },
1750
- shouldAcceptResult,
1864
+ shouldAcceptResult: (data, resultVariables) =>
1865
+ (!options?.rejectInvalidatedResults ||
1866
+ getLatestQueryForceRefreshSequence(query, qryVariablesKey) === requestForceSequence) &&
1867
+ (!shouldAcceptResult || shouldAcceptResult(data, resultVariables)),
1751
1868
  },
1752
- tracker.current.abortCtrl.signal,
1869
+ queryAbortController.signal,
1753
1870
  trackedUpdateObservers,
1754
1871
  );
1755
1872
  QRY_PROMISES.set(qryQueryKey, queryPromise);
1873
+ QRY_PROMISE_RESET_ONLY_SEQUENCES.set(qryQueryKey, requestResetOnlySequence);
1874
+ FORCE_QUERY_REFRESH.pending.set(qryQueryKey, requestForceSequence);
1756
1875
 
1757
1876
  let apiResult: any;
1758
1877
  try {
1759
1878
  apiResult = await queryPromise;
1760
1879
  } finally {
1880
+ clearRequestTimeout();
1881
+ externalSignal?.removeEventListener('abort', onExternalAbort);
1761
1882
  if (QRY_PROMISES.get(qryQueryKey) === queryPromise) {
1762
1883
  QRY_PROMISES.delete(qryQueryKey);
1884
+ QRY_PROMISE_RESET_ONLY_SEQUENCES.delete(qryQueryKey);
1885
+ FORCE_QUERY_REFRESH.pending.delete(qryQueryKey);
1763
1886
  }
1764
1887
  }
1765
1888
 
1766
1889
  if (apiResult.aborted) {
1767
- tracker.current.activeQueryKey = null;
1768
- tracker.current.ownQueryObserverCount = 0;
1769
- unsetQueryTracker(qryQueryKey, tracker.current.unique);
1890
+ const ownsCurrentController = tracker.current.abortCtrl === queryAbortController;
1891
+ if (ownsCurrentController) {
1892
+ tracker.current.abortCtrl = null;
1893
+ tracker.current.activeQueryKey = null;
1894
+ tracker.current.ownQueryObserverCount = 0;
1895
+ if (tracker.current.mounted) {
1896
+ setQryValues((currentValues: GraphQLQueryValues) => ({
1897
+ ...currentValues,
1898
+ loading: false,
1899
+ }));
1900
+ }
1901
+ }
1902
+ if (ownsCurrentController || tracker.current.activeQueryKey !== qryQueryKey) {
1903
+ unsetQueryTracker(qryQueryKey, tracker.current.unique);
1904
+ }
1770
1905
  return apiResult;
1771
1906
  }
1772
1907
 
@@ -1774,22 +1909,19 @@ export function useQuery(
1774
1909
  tracker.current.activeQueryKey = null;
1775
1910
  tracker.current.ownQueryObserverCount = 0;
1776
1911
  unsetQueryTracker(qryQueryKey, tracker.current.unique);
1777
- const rejectedResultRetryCount = Math.min(
1778
- 2,
1779
- Math.max(0, Math.floor(options?.rejectedResultRetryCount || 0)),
1780
- );
1912
+ const rejectedResultRetryCount = Math.min(2, Math.max(0, Math.floor(options?.rejectedResultRetryCount || 0)));
1781
1913
  if (rejectedResultCount < rejectedResultRetryCount) {
1782
1914
  tracker.current.abortCtrl = null;
1783
- return doQuery(queryVariables, triedCount, rejectedResultCount + 1);
1915
+ return doQuery(queryVariables, triedCount, rejectedResultCount + 1, externalSignal);
1784
1916
  }
1917
+ // A rejected result must obey the same bounded attempt limit as a failed
1918
+ // refresh. Later invalidations retain their own unacknowledged sequence.
1919
+ acknowledgeQueryForceRefresh(qryQueryKey, requestForceSequence);
1920
+ if (requestResetOnlyTime) tracker.current.failedResetOnly = { queryKey: qryQueryKey, sequence: requestResetOnlySequence };
1785
1921
  setQryValues((currentValues: GraphQLQueryValues) => ({
1786
1922
  ...currentValues,
1787
1923
  loading: false,
1788
- lastUpdatedCount: getNextQueryLastUpdatedCount(
1789
- currentValues.lastUpdatedCount,
1790
- updatedCount,
1791
- 0,
1792
- ),
1924
+ lastUpdatedCount: getNextQueryLastUpdatedCount(currentValues.lastUpdatedCount, updatedCount, 0),
1793
1925
  }));
1794
1926
  return apiResult;
1795
1927
  }
@@ -1797,15 +1929,20 @@ export function useQuery(
1797
1929
  if (!apiResult.data && isServerErrorGQL(apiResult)) {
1798
1930
  if (retryCount > triedCount) {
1799
1931
  await delay(retryDelay);
1932
+ if (
1933
+ !ownsRequestState() ||
1934
+ requestCacheEpoch !== getGraphQLCacheEpoch() ||
1935
+ queryRuntimeRef.current.skip ||
1936
+ queryRuntimeRef.current.queryKey !== queryKey
1937
+ )
1938
+ return { aborted: true };
1800
1939
  if (getENVVariable('NODE_ENV') === 'development') {
1801
1940
  console.log(`retrying query... ${triedCount + 1} / ${retryCount}`);
1802
1941
  }
1803
1942
 
1804
- return doQuery(queryVariables, triedCount + 1);
1943
+ return queryRuntimeRef.current.doQuery(queryVariables, triedCount + 1, rejectedResultCount, externalSignal);
1805
1944
  } else if (getENVVariable('NODE_ENV') === 'development') {
1806
- console.log(
1807
- `query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
1808
- );
1945
+ console.log(`query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`);
1809
1946
  }
1810
1947
  }
1811
1948
 
@@ -1813,58 +1950,59 @@ export function useQuery(
1813
1950
  };
1814
1951
 
1815
1952
  /*
1816
- * Reassess hydration-safe warm snapshots when their activation inputs
1817
- * change. The query-keyed promise registry deduplicates overlapping loads.
1953
+ * Revalidate warm snapshots once per activation while retaining their first paint.
1954
+ * The query-keyed promise registry deduplicates overlapping consumers.
1818
1955
  */
1819
1956
  useEffect(() => {
1820
- if (
1821
- !queryCacheSnapshotReady ||
1822
- !cachedQuerySnapshot ||
1823
- skip ||
1824
- !optimisticConnectedToServer
1825
- ) {
1957
+ activation.current = getQueryActivation(activation.current, queryKey, !!skip);
1958
+ if (!queryCacheSnapshotReady || !cachedQuerySnapshot || skip || !optimisticConnectedToServer) {
1826
1959
  return;
1827
1960
  }
1828
1961
 
1829
- if (forceRefetch || resetOnlyTime || triggerTime) {
1962
+ if (resetOnlyPending || forceRefreshPending || triggerTime) {
1830
1963
  return;
1831
1964
  }
1832
1965
 
1833
- if (
1834
- updatedCount !== qryValues.lastUpdatedCount ||
1835
- variablesKey !== qryValuesVariablesKey
1836
- ) {
1966
+ if (updatedCount !== qryValues.lastUpdatedCount || variablesKey !== qryValuesVariablesKey) {
1837
1967
  return;
1838
1968
  }
1839
1969
 
1840
- tracker.current.reconnectedAt =
1841
- getQueryLastFetchedAt(queryKey) || Date.now();
1970
+ tracker.current.reconnectedAt = getQueryLastFetchedAt(queryKey) || Date.now();
1842
1971
 
1843
- if (queryDataIsStale(queryName, queryKey, persistTime)) {
1844
- void doQuery(undefined, 0, 0, true);
1972
+ if (
1973
+ claimQueryActivation(activation.current, queryKey) &&
1974
+ (revalidateOnMount || queryDataIsStale(queryName, queryKey, persistTime))
1975
+ ) {
1976
+ void doQuery();
1845
1977
  }
1846
1978
  }, [
1847
1979
  cachedQuerySnapshot,
1848
- forceRefetch,
1849
1980
  optimisticConnectedToServer,
1850
1981
  queryCacheSnapshotReady,
1851
1982
  queryKey,
1852
1983
  qryValues.lastUpdatedCount,
1853
1984
  qryValuesVariablesKey,
1854
1985
  resetOnlyTime,
1986
+ resetOnlyPending,
1987
+ forceRefreshPending,
1855
1988
  skip,
1856
1989
  triggerTime,
1857
1990
  updatedCount,
1858
1991
  variablesKey,
1992
+ revalidateOnMount,
1993
+ persistTime,
1859
1994
  ]);
1860
1995
 
1861
1996
  // Mount & unmount
1862
1997
 
1863
1998
  useEffect(() => {
1864
1999
  tracker.current.mounted = true;
2000
+ // Skipped hooks and hooks without a cached result register too; realtime changes reach them only through this
2001
+ retainMountedQueryKey(queryKey);
1865
2002
 
1866
2003
  return () => {
1867
2004
  tracker.current.mounted = false;
2005
+ releaseMountedQueryKey(queryKey);
1868
2006
  unsetQueryTracker(queryKey, tracker.current.unique);
1869
2007
  };
1870
2008
  }, [queryKey]);
@@ -1888,22 +2026,24 @@ export function useQuery(
1888
2026
  useEffect(() => {
1889
2027
  // isTest && console.log('useQuery check:', refreshTime, updatedCount, qryValues.lastUpdatedCount);
1890
2028
 
2029
+ if (deferResetOnly && !forceRefreshPending && !triggerTime) {
2030
+ return;
2031
+ }
2032
+
1891
2033
  if (
1892
2034
  queryCacheSnapshotReady &&
1893
2035
  !skip &&
1894
2036
  ((triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime) ||
2037
+ resetOnlyAutoRefetch ||
2038
+ forceRefreshPending ||
1895
2039
  updatedCount !== qryValues.lastUpdatedCount ||
1896
2040
  variablesKey !== qryValuesVariablesKey ||
1897
2041
  (!qryValues.error && !effectiveQueryDataIsComplete))
1898
2042
  ) {
1899
2043
  const currentDataMatchesVariables =
1900
- effectiveQueryDataIsComplete &&
1901
- (!!cachedQuerySnapshot || variablesKey === qryValuesVariablesKey);
1902
- const canAcknowledgeCurrentData =
1903
- currentDataMatchesVariables &&
1904
- !forceRefetch &&
1905
- !resetOnlyTime &&
1906
- !triggerTime;
2044
+ effectiveQueryDataIsComplete && (!!cachedQuerySnapshot || variablesKey === qryValuesVariablesKey);
2045
+ // A completed manual refresh acknowledges its sequence even if the last observer still says forceRefetch.
2046
+ const canAcknowledgeCurrentData = currentDataMatchesVariables && !resetOnlyPending && !forceRefreshPending && !triggerTime;
1907
2047
 
1908
2048
  if (canAcknowledgeCurrentData) {
1909
2049
  setQryValues((currentValues: GraphQLQueryValues) => ({
@@ -1915,16 +2055,15 @@ export function useQuery(
1915
2055
  return;
1916
2056
  }
1917
2057
 
1918
- const cachedResult =
1919
- cachedQuerySnapshot ||
1920
- fetchCachedData(query, variablesKey, updateObservers);
2058
+ const cachedResult = cachedQuerySnapshot || fetchCachedData(query, variablesKey, updateObservers);
1921
2059
  if (cachedResult) {
1922
2060
  setQryValues({
1923
2061
  ...qryValues,
1924
2062
  variables,
1925
2063
  data: cachedResult,
1926
- error: null,
1927
- loading: false, // IMPORTANT: must be false here
2064
+ // Cached data cannot restore access denied by a newer request.
2065
+ error: qryValuesVariablesKey === variablesKey ? qryValues.error : null,
2066
+ loading: qryValues.loading,
1928
2067
  lastRefreshTriggerTime: triggerTime,
1929
2068
  lastUpdatedCount: updatedCount || 0,
1930
2069
  });
@@ -1936,21 +2075,16 @@ export function useQuery(
1936
2075
  tracker.current.reconnectedAt = lastFetchedAt || Date.now();
1937
2076
  }
1938
2077
 
1939
- if (forceRefetch && !qryValues.loading) {
2078
+ if ((resetOnlyAutoRefetch || forceRefreshPending || !!triggerTime) && !qryValues.loading) {
1940
2079
  // doLog(query, 'forceRefetchhing query at: $0|' + variablesKey + skip + updatedCount);
1941
2080
  doQuery();
1942
2081
  // isTest && console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
1943
2082
  // console.log('::', variablesKey, skip, updatedCount);
1944
- } else if (
1945
- !qryValues.loading &&
1946
- connectedToServer &&
1947
- queryDataIsStale(queryName, queryKey, persistTime)
1948
- ) {
1949
- // Cached data is served above; refresh it silently in the
1950
- // background (stale-while-revalidate)
1951
- doQuery(undefined, 0, 0, true);
2083
+ } else if (!qryValues.loading && connectedToServer && queryDataIsStale(queryName, queryKey, persistTime)) {
2084
+ // Keep serving cached data while it is refreshed in the background.
2085
+ doQuery();
1952
2086
  }
1953
- } else if (!qryValues.loading) {
2087
+ } else if (!qryValues.loading || tracker.current.requestedQueryKey !== queryKey) {
1954
2088
  // isTest && console.log(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
1955
2089
  // doLog(query, '!qryValues.loading, doing query at: $0|' + variablesKey + skip + updatedCount);
1956
2090
  // doLog(query, '1: ' + (triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime));
@@ -1964,12 +2098,16 @@ export function useQuery(
1964
2098
  }
1965
2099
  }
1966
2100
  }, [
2101
+ deferResetOnly,
1967
2102
  cachedQuerySnapshot,
1968
2103
  effectiveQueryDataIsComplete,
1969
2104
  queryCacheSnapshotReady,
1970
2105
  variablesKey,
1971
2106
  qryValuesVariablesKey,
1972
2107
  qryValues.loading,
2108
+ resetOnlyPending,
2109
+ resetOnlyAutoRefetch,
2110
+ forceRefreshPending,
1973
2111
  skip,
1974
2112
  updatedCount,
1975
2113
  triggerTime,
@@ -1979,40 +2117,24 @@ export function useQuery(
1979
2117
 
1980
2118
  const withoutData = effectiveQueryData === null;
1981
2119
  const reconnectedWithoutData =
1982
- queryCacheSnapshotReady &&
1983
- !skip &&
1984
- !qryValues.error &&
1985
- withoutData &&
1986
- !qryValues.loading &&
1987
- connectedToServer;
2120
+ queryCacheSnapshotReady && !skip && !qryValues.error && withoutData && !qryValues.loading && connectedToServer;
1988
2121
 
2122
+ // A pending RESET_ONLY refresh notice also defers focus-based background reloads.
1989
2123
  useEffect(() => {
1990
2124
  if (
1991
2125
  queryCacheSnapshotReady &&
2126
+ !deferResetOnly &&
1992
2127
  connectedToServer &&
1993
2128
  screenIsFocused &&
1994
2129
  !skip &&
1995
- !qryValues.error
2130
+ !qryValues.error &&
2131
+ !qryValues.loading
1996
2132
  ) {
1997
2133
  const now = Date.now();
1998
-
1999
- let timeDiff: number, timeThresh: number;
2000
- if (reconnectedWithoutData) {
2001
- timeDiff = tracker.current.reconnectedAt
2002
- ? now - tracker.current.reconnectedAt
2003
- : Infinity;
2004
- timeThresh = 5000;
2005
- } else {
2006
- timeDiff = tracker.current.reconnectedAt
2007
- ? now - tracker.current.reconnectedAt
2008
- : -Infinity;
2009
- timeThresh =
2010
- QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
2011
- }
2012
-
2013
- // console.log('>>', queryName, timeDiff, timeThresh, timeDiff > timeThresh);
2014
-
2015
- if (tracker.current.init && timeDiff > timeThresh) {
2134
+ const needsRefresh = reconnectedWithoutData
2135
+ ? !tracker.current.reconnectedAt || now - tracker.current.reconnectedAt >= 5000
2136
+ : queryDataIsStale(queryName, queryKey, persistTime);
2137
+ if (tracker.current.init && needsRefresh) {
2016
2138
  // console.log('query again:', queryName, timeDiff);
2017
2139
  // doLog(query, reconnectedWithoutData + ' / ' + skip + ' / ' + withoutData + ' / ' + !qryValues.loading);
2018
2140
  tracker.current.reconnectedAt = now;
@@ -2021,7 +2143,7 @@ export function useQuery(
2021
2143
  tracker.current.init = true;
2022
2144
  }
2023
2145
  }
2024
- }, [queryCacheSnapshotReady, reconnectedWithoutData, screenIsFocused]);
2146
+ }, [deferResetOnly, queryCacheSnapshotReady, reconnectedWithoutData, screenIsFocused, connectedToServer, skip, persistTime]);
2025
2147
 
2026
2148
  const transientError = isTransientServerError(qryValues.error);
2027
2149
 
@@ -2038,9 +2160,7 @@ export function useQuery(
2038
2160
  return;
2039
2161
  }
2040
2162
 
2041
- const retryDelay = getTransientRetryDelay(
2042
- tracker.current.transientRetryAttemptCount,
2043
- );
2163
+ const retryDelay = getTransientRetryDelay(tracker.current.transientRetryAttemptCount);
2044
2164
  const retryAuthToken = getAuthToken();
2045
2165
  const timeoutId = globalThis.setTimeout(() => {
2046
2166
  if (!authContextMatchesRetryToken(retryAuthToken, getAuthToken())) {
@@ -2054,86 +2174,95 @@ export function useQuery(
2054
2174
  return () => {
2055
2175
  globalThis.clearTimeout(timeoutId);
2056
2176
  };
2057
- }, [
2058
- connectedToServer,
2059
- qryValues.loading,
2060
- screenIsFocused,
2061
- skip,
2062
- transientError,
2063
- variablesKey,
2064
- ]);
2177
+ }, [connectedToServer, qryValues.loading, screenIsFocused, skip, transientError, variablesKey]);
2065
2178
 
2066
2179
  /*
2067
2180
  * Keep imperative refreshes behind the same skip boundary as effect-driven
2068
2181
  * loads so stale observers cannot send temporarily null required variables.
2069
2182
  */
2070
- const queryRuntimeRef = useRef({ doQuery, skip });
2183
+ const queryRuntimeRef = useRef({ doQuery, queryKey, skip });
2071
2184
 
2072
2185
  /*
2073
2186
  * Publish only committed query variables to stable imperative callbacks.
2074
2187
  */
2075
2188
  useLayoutEffect(() => {
2076
- queryRuntimeRef.current = { doQuery, skip };
2189
+ queryRuntimeRef.current = { doQuery, queryKey, skip };
2077
2190
  });
2078
2191
 
2079
2192
  /*
2080
- * Refetch with the latest render's query runtime while keeping the public
2081
- * callback identity stable for memoized consumers.
2193
+ * Refetch the committed query and retain a refresh requested during an older
2194
+ * request. Callers awaiting recovery must receive the following fresh result.
2082
2195
  */
2083
- const refetch = useCallback(() => {
2196
+ const refetch = useCallback(async () => {
2084
2197
  const queryRuntime = queryRuntimeRef.current;
2085
- return queryRuntime.skip
2086
- ? Promise.resolve({ skipped: true })
2087
- : queryRuntime.doQuery();
2198
+ if (queryRuntime.skip) return { skipped: true };
2199
+ const refreshSequence = (LAST_QUERY_OBSERVER_EVENT.eventSequence || 0) + 1;
2200
+ updateDataObservers({ queryId: queryRuntime.queryKey, forceRefetch: true });
2201
+ const result = await queryRuntime.doQuery();
2202
+ if (
2203
+ tracker.current.mounted &&
2204
+ !queryRuntimeRef.current.skip &&
2205
+ queryRuntimeRef.current.queryKey === queryRuntime.queryKey &&
2206
+ refreshSequence > (FORCE_QUERY_REFRESH.acknowledged.get(queryRuntime.queryKey) || 0)
2207
+ ) {
2208
+ return queryRuntimeRef.current.doQuery();
2209
+ }
2210
+ return result;
2088
2211
  }, []);
2089
2212
 
2213
+ // A deferred RESET_ONLY keeps the displayed result until the user refreshes it.
2214
+ const stale = deferResetOnly && !skip;
2215
+
2216
+ /*
2217
+ * Offer this hook's refetch to the app-level stale notice while its result is
2218
+ * stale; a newer invalidation generation re-registers so a dismissed notice returns.
2219
+ */
2220
+ useEffect(() => {
2221
+ if (!stale) {
2222
+ return;
2223
+ }
2224
+
2225
+ const hookId = tracker.current.unique;
2226
+ registerStaleQuery(hookId, {
2227
+ queryKey,
2228
+ refetch,
2229
+ sequence: resetOnlySequence,
2230
+ });
2231
+
2232
+ return () => {
2233
+ unregisterStaleQuery(hookId);
2234
+ };
2235
+ }, [stale, queryKey, resetOnlySequence]);
2236
+
2090
2237
  /*
2091
2238
  * Fetch another variables page through the latest query runtime while
2092
2239
  * retaining a stable callback identity.
2093
2240
  */
2094
- const fetchMore = useCallback(
2095
- async (obj: GraphQLRequestOptions): Promise<any> => {
2096
- const queryRuntime = queryRuntimeRef.current;
2097
- if (queryRuntime.skip) {
2098
- return { skipped: true };
2099
- }
2241
+ const fetchMore = useCallback(async (obj: GraphQLRequestOptions): Promise<any> => {
2242
+ const queryRuntime = queryRuntimeRef.current;
2243
+ if (queryRuntime.skip) {
2244
+ return { skipped: true };
2245
+ }
2100
2246
 
2101
- const result = await queryRuntime.doQuery(obj?.variables);
2247
+ const result = await queryRuntime.doQuery(obj?.variables, 0, 0, obj?.signal);
2102
2248
 
2103
- if (result.error) {
2104
- return {
2105
- ...result,
2106
- error: normalizeServerError(result.error),
2107
- };
2108
- }
2249
+ if (result.error) {
2250
+ return {
2251
+ ...result,
2252
+ error: normalizeServerError(result.error),
2253
+ };
2254
+ }
2109
2255
 
2110
- return result;
2111
- },
2112
- [],
2113
- );
2256
+ return result;
2257
+ }, []);
2114
2258
 
2115
2259
  const queryData = useMemo(() => {
2116
2260
  if (!queryCacheSnapshotReady) {
2117
2261
  return {};
2118
2262
  }
2119
2263
 
2120
- return loadDataFromCache(
2121
- effectiveQueryData,
2122
- query,
2123
- variablesKey,
2124
- cacheMap,
2125
- eagerFragmentKeyMap,
2126
- false,
2127
- );
2128
- }, [
2129
- cacheMap,
2130
- eagerFragmentKeyMap,
2131
- effectiveQueryData,
2132
- query,
2133
- queryCacheSnapshotReady,
2134
- updatedCount,
2135
- variablesKey,
2136
- ]);
2264
+ return loadDataFromCache(effectiveQueryData, query, variablesKey, cacheMap, eagerFragmentKeyMap, false);
2265
+ }, [cacheMap, eagerFragmentKeyMap, effectiveQueryData, query, queryCacheSnapshotReady, updatedCount, variablesKey]);
2137
2266
 
2138
2267
  const resultData = queryData[queryName];
2139
2268
  const queryOutputRef = useRef<GraphQLQueryOutput>({
@@ -2168,6 +2297,8 @@ export function useQuery(
2168
2297
  data: hasFreshData ? queryData : queryOutput.data || queryData,
2169
2298
  refreshTime: hasFreshData ? refreshTime : queryOutput.refreshTime,
2170
2299
  resetOnlyTime,
2300
+ acknowledgedResetOnlyTime: qryValues.lastResetOnlyQueryKey === queryKey ? qryValues.lastResetOnlyTime : '',
2301
+ stale,
2171
2302
  variablesKey,
2172
2303
  refetch,
2173
2304
  fetchMore,
@@ -2183,13 +2314,87 @@ export function useQuery(
2183
2314
  * Helper: For development purposes; do not remove.
2184
2315
  */
2185
2316
 
2186
- // function getQueryName(query: any) {
2187
- // return query.definitions.filter((d: any) => d.kind === 'OperationDefinition').map(d => d.name.value).join(', ');
2188
- // }
2317
+ /*
2318
+ * Publish a new stale-queries snapshot to every subscriber.
2319
+ */
2320
+ function publishStaleQueries() {
2321
+ STALE_QUERIES_SNAPSHOT = {
2322
+ count: new Set(Array.from(STALE_QUERIES.values(), (entry) => entry.queryKey)).size,
2323
+ version: STALE_QUERIES_SNAPSHOT.version + 1,
2324
+ };
2325
+ STALE_QUERY_LISTENERS.forEach((listener) => {
2326
+ listener();
2327
+ });
2328
+ }
2189
2329
 
2190
- // function doLog(query: any, logStr: string) {
2191
- // const queryName = getQueryName(query);
2192
- // if (queryName === 'dataTableRowsForSheetRegions') {
2193
- // console.log(logStr.replace(/\$0/gi, queryName));
2194
- // }
2195
- // }
2330
+ /*
2331
+ * Register or update one mounted hook whose displayed result is stale.
2332
+ */
2333
+ function registerStaleQuery(hookId: string, entry: StaleQueryEntry) {
2334
+ const current = STALE_QUERIES.get(hookId);
2335
+ if (current && current.queryKey === entry.queryKey && current.sequence === entry.sequence) {
2336
+ current.refetch = entry.refetch;
2337
+ return;
2338
+ }
2339
+ STALE_QUERIES.set(hookId, entry);
2340
+ publishStaleQueries();
2341
+ }
2342
+
2343
+ /*
2344
+ * Remove one hook from the stale registry once it refreshed or unmounted.
2345
+ */
2346
+ function unregisterStaleQuery(hookId: string) {
2347
+ if (STALE_QUERIES.delete(hookId)) {
2348
+ publishStaleQueries();
2349
+ }
2350
+ }
2351
+
2352
+ /*
2353
+ * Subscribe to the stale-queries snapshot outside React.
2354
+ */
2355
+ function subscribeStaleQueries(listener: () => void) {
2356
+ STALE_QUERY_LISTENERS.add(listener);
2357
+ return () => {
2358
+ STALE_QUERY_LISTENERS.delete(listener);
2359
+ };
2360
+ }
2361
+
2362
+ /*
2363
+ * Return the current stale-queries snapshot.
2364
+ */
2365
+ function getStaleQueriesSnapshot() {
2366
+ return STALE_QUERIES_SNAPSHOT;
2367
+ }
2368
+
2369
+ /**
2370
+ * Observe how many mounted queries hold a stale result behind a RESET_ONLY
2371
+ * invalidation. `version` changes whenever the set or its generations change,
2372
+ * so a dismissed notice can return for a newer invalidation.
2373
+ */
2374
+ export function useStaleQueries(): StaleQueriesSnapshot {
2375
+ return useSyncExternalStore(subscribeStaleQueries, getStaleQueriesSnapshot, getStaleQueriesSnapshot);
2376
+ }
2377
+
2378
+ /**
2379
+ * Refetch every mounted stale query once per query key. Each hook acknowledges
2380
+ * its own RESET_ONLY generation when its fresh result lands and leaves the registry.
2381
+ */
2382
+ export function refetchStaleQueries(): Promise<unknown> {
2383
+ const refetches = new Map<string, () => Promise<any>>();
2384
+ for (const entry of STALE_QUERIES.values()) {
2385
+ if (!refetches.has(entry.queryKey)) {
2386
+ refetches.set(entry.queryKey, entry.refetch);
2387
+ }
2388
+ }
2389
+ return Promise.all(Array.from(refetches.values(), (refetch) => refetch()));
2390
+ }
2391
+
2392
+ /*
2393
+ * Subscribe to standard query invalidations for ephemeral consumers outside useQuery.
2394
+ */
2395
+ export function subscribeQueryObserverEvents(listener: (event: QueryObserverEventObj) => void) {
2396
+ QUERY_OBSERVER_LISTENERS.add(listener);
2397
+ return () => {
2398
+ QUERY_OBSERVER_LISTENERS.delete(listener);
2399
+ };
2400
+ }