@jsb188/graphql 1.1.11 → 1.1.12

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